from McUtils.GaussianInterface import GaussianLogReader, GaussianFChkReader
import numpy as np

class LogInterpreter:
    def __init__(self, *logs, method=None, **kwargs):
        self.params = kwargs
        if len(logs) == 0:
            raise Exception('Nothing to interpret.')
        self.logs = logs
        self.method = method
        self._atom_num = None  # should be atomic numbers
        self._atom_str = None  # should be atomic letters in order of atom_num
        self._energies = None  # np.ndarray of electronic energies from Gaussian
        self._finite_energies = None  # np.ndarray of electronic energies from bottom of oo wells
        self._cartesians = None  # dictionary of cartesian coordinates keyed by (x, y) distances
        self._zmatrices = None   # dictionary of z-matrix values keyed by (x, y) distances
        self._dipoles = None     # dictionary of dipole values keyed by (x, y) distances

    @property
    def energies(self):
        if self._energies is None:
            self._energies = self.get_electronic_energy(**self.params)
        return self._energies

    @property
    def finite_energies(self):
        if self._finite_energies is None:
            self._finite_energies = self.get_finitedata()
        return self._finite_energies

    @property
    def cartesians(self):
        if self._cartesians is None:
            self._atom_num, self._cartesians = self.get_scoords(**self.params)
        return self._cartesians

    @property
    def atom_num(self):
        if self._atom_num is None:
            self.cartesians
        return self._atom_num

    @property
    def atom_str(self):
        from McUtils.Data import AtomData
        if self._atom_str is None:
            self._atom_str = tuple(AtomData[int(an)]["Symbol"] for an in self.atom_num)
        return self._atom_str

    @property
    def zmatrices(self):
        if self._zmatrices is None:
            self._atom_str, self._atom_num, self._zmatrices = self.get_zmats(**self.params)
        return self._zmatrices

    @property
    def dipoles(self):
        if self._dipoles is None:
            self._dipoles = self.get_dips(**self.params)
        return self._dipoles

    def get_electronic_energy(self, shift=True, optimized=False, **params):
        """
        Currently, opens data file of grid points, soon.. should be able to pull the "Summary of the potential surface
        scan" (in which case there should be an option to multiply to roo distance). Also shifts the potential energy to
        0 to avoid problems with DVR later.
        :return: an array (col0: scancoord_1(ang), col1: scancoord_2(ang), col2: energy(shifted hartrees))
        :rtype: np.ndarray
        """
        ens = []
        for log in self.logs:
            if optimized:
                with GaussianLogReader(log) as reader:
                    parse = reader.parse("OptimizedScanEnergies")
                energy_array, coords = parse["OptimizedScanEnergies"]
                roo = coords['Roo12']
                roh = coords['Roh']
                ens.append(np.column_stack((roo, roh, energy_array)))
            else:
                with GaussianLogReader(log) as reader:
                    parse = reader.parse("ScanEnergies")
                ens.append(parse["ScanEnergies"])
        energy = np.concatenate(ens)
        energy[:, 0] *= 2
        idx = np.lexsort((energy[:, 1], energy[:, 0]))
        energy = energy[idx]
        row_mask = np.append([True], np.any(np.diff(energy, axis=0), 1))
        out = energy[row_mask]
        if shift:
            out[:, 2:] -= min(out[:, 2:])  # shift gaussian numbers to zero HERE to avoid headaches later.
        return out

    def get_finitedata(self):
        import os
        import glob as glob
        main_dir = os.path.dirname(os.path.dirname(__file__))
        FD_dir = os.path.join(main_dir, 'VAA', 'harmonic data', 'finite data')
        FD_scans = sorted(glob.glob(os.path.join(FD_dir, ('Egraph_%s_*.dat' % self.method))))
        oos = np.unique(np.array(list(self.cartesians.keys()))[:, 0])
        finite_energies = np.empty((0, 3), int)
        for oo, dat in zip(oos, FD_scans):
            pts = np.loadtxt(dat)
            oh = pts[:, 0]
            energy = pts[:, 1]
            rep_oo = np.repeat(oo, len(oh))
            vals = np.column_stack((rep_oo, oh, energy))
            finite_energies = np.append(finite_energies, vals, axis=0)
        finite_energies[:, 2:] -= min(finite_energies[:, 2:])
        return finite_energies

    def get_scoords(self, scancoord_1=None, scancoord_2=None, **params):
        """ pulls the optimized (if applicable) structures from  a 2D Gaussian scan.
        :param scancoord_1: x-coordinate of the scan
        :type scancoord_1: tuple
        :param scancoord_2: y-coordinate of the scan
        :type scancoord_2: tuple
        :return: atomnum:
        :return: cartesian coordinates at STANDARD optimized geometry keyed by the (scancoord_1, scancoord_2) distances.
        :rtype: OrderedDict
        """
        from collections import OrderedDict
        struct = OrderedDict()
        for log in self.logs:
            with GaussianLogReader(log) as reader:
                parse = reader.parse("StandardCartesianCoordinates")
            atomnum, ccs = parse["StandardCartesianCoordinates"]
            atomnum = [a[1] for a in atomnum]
            x_pos = scancoord_1
            xps = ccs[:, x_pos]
            xdiffs = np.diff(xps, axis=1)
            xdiffs = xdiffs.reshape((len(xdiffs), 3))
            xdists = np.linalg.norm(xdiffs, axis=1)
            xdists = np.around(xdists, 4)

            y_pos = scancoord_2
            yps = ccs[:, y_pos]
            ydiffs = np.diff(yps, axis=1)
            ydiffs = ydiffs.reshape((len(ydiffs), 3))
            ydists = np.linalg.norm(ydiffs, axis=1)
            ydists = np.around(ydists, 4)

            coords = zip(xdists, ydists, ccs)
            struct.update((((x, y), cc) for x, y, cc in coords))
        return atomnum, struct

    def get_zmats(self, zmat_coord=None):
        """ pulls the Z-Matrices from a 1D Gaussian scan
        :param zmat_coord: x-coordinate of the scan
        :type zmat_coord: tuple
        :return: Z-matrix values keyed by the coordinate distances.
        :rtype: OrderedDict
        """
        from collections import OrderedDict
        struct = OrderedDict()
        for log in self.logs:
            with GaussianLogReader(log) as reader:
                parse = reader.parse("ZMatrices")
            zmcs = parse["ZMatrices"]
            atomstr = np.array(list(zmcs[0]))
            atomstr = atomstr[:, 2]
            atomnum = zmcs[1]
            vals = zmcs[2]
            xps = vals[:, 0, zmat_coord]
            xdists = np.around(xps, 4)

            things = zip(xdists, vals)
            struct.update(((oo, zm) for oo, zm in things))
        return atomstr, atomnum, struct

    def get_crds_for_one(self, use_zmat=False, xdist=None, ydist=None):
        # should work with either cartesian coordinates or z matrices, does it?? who knows.
        """Takes the entire dictionary of structures of parses it for only one oo distance.
            :param use_zmat: if True, pulls Z-matrix value instead of Cartesian Coordinates
            :type  use_zmat: False
            :param xdist: x distance of coordinates pulled (ang)
            :type xdist: float (4 decimal places)
            :param ydist: y distance of coordinates pulled (ang)
            :type ydist: float (4 decimal places)
            :returns crds_for_one: standard cartesian coordinates for structure with xdist, ydist"""
        crds_for_one = ()
        if use_zmat:
            pos = list(self.zmatrices.keys())
            for x in pos:
                if x[0] == xdist and x[1] == ydist:
                    crds_for_one = self.zmatrices[x]
        else:
            pos = list(self.cartesians.keys())
            for x in pos:
                if x[0] == xdist and x[1] == ydist:
                    crds_for_one = self.cartesians[x]
        return crds_for_one

    def get_dips(self, optimized=False, **params):
        """Pulls the dipoles from a list of Gaussian log files
        :param optimized: if True, the list of log files are optimization scans
        :type optimized: bool
        :return: Dipole values keyed by the coordinate distances.
        :rtype: OrderedDict
        """
        from collections import OrderedDict
        struct = OrderedDict()
        for log in self.logs:
            with GaussianLogReader(log) as reader:
                parse = reader.parse(("OptimizedDipoleMoments", "DipoleMoments"))
            if optimized:
                dips = parse["OptimizedDipoleMoments"]
            else:
                dips = parse["DipoleMoments"]
            dips = np.array(list(dips))
            coord = LogInterpreter(log, scancoord_1=(0, 1), scancoord_2=(1, 2)).cartesians.keys()
            struct.update(((c, d) for c, d in zip(coord, dips)))
        return struct

    def cut_dictionary(self, midpoint=False, fillvalues=False, interp_kind='cubic', plot=False):
        """ creates a dictionary of cuts from POTENTIAL ENERGY SURFACES (scancoord_2 OR MIDPOINT scancoord_2)
            -- interpolates to a square if not already (in the y-coordinate) to make everyone's life easier
        :param midpoint: If true, calculates scancoord_2 to be the distance from the midpoint of scancoord_1
        :type midpoint: Bool
        :param fillvalues: If true, instead of extrapolating points outside of the grid are filled with the last data
        point on either side. When False, values are extrapolated via interp_kind
        :type fillvalues: Bool
        :param interp_kind: type of interpolation to do ('cubic' | 'linear' | 'nearest' | ...)
        :type interp_kind: str
        :param plot: If true, plots the extrapolated cuts for visualization purposes.
        :type plot: Bool
        :return: dictionary: {scancoord_1: (scancoord_2, energy)} (input units)
        :rtype: OrderedDict
        """
        from scipy import interpolate
        import matplotlib.pyplot as plt
        from collections import OrderedDict
        pes = self.energies
        xvals = np.unique(self.energies[:, 0])
        slices = [pes[self.energies[:, 0] == xv] for xv in xvals]
        slices = [slICE[slICE[:, 1].argsort()] for slICE in slices]
        maxx = max(len(slIce) for slIce in slices)
        idx = np.argmax([len(slIce) for slIce in slices])
        rnge = sorted(slices[idx][:, 1])
        cuts = OrderedDict()
        for slICE in slices:
            if len(slICE) < maxx:
                xx = np.repeat(slICE[0, 0], maxx)
                g = rnge
                if fillvalues:
                    f = interpolate.interp1d(slICE[:, 1], slICE[:, 2], kind=interp_kind,
                                             fill_value=(slICE[0, 2], slICE[-1, 2]), bounds_error=False)
                else:
                    f = interpolate.interp1d(slICE[:, 1], slICE[:, 2], kind=interp_kind,
                                             fill_value='extrapolate', bounds_error=False)
                y_fit = f(g)
                if plot:
                    plt.plot(g, y_fit, 'o')
                    plt.show()
                pice = np.column_stack((g, y_fit))
                if midpoint:
                    pice[:, 0] = (xx[0]/2) - pice[:, 0]
                    pice[:, 0] *= -1
                cuts[xx[0]] = pice
            else:
                if midpoint:
                    slICE[:, 1] = (slICE[0, 0]/2) - slICE[:, 1]
                    slICE[:, 1] *= -1
                cuts[slICE[0, 0]] = slICE[:, 1:]
        return cuts

    def finite_dict(self, midpoint=False):
        from collections import OrderedDict
        pes = self.finite_energies
        xvals = np.unique(self.finite_energies[:, 0])
        slices = [pes[self.finite_energies[:, 0] == xv] for xv in xvals]
        slices = [slICE[slICE[:, 1].argsort()] for slICE in slices]
        cuts = OrderedDict()
        for slICE in slices:
            if midpoint:
                slICE[:, 1] = (slICE[0, 0] / 2) - slICE[:, 1]
                slICE[:, 1] *= -1
            cuts[slICE[0, 0]] = slICE[:, 1:]
        return cuts

    def minimum_pot(self):
        """Calculates the minimum potential cut through the 2D scan. (to be used as electronic energy for plots and any
        harmonic approximations. So far hard coded to do "Roo12" and "Roh"
        :return: array (col0: scancoord_1, col1: scancoord_2, col1: energy)
        :rtype: np.ndarray
        """
        import os
        scan_dir = os.path.join(os.path.dirname(os.path.dirname(__file__)), '1D Scans')
        onedeescan = os.path.join(scan_dir, ("1D_%s_ooscan.log" % self.method))
        with GaussianLogReader(onedeescan) as reader:
            parse = reader.parse("OptimizedScanEnergies")
        energy_array, coords = (parse["OptimizedScanEnergies"])
        roo = coords['Roo12']*2
        roh = coords['Roh']
        ens = np.column_stack((roo, roh, energy_array))
        ens[:, 2:] -= min(ens[:, 2:])  # shift gaussian numbers to zero HERE to avoid headaches later.
        return ens

    def write_freq(self, use_zmat=False, coordinate=None, filename=None, config=None, variables=None):
        """ Writes and saves a gaussian gjf file for a frequency calculation
        :param use_zmat: if true, creates  gjf based off of a z_matrix, otherwise, uses cartesian coordinates.
        :type use_zmat: Bool
        :param coordinate: name of coordinate for file naming purposes
        :type coordinate: str
        :param filename: identifier for type of job ('rigid' |  'part_rig' | etc)
        :type filename: str
        :param config: use to change number of processors or memory allocated to job
        :type config: dict
        :param variables: set system constants
        :type variables: list of tuples
        :return: a gjf file
        :rtype: output file
        """
        from McUtils.GaussianInterface import GaussianJob
        if use_zmat:
            xdists = np.array(list(self.zmatrices.keys()))
            zmcs = np.array(list(self.zmatrices.values()))
        else:
            xdists = np.array(list(self.cartesians.keys()))[:, 0]
            zmcs = np.array(list(self.cartesians.values()))
        default_config = dict(NProc=4, Mem='1000MB')
        default_config.update(config if config is not None else dict())
        for i in range(0, len(xdists)):
            GaussianJob(
                "Frequency jobs",
                description="Freq for %s %.3f" % (coordinate, xdists[i]),
                file='%s_%sFreq_%.3f.gjf' % (filename, coordinate, xdists[i]),
                template="TemplateTerse.gjf",
                config=GaussianJob.Config(**default_config),
                job=GaussianJob.Job('Frequency'),
                system=GaussianJob.System(
                    charge=1,
                    molecule=[self.atom_str, (self.atom_num, zmcs[i])],
                    vars=[GaussianJob.System.Constant(*variables)]  # soft fix, ask mark about cases with multiple changes or no changes
                )
            ).write()

    def write_finitescan(self, config=None, variables=None):
        """ Writes and save a gaussian gjf file to conduct a scan with a small enough range for finite differencing
        :param config: use to change number of processors or memory allocated to job
        :type config: dict
        :param variables: set system constants
        :type variables: list of tuples
        :return: a gjf file
        :rtype: output file
        """
        from McUtils.GaussianInterface import GaussianJob
        xdists = np.array(list(self.zmatrices.keys()))
        zmcs = np.array(list(self.zmatrices.values()))
        default_config = dict(NProc=4, Mem='1000MB')
        default_config.update(config if config is not None else dict())
        yvals = zmcs[:, 3, 0]  # CHANGE THIS SOMEHOW
        for i in range(0, len(xdists)):
            # default_variables = [("dist4", (yvals[i] - 0.01), 4, .005)]
            # default_variables.extend(variables if variables is not None else [])
            GaussianJob(
                "Finite Difference scan jobs",
                description="FD Scan for Roo %.3f" % (xdists[i]*2),
                file='rigid_finiteSPE_%.3f.gjf' % (xdists[i]*2),
                template="TemplateTerse.gjf",
                config=GaussianJob.Config(**default_config),
                job=GaussianJob.Job('Scan'),
                system=GaussianJob.System(
                    charge=1,
                    molecule=[self.atom_str, (self.atom_num, zmcs[i])],
                    vars=[GaussianJob.System.Variable("dist4", (yvals[i] - 0.01), 4, .005),
                          GaussianJob.System.Constant("angle4", 0.00001)]
                )).write()

class FchkInterpreter:
    def __init__(self, *fchks, **kwargs):
        self.params = kwargs
        if len(fchks) == 0:
            raise Exception('Nothing to interpret.')
        self.fchks = fchks
        self._atom_str = None  # should be atomic letters, potentially derived from atom_num???
        self._atom_num = None  # should be atomic numbers in order of atom string
        self._hessian = None
        self._cartesians = None  # dictionary of cartesian coordinates keyed by (x, y) distances
        self._zmatrices = None  # dictionary of z-matrix values keyed by (x, y) distances

    @property
    def cartesians(self):
        if self._cartesians is None:
            self._cartesians = self.get_coords()
        return self._cartesians

    @property
    def hessian(self):
        if self._hessian is None:
            self._hessian = self.get_hess()
        return self._hessian

    def get_coords(self):
        """Uses McUtils parser to pull cartesian coordinates
            :returns coords: nx3 coordinate matrix"""
        for fchk in self.fchks:
            with GaussianFChkReader(fchk) as reader:
                parse = reader.parse("Coordinates")
            coords = parse["Coordinates"]
        return coords

    def get_hess(self):
        """Pulls the Hessian (Force Constants) from a Gaussian Frequency output file
            :arg chk_file: a Gaussian Frequency formatted checkpoint file
            :returns hess: full Hessian of system as an np.array"""
        for fchk in self.fchks:
            with GaussianFChkReader(fchk) as reader:
                parse = reader.parse("ForceConstants")
            forcies = parse["ForceConstants"]
        # ArrayPlot(forcies.array, colorbar=True).show()
        return forcies.array


from flask import Flask
from flask_restplus import Api, Resource, fields
import re

flask_app = Flask(__name__)
api = Api(app = flask_app)

def check_pyramid_word(word):
    word = word.lower()
    #check if what was given is a single word with no special characters
    if not word.isalpha():
        return False
    counts_list = [word.count(char) for char in set(word)]
    counts_list.sort()
    count = 1
    for integer in counts_list:
        if integer == count:
            count +=1
        else:
            break
    else:
        return True
    return False

@api.route('/pyramid/<string:word>', endpoint='pyramid')
@api.doc(
    description='Used to check if a given string meets the requirements for a valid pyramid string.',
    params={'word': 'The string you want to check.'}
    )
class PyramidWord(Resource):

    @api.response(200, 'Success', fields.Boolean)
    @api.response(500, 'Internal Server Error')
    def get(self, word):
        return check_pyramid_word(word)
        # return {'isPyramid': check_pyramid_word(word)}

if __name__ == '__main__':
    flask_app.run(port=5001, debug=True)


# To hide
# img = (covr >> n << n) | hide >> (8 - n)

# To extract
# img << (8-n)

from PIL import Image

def extract(source, lsb):
    image = Image.open(source).convert(mode = "RGB")
    pixels = image.load()
    for x in range(image.width):
        for y in range(image.height):
            r, g, b = pixels[x, y]
            r = 0xFF & (r << (8 - lsb))
            g = 0xFF & (g << (8 - lsb))
            b = 0xFF & (b << (8 - lsb))
            pixels[x, y] = (r, g, b)

    image.save('output.png')
    print("Image saved into output.png!")

    image.show()
    image.close()

def hide(medium, secret_image, lsb):
    medium_image = Image.open(medium).convert(mode = "RGB")

    orig_secretImage = Image.open(secret_image).convert(mode = "RGB")
    resized_secretImage = orig_secretImage.resize(medium_image.size)
    orig_secretImage.close()

    m_pixels = medium_image.load()
    s_pixels = resized_secretImage.load()

    result = Image.new("RGB", medium_image.size)
    r_pixels = result.load()

    for x in range(result.width):
        for y in range(result.height):
            o_r, o_g, o_b = m_pixels[x, y]
            s_r, s_g, s_b = s_pixels[x, y]

            r = (o_r >> lsb << lsb) | (s_r >> (8 - lsb))
            g = (o_g >> lsb << lsb) | (s_g >> (8 - lsb))
            b = (o_b >> lsb << lsb) | (s_b >> (8 - lsb))

            r_pixels[x, y] = r, g, b

    result.save('output.png')
    print("Image saved into output.png!")

    result.show()
    result.close()
    medium_image.close()
    resized_secretImage.close()

##########################################################
# The stuff below here already written for you!
# It's boring stuff that isn't really part of the activity
# ---
# Of course, feel free to poke around, and mess with it
# Your mentors will be able to help explain the code :)
##########################################################

if __name__ == "__main__":
    print("LSB Image in Image")
    print("==================")
    print("1. Hide           ")
    print("2. Extract        ")

    from tempfile import SpooledTemporaryFile
    from typing import Union

    def getFile(prompt: str) -> Union[str, SpooledTemporaryFile]:
      file = input(prompt)

      import os.path
      if os.path.isfile(file): return file

      import re
      if re.match("^https?://", file, re.IGNORECASE):
        print("Detected web link - downloading...")
        try:
          from urllib import request as urllib2
          import tempfile

          tmpFile = SpooledTemporaryFile()
          tmpFile.write(urllib2.urlopen(file).read())

          tmpFile.flush()
          return tmpFile
        except:
          print("Could not retrieve file at", file)

      return None

    def getIntInput(prompt: str, *args: [int]) -> int:
      number = input(prompt)
      if not number.isdigit(): return None

      number = int(number)
      if args and not number in args: return None

      return number

    while True:
        action = getIntInput("Enter an action > ", *(1,2))
        if action is None: continue

        if action == 1:
            medium = getFile("Enter the filename of the medium (image to hide into): ")
            if medium is None:
              print("Cannot find file")
              continue

            secret_image = getFile("Enter the filename of the secret image: ")
            if secret_image is None:
              print("Cannot find file")
              continue

            lsb = getIntInput("Enter the number of significant bits to modify (0-8): ", *range(9))
            if lsb is None:
              print("Invalid choice")
              continue

            hide(medium, secret_image, lsb)
            if type(medium) is SpooledTemporaryFile: medium.close()
            if type(secret_image) is SpooledTemporaryFile: secret_image.close()
        else:
            source = getFile("Enter the filename of the image to extract from: ")
            if source is None:
              print("Cannot find file")
              continue

            lsb = getIntInput("Enter the number of significant bits to analyse: ", *range(9))
            if lsb is None:
              print("Invalid choice")
              continue

            extract(source, lsb)
            if type(source) is SpooledTemporaryFile: source.close()
        break


import sqlite3

conexion= sqlite3.connect("dbPrueba.db")

cursor= conexion.cursor()
#tengo que usar el commit para ejecutar los cambios en los datos
"""cursor.execute("INSERT INTO Persona VALUES (null,'Julian','Perez')")
conexion.commit()
cursor.execute("INSERT INTO Persona VALUES (null,'Martina','Donadio')")
conexion.commit()"""
#para ejecutar muchos inserts seguidos:
personas=[
    ("Julian", "Perez"),
    ("Martina","Donadio"),
    ("Freya","Perez Donadio"),
]
cursor.executemany("INSERT INTO Persona VALUES(null,?,?)",personas)
conexion.commit()
cursor.execute("SELECT * FROM Persona")
persona= cursor.fetchall()
for p in persona:
    print("Se llama",p[1],p[2])
conexion.close()

curso python/base de datos/sqllite sintaxis.py


import os
from flask import Flask, request, redirect, url_for
from werkzeug import secure_filename
from flask import send_from_directory
from celery_tasks import process
UPLOAD_FOLDER = './uploads'
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

def allowed_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

@app.route('/', methods=['GET', 'POST'])
def upload_file():
    if request.method == 'POST':
        file = request.files['file']
        if file and allowed_file(file.filename):
            filename = secure_filename(file.filename)
            process(filename, file.read())
            return "Thank you for your upload... It is being processed."
    return '''
    <!doctype html>
    <title>Upload new File</title>

Upload new File

    <form action="" method=post enctype=multipart/form-data>

<input type=file name=file>
         <input type=submit value=Upload>
    </form>
    '''

@app.route('/uploads/<filename>')
def uploaded_file(filename):
    return send_from_directory(app.config['UPLOAD_FOLDER'],
                               filename)

if __name__ == '__main__':
    app.run(debug=True)


import numpy as np
import pandas as pd
import os
import csv
import shutil
from nltk import word_tokenize, sent_tokenize
from nltk.tokenize import RegexpTokenizer
from nltk import bigrams, trigrams
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
import string

class Preprocessing():
    def __init__(self, data_path):
        super().__init__()
        if os.path.isdir('result'):
            shutil.rmtree('result')
        os.makedirs('result')
        self.list_path = []
        self.read_through(data_path=data_path)
        self.stopwords = stopwords.words("english")

        # Task 1: Process all debates into two datasets: "Oral questions" and "Statements By Members"
        self.create_csv()
        self.write_csv()

        # Step 2: Remove duplicate rows in the two dataset if any
        self.remove_duplicated_words(source_file='result/oral_questions.csv',
                                     new_file='result/unduplicated_oral_questions.csv')
        self.remove_duplicated_words(source_file='result/statements_by_members.csv',
                                     new_file='result/unduplicated_statements_by_members.csv')

        self.frequent_word_OQ = []
        self.frequent_word_OQ.append(
            self.unique_word(csv_file="result/oral_questions.csv", record_file="result/OQ_10_most_occurring_words.csv"))
        self.frequent_word_OQ.append(self.unique_two_word(csv_file="result/oral_questions.csv",
                                                          record_file="result/OQ_10_most_occurring_two_words.csv"))
        self.frequent_word_OQ.append(self.unique_three_word(csv_file="result/oral_questions.csv",
                                                            record_file="result/OQ_10_most_occurring_three_words.csv"))

        self.frequent_word_SBM = []
        self.frequent_word_SBM.append(self.unique_word(csv_file="result/statements_by_members.csv",
                                                       record_file="result/SBM_10_most_occurring_words.csv"))
        self.frequent_word_SBM.append(self.unique_two_word(csv_file="result/statements_by_members.csv",
                                                           record_file="result/SBM_10_most_occurring_two_words.csv"))
        self.frequent_word_SBM.append(self.unique_three_word(csv_file="result/statements_by_members.csv",
                                                             record_file="result/SBM_10_most_occurring_three_words.csv"))

        # print("10 most occurring words: ", unique_one_words)
        # print("10 most occurring two sequential words: ", unique_two_words)
        # print("10 most occurring three sequential words: ", unique_three_words)

        self.summary_report(file_name='result/summary.txt')

    def read_through(self, data_path):
        for root, directory, files in os.walk(data_path):
            for folder in directory:
                self.read_through(folder)
            for file in files:
                self.list_path.append(root + "/" + os.path.relpath(file))

    def create_csv(self):
        if os.path.isfile("result/oral_questions.csv"):
            os.remove("result/oral_questions.csv")
        else:
            with open("result/oral_questions.csv", mode="a", encoding="utf-8") as csvfile:
                field = ["basepk", "hid", "speechdate", "pid", "opid", "speakeroldname", "speakerposition", "maintopic",
                         "subtopic", "subsubtopic", "speechtext", "speakerparty", "speakerriding", "speakername",
                         "speakerurl"]
                csv_file = csv.DictWriter(f=csvfile, fieldnames=field)
                csv_file.writeheader()
            csvfile.close()

        if os.path.isfile("result/statements_by_members.csv"):
            os.remove("result/statements_by_members.csv")
        else:
            with open("result/statements_by_members.csv", mode="a", encoding="utf-8") as csvfile:
                field = ["basepk", "hid", "speechdate", "pid", "opid", "speakeroldname", "speakerposition", "maintopic",
                         "subtopic", "subsubtopic", "speechtext", "speakerparty", "speakerriding", "speakername",
                         "speakerurl"]
                csv_file = csv.DictWriter(f=csvfile, fieldnames=field)
                csv_file.writeheader()
            csvfile.close()

    def write_csv(self):
        for file_path in self.list_path:
            data = pd.read_csv(filepath_or_buffer=file_path, header=0).values
            for row in data:
                if str(row[7]) == "Oral Questions":
                    with open("result/oral_questions.csv", mode="a", encoding="utf-8") as csv_file:
                        writer = csv.writer(csv_file)
                        writer.writerow(row)
                    csv_file.close()
                elif str(row[7]) == "Statements By Members":
                    with open("result/statements_by_members.csv", mode="a", encoding="utf-8") as csv_file:
                        writer = csv.writer(csv_file)
                        writer.writerow(row)
                    csv_file.close()
                else:
                    pass

    # Report 10 most occurring words
    def unique_word(self, csv_file, num_word=10, record_file="result/OQ_10_most_occurring_words.csv"):
        all_words = []
        unique_words = {}
        data_text = pd.read_csv(filepath_or_buffer=csv_file).values
        data_text = [str(record[10]).lower() for record in data_text]
        for record in data_text:
            for sent in sent_tokenize(text=record):
                for word in word_tokenize(text=sent):
                    if word not in self.stopwords:
                        all_words.append(word)

        # porter = PorterStemmer()
        # all_word = [porter.stem(word) for word in all_words]

        for word in all_words:
            if word in string.punctuation:
                continue
            if word not in unique_words.keys():
                unique_words[word] = 1
            else:
                unique_words[word] += 1

        self.record_words(path=record_file, list_words=unique_words)
        word_dict = sorted(unique_words, key=unique_words.get, reverse=True)[0:num_word]

        return word_dict

    # 10 most occurring two sequential words
    def unique_two_word(self, csv_file, num_word=10, record_file="result/OQ_10_most_occurring_two_words.csv"):
        data_text = pd.read_csv(filepath_or_buffer=csv_file).values
        data_text = [str(record[10]).lower() for record in data_text]

        tokenizer = RegexpTokenizer(r'\w+')
        data_text = [tokenizer.tokenize(record) for record in data_text]
        data_text = [[item for item in record if item not in self.stopwords] for record in data_text]
        data_text = [" ".join(record) for record in data_text]
        data_text = [bigrams(sequence=record.split()) for record in data_text]
        data_text = [["{} {}".format(item[0], item[1]) for item in record] for record in data_text]
        all_two_words = []
        unique_two_words = {}
        for record in data_text:
            for item in record:
                all_two_words.append(item)
        for item in all_two_words:
            if item not in unique_two_words.keys():
                unique_two_words[item] = 1
            else:
                unique_two_words[item] += 1

        self.record_words(path=record_file, list_words=unique_two_words)
        word_dict = sorted(unique_two_words, key=unique_two_words.get, reverse=True)[0:num_word]

        return word_dict

    # 10 most occurring two sequential words
    def unique_three_word(self, csv_file, num_word=10, record_file="result/OQ_10_most_occurring_three_words.csv"):
        data_text = pd.read_csv(filepath_or_buffer=csv_file).values
        data_text = [str(record[10]).lower() for record in data_text]

        tokenizer = RegexpTokenizer(r'\w+')
        data_text = [tokenizer.tokenize(record) for record in data_text]
        data_text = [[item for item in record if item not in self.stopwords] for record in data_text]
        data_text = [" ".join(record) for record in data_text]
        data_text = [trigrams(sequence=record.split()) for record in data_text]
        data_text = [["{} {} {}".format(item[0], item[1], item[2]) for item in record] for record in data_text]
        all_three_words = []
        unique_three_words = {}
        for record in data_text:
            for item in record:
                all_three_words.append(item)
        for item in all_three_words:
            if item not in unique_three_words.keys():
                unique_three_words[item] = 1
            else:
                unique_three_words[item] += 1

        self.record_words(path=record_file, list_words=unique_three_words)
        word_dict = sorted(unique_three_words, key=unique_three_words.get, reverse=True)[0:num_word]

        return word_dict

    def remove_duplicated_words(self, source_file='result/oral_questions.csv', keep_record="first",
                                new_file='result/unduplicated_oral_questions.csv'):
        df = pd.read_csv(filepath_or_buffer=source_file, header=0)
        df.drop_duplicates(inplace=True, subset='speechtext', keep=keep_record)
        df.to_csv(new_file, index=False)

    def record_words(self, path, list_words):
        with open(path, mode="a", encoding="utf-8") as csv_file:
            for w in sorted(list_words, key=list_words.get, reverse=True):
                row = "{}, {}".format(w, list_words[w])
                csv_file.write(row + "\n")
        csv_file.close()

    def summary_report(self, file_name):
        with open(file=file_name, mode='a', encoding="utf-8") as text_file:
            text_file.write("Summary of PreProcessing \n")
            # text_file.write("Data of Oral questions: {} \n".format(os.path.abspath(path='oral_questions.csv')))
            # text_file.write(
            #     "Data of Statements By Members: {} \n".format(os.path.abspath(path='statements_by_members.csv')))
            text_file.write("\n")
            text_file.write("In Oral_Questions \n")

            data_file = pd.read_csv(filepath_or_buffer='result/oral_questions.csv', header=0).values
            text_file.write("Before Removing duplicate rows, the number of row: {} \n".format(len(data_file)))

            data_file = pd.read_csv(filepath_or_buffer='result/unduplicated_oral_questions.csv', header=0).values
            text_file.write("After Removing duplicate rows, the number of row: {} \n".format(len(data_file)))

            text_file.write("\n")
            text_file.write("In Statements By Members \n")
            data_file = pd.read_csv(filepath_or_buffer='result/statements_by_members.csv', header=0).values
            text_file.write("Before Removing duplicate rows, the number of row: {} \n".format(len(data_file)))

            data_file = pd.read_csv(filepath_or_buffer='result/unduplicated_statements_by_members.csv', header=0).values
            text_file.write("After Removing duplicate rows, the number of row: {} \n \n".format(len(data_file)))

            text_file.write("10 most occurring words in Oral Questions \n")
            text_file.write('{} \n'.format(self.frequent_word_OQ[0]))

            text_file.write("10 most occurring two sequential words in Oral Questions \n")
            text_file.write('{} \n'.format(self.frequent_word_OQ[1]))

            text_file.write("10 most occurring three sequential words in Oral Questions \n")
            text_file.write('{} \n'.format(self.frequent_word_OQ[2]))

            text_file.write('\n')

            text_file.write("10 most occurring words in Statements By Members \n")
            text_file.write('{} \n'.format(self.frequent_word_SBM[0]))

            text_file.write("10 most occurring two sequential words in Statements By Members \n")
            text_file.write('{} \n'.format(self.frequent_word_SBM[1]))

            text_file.write("10 most occurring three sequential words in Statements By Members \n")
            text_file.write('{} \n'.format(self.frequent_word_SBM[2]))

if __name__ == '__main__':
    Preprocessing(data_path="../data/lipad")


import cv2
import matplotlib.pyplot as plt
import cvlib as cv
from cvlib.object_detection import draw_bbox
import time

boundingBOX = ()
cap = cv2.VideoCapture(0)

tracker = cv2.TrackerCSRT_create()
success, img = cap.read()
bbox, labels, conf = cv.detect_common_objects(img)

# output_image = draw_bbox(img, bbox, labels, conf)
# plt.imshow(output_image)
# plt.show()

try:
    i = tuple(labels).index("sports ball")
    newBBOX = (bbox[i][0], bbox[i][1], bbox[i][2] - bbox[i][0], bbox[i][3] - bbox[i][1])
    boundingBOX = newBBOX
except:
    print("billy")
    bbox = cv2.selectROI("Tracking", img, False)
    boundingBOX = bbox

print(labels)

tracker.init(img, boundingBOX)

def drawbox(img, bbox):
    x, y, w, h = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3])
    cv2.rectangle(img, (x, y), ((x + w), (y + h)), (255, 0, 255), 3, 1)
    cv2.putText(img, "Tracking", (75, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

while True:
    # Capture the video frame
    # by frame
    timer = cv2.getTickCount()
    success, img = cap.read()

    success2, bbox = tracker.update(img)
    print(success2)
    if success2:
        drawbox(img, bbox)
    else:
        cv2.putText(img, "Lost", (75, 75), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)
        time.sleep(5.0)
        bbox = cv2.selectROI("Tracking", img, False)
        tracker.init(img, bbox)

    fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)
    cv2.putText(img, 'Ball', (75, 50), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2)

    cv2.imshow('img', img)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# After the loop release the cap object
cap.release()
# Destroy all the windows
cv2.destroyAllWindows()


#!/usr/bin/env python

"""
$Id: takeover.py 1465 2010-03-13 10:44:24Z stamparm $

This file is part of the sqlmap project, http://sqlmap.sourceforge.net.

Copyright (c) 2007-2010 Bernardo Damele A. G. <bernardo.damele@gmail.com>
Copyright (c) 2006 Daniele Bellucci <daniele.bellucci@gmail.com>

sqlmap is free software; you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free
Software Foundation version 2 of the License.

sqlmap is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
details.

You should have received a copy of the GNU General Public License along
with sqlmap; if not, write to the Free Software Foundation, Inc., 51
Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
"""

import os
import re

from lib.core.agent import agent
from lib.core.common import decloakToNamedTemporaryFile
from lib.core.common import fileToStr
from lib.core.common import getDirs
from lib.core.common import getDocRoot
from lib.core.common import randomStr
from lib.core.common import readInput
from lib.core.convert import hexencode
from lib.core.data import conf
from lib.core.data import kb
from lib.core.data import logger
from lib.core.data import paths
from lib.core.exception import sqlmapNotVulnerableException
from lib.core.exception import sqlmapUnsupportedDBMSException
from lib.core.shell import autoCompletion
from lib.request.connect import Connect as Request
from lib.takeover.abstraction import Abstraction
from lib.takeover.metasploit import Metasploit
from lib.takeover.registry import Registry
from lib.techniques.outband.stacked import stackedTest

class Takeover(Abstraction, Metasploit, Registry):
    """
    This class defines generic OS takeover functionalities for plugins.
    """

    def __init__(self):
        self.cmdTblName       = "sqlmapoutput"
        self.tblField         = "data"

        Abstraction.__init__(self)

    def osCmd(self):
        stackedTest()

        if kb.stackedTest:
            web = False
        elif not kb.stackedTest and kb.dbms == "MySQL":
            infoMsg = "going to use a web backdoor for command execution"
            logger.info(infoMsg)

            web = True
        else:
            errMsg  = "unable to execute operating system commands via "
            errMsg += "the back-end DBMS"
            raise sqlmapNotVulnerableException(errMsg)

        self.initEnv(web=web)

        if not web or (web and self.webBackdoorUrl is not None):
            self.runCmd(conf.osCmd)

        if not conf.osShell and not conf.osPwn and not conf.cleanup:
            self.cleanup()

    def osShell(self):
        stackedTest()

        if kb.stackedTest:
            web = False
        elif not kb.stackedTest and kb.dbms == "MySQL":
            infoMsg = "going to use a web backdoor for command prompt"
            logger.info(infoMsg)

            web = True
        else:
            errMsg  = "unable to prompt for an interactive operating "
            errMsg += "system shell via the back-end DBMS"
            raise sqlmapNotVulnerableException(errMsg)

        self.initEnv(web=web)

        if not web or (web and self.webBackdoorUrl is not None):
            self.shell()

        if not conf.osPwn and not conf.cleanup:
            self.cleanup()

    def osPwn(self):
        goUdf = False

        stackedTest()

        if kb.stackedTest:
            web = False

            self.initEnv(web=web)
            self.getRemoteTempPath()

            if kb.dbms in ( "MySQL", "PostgreSQL" ):
                msg  = "how do you want to execute the Metasploit shellcode "
                msg += "on the back-end database underlying operating system?"
                msg += "\n[1] Via UDF 'sys_bineval' (in-memory way, anti-forensics, default)"
                msg += "\n[2] Stand-alone payload stager (file system way)"

                while True:
                    choice = readInput(msg, default=1)

                    if isinstance(choice, str) and choice.isdigit() and int(choice) in ( 1, 2 ):
                        choice = int(choice)
                        break

                    elif isinstance(choice, int) and choice in ( 1, 2 ):
                        break

                    else:
                        warnMsg = "invalid value, valid values are 1 and 2"
                        logger.warn(warnMsg)

                if choice == 1:
                    goUdf = True

            if goUdf:
                self.createMsfShellcode(exitfunc="thread", format="raw", extra="BufferRegister=EAX", encode="x86/alpha_mixed")
            else:
                self.createMsfPayloadStager()
                self.uploadMsfPayloadStager()

            if kb.os == "Windows" and conf.privEsc:
                if kb.dbms == "MySQL":
                    debugMsg  = "by default MySQL on Windows runs as SYSTEM "
                    debugMsg += "user, no need to privilege escalate"
                    logger.debug(debugMsg)

            elif kb.os != "Windows" and conf.privEsc:
                # Unset --priv-esc if the back-end DBMS underlying operating
                # system is not Windows
                conf.privEsc = False

                warnMsg  = "sqlmap does not implement any operating system "
                warnMsg += "user privilege escalation technique when the "
                warnMsg += "back-end DBMS underlying system is not Windows"
                logger.warn(warnMsg)

        elif not kb.stackedTest and kb.dbms == "MySQL":
            infoMsg  = "going to use a web backdoor to execute the "
            infoMsg += "payload stager"
            logger.info(infoMsg)

            web = True

            self.initEnv(web=web)

            if self.webBackdoorUrl:
                if kb.os != "Windows" and conf.privEsc:
                    # Unset --priv-esc if the back-end DBMS underlying operating
                    # system is not Windows
                    conf.privEsc = False

                    warnMsg  = "sqlmap does not implement any operating system "
                    warnMsg += "user privilege escalation technique when the "
                    warnMsg += "back-end DBMS underlying system is not Windows"
                    logger.warn(warnMsg)

                self.getRemoteTempPath()
                self.createMsfPayloadStager()
                self.uploadMsfPayloadStager(web=True)
        else:
            errMsg  = "unable to prompt for an out-of-band session via "
            errMsg += "the back-end DBMS"
            raise sqlmapNotVulnerableException(errMsg)

        if not web or (web and self.webBackdoorUrl is not None):
            self.pwn(goUdf)

        if not conf.cleanup:
            self.cleanup()

    def osSmb(self):
        stackedTest()

        self.checkDbmsOs()

        if kb.os != "Windows":
            errMsg  = "the back-end DBMS underlying operating system is "
            errMsg += "not Windows: it is not possible to perform the SMB "
            errMsg += "relay attack"
            raise sqlmapUnsupportedDBMSException(errMsg)

        if not kb.stackedTest:
            if kb.dbms in ( "PostgreSQL", "Microsoft SQL Server" ):
                errMsg  = "on this back-end DBMS it is only possible to "
                errMsg += "perform the SMB relay attack if stacked "
                errMsg += "queries are supported"
                raise sqlmapUnsupportedDBMSException(errMsg)

            elif kb.dbms == "MySQL":
                debugMsg  = "since stacked queries are not supported, "
                debugMsg += "sqlmap is going to perform the SMB relay "
                debugMsg += "attack via inference blind SQL injection"
                logger.debug(debugMsg)

        printWarn = True
        warnMsg   = "it is unlikely that this attack will be successful "

        if kb.dbms == "MySQL":
            warnMsg += "because by default MySQL on Windows runs as "
            warnMsg += "Local System which is not a real user, it does "
            warnMsg += "not send the NTLM session hash when connecting to "
            warnMsg += "a SMB service"

        elif kb.dbms == "PostgreSQL":
            warnMsg += "because by default PostgreSQL on Windows runs "
            warnMsg += "as postgres user which is a real user of the "
            warnMsg += "system, but not within the Administrators group"

        elif kb.dbms == "Microsoft SQL Server" and kb.dbmsVersion[0] in ( "2005", "2008" ):
            warnMsg += "because often Microsoft SQL Server %s " % kb.dbmsVersion[0]
            warnMsg += "runs as Network Service which is not a real user, "
            warnMsg += "it does not send the NTLM session hash when "
            warnMsg += "connecting to a SMB service"

        else:
            printWarn = False

        if printWarn:
            logger.warn(warnMsg)

        self.smb()

    def osBof(self):
        stackedTest()

        if not kb.stackedTest:
            return

        if not kb.dbms == "Microsoft SQL Server" or kb.dbmsVersion[0] not in ( "2000", "2005" ):
            errMsg  = "the back-end DBMS must be Microsoft SQL Server "
            errMsg += "2000 or 2005 to be able to exploit the heap-based "
            errMsg += "buffer overflow in the 'sp_replwritetovarbin' "
            errMsg += "stored procedure (MS09-004)"
            raise sqlmapUnsupportedDBMSException(errMsg)

        infoMsg  = "going to exploit the Microsoft SQL Server %s " % kb.dbmsVersion[0]
        infoMsg += "'sp_replwritetovarbin' stored procedure heap-based "
        infoMsg += "buffer overflow (MS09-004)"
        logger.info(infoMsg)

        self.initEnv(mandatory=False, detailed=True)
        self.getRemoteTempPath()
        self.createMsfShellcode(exitfunc="seh", format="raw", extra="-b 27", encode=True)
        self.bof()

    def __regInit(self):
        stackedTest()

        if not kb.stackedTest:
            return

        self.checkDbmsOs()

        if kb.os != "Windows":
            errMsg  = "the back-end DBMS underlying operating system is "
            errMsg += "not Windows"
            raise sqlmapUnsupportedDBMSException(errMsg)

        self.initEnv()
        self.getRemoteTempPath()

    def regRead(self):
        self.__regInit()

        if not conf.regKey:
            default = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion"
            msg     = "which registry key do you want to read? [%s] " % default
            regKey  = readInput(msg, default=default)
        else:
            regKey = conf.regKey

        if not conf.regVal:
            default = "ProductName"
            msg     = "which registry key value do you want to read? [%s] " % default
            regVal  = readInput(msg, default=default)
        else:
            regVal = conf.regVal

        infoMsg = "reading Windows registry path '%s\%s' " % (regKey, regVal)
        logger.info(infoMsg)

        return self.readRegKey(regKey, regVal, True)

    def regAdd(self):
        self.__regInit()

        errMsg = "missing mandatory option"

        if not conf.regKey:
            msg    = "which registry key do you want to write? "
            regKey = readInput(msg)

            if not regKey:
                raise sqlmapMissingMandatoryOptionException(errMsg)
        else:
            regKey = conf.regKey

        if not conf.regVal:
            msg    = "which registry key value do you want to write? "
            regVal = readInput(msg)

            if not regVal:
                raise sqlmapMissingMandatoryOptionException(errMsg)
        else:
            regVal = conf.regVal

        if not conf.regData:
            msg     = "which registry key value data do you want to write? "
            regData = readInput(msg)

            if not regData:
                raise sqlmapMissingMandatoryOptionException(errMsg)
        else:
            regData = conf.regData

        if not conf.regType:
            default = "REG_SZ"
            msg     = "which registry key value data-type is it? "
            msg    += "[%s] " % default
            regType = readInput(msg, default=default)
        else:
            regType = conf.regType

        infoMsg  = "adding Windows registry path '%s\%s' " % (regKey, regVal)
        infoMsg += "with data '%s'. " % regData
        infoMsg += "This will work only if the user running the database "
        infoMsg += "process has privileges to modify the Windows registry."
        logger.info(infoMsg)

        self.addRegKey(regKey, regVal, regType, regData)

    def regDel(self):
        self.__regInit()

        errMsg = "missing mandatory option"

        if not conf.regKey:
            msg    = "which registry key do you want to delete? "
            regKey = readInput(msg)

            if not regKey:
                raise sqlmapMissingMandatoryOptionException(errMsg)
        else:
            regKey = conf.regKey

        if not conf.regVal:
            msg    = "which registry key value do you want to delete? "
            regVal = readInput(msg)

            if not regVal:
                raise sqlmapMissingMandatoryOptionException(errMsg)
        else:
            regVal = conf.regVal

        message  = "are you sure that you want to delete the Windows "
        message += "registry path '%s\%s? [y/N] " % (regKey, regVal)
        output   = readInput(message, default="N")

        if output and output[0] not in ( "Y", "y" ):
            return

        infoMsg  = "deleting Windows registry path '%s\%s'. " % (regKey, regVal)
        infoMsg += "This will work only if the user running the database "
        infoMsg += "process has privileges to modify the Windows registry."
        logger.info(infoMsg)

        self.delRegKey(regKey, regVal)


from flask import Blueprint, request
from flask_login import login_required, current_user
from ToCTF.extensions import re_template
from ToCTF.models import db, Challenge, Record, Type as C_type

challenge_view = Blueprint('challenges', __name__)

def record(user, clg, right, answer):
    _record = Record(user.id, clg.id, right, answer)
    if right:
        user.score = user.score + clg.score
        db.session.add(user)
    db.session.add(_record)
    db.session.commit()

@challenge_view.route('/', methods=['GET', 'POST'])
def home():
    c_list = Challenge.query.all()
    c_types = C_type.query.all()
    return re_template('challenge/home.html', clist=c_list, ctypes=c_types)

@challenge_view.route('/<_id>', methods=['GET', 'POST'])
@login_required
def challenge(_id):
    clg = Challenge.query.filter_by(id=_id).all()
    # 题目检测
    if not clg:
        return re_template('challenge/challenge.html', mess='不存在此题目!')
    clg = clg[0]
    # 返回题目信息
    if request.method == 'GET':
        return re_template('challenge/challenge.html', mess=clg.title)
    # 校验答案
    answer = request.form.get('answer')
    name = request.form.get('name')
    flag = clg.flag.split(',')
    if answer in flag:
        if not Record.query.filter_by(user=current_user, challenge=clg, right=True).all() != []:
            record(current_user, clg, True, answer)
            mess = '答案正确'
        else:
            mess = '答案正确,请不要重复提交'
    else:
        record(current_user, clg, False, answer)
        mess = '答案错误,再想一想'

    return re_template('challenge/challenge.html', mess=mess, name=name)


# -*- coding: utf-8 -*-
from util import *

CHEBISHEV = 0
LEGENDRE = 1
LAGUERRE = 2
HERMITE = 3

def print_psi(file, lamb, polynom_type, dimensions, degrees, startdegrees):
    """print functions psi"""
    if polynom_type == CHEBISHEV:
        letter = "T"
    elif polynom_type == LEGENDRE:
        letter = "P"
    elif polynom_type == LAGUERRE:
        letter = "L"
    elif polynom_type == HERMITE:
        letter = "H"
    f = open(file, "a")
    f.write("Третий иерархический уровень - функции Psi[k,jk] (k - № вектора, jk - № координаты):\n")
    for i in xrange(lamb.shape[0]):
        f.write("i = %d\n" % (i + 1))
        for k in xrange(3):
            for jk in xrange(dimensions[k]):
                f.write("Psi[%d,%d](x%d%d) = " % (k + 1, jk + 1, k + 1, jk + 1))
                f.write("%.6f*%s%d(x%d%d)" % (
                    lamb[i][pos_of_xi_in_all(k, dimensions, degrees) + jk * (degrees[k] + 1)], letter, startdegrees[k],
                    k + 1, jk + 1))
                for l in xrange(1, degrees[k] + 1):
                    if lamb[i][pos_of_xi_in_all(k, dimensions, degrees) + jk * (degrees[k] + 1) + l] >= 0:
                        sign = "+"
                    else:
                        sign = "-"
                    f.write(" %s %.6f*%s%d(x%d%d)" % (
                        sign, abs(lamb[i][pos_of_xi_in_all(k, dimensions, degrees) + jk * (degrees[k] + 1) + l]),
                        letter,
                        l + startdegrees[k], k + 1, jk + 1))
                f.write("\n")
    f.write("\n")
    f.close()

def print_Fij(file, a, dimensions):
    """print functions psi"""
    f = open(file, "a")
    f.write("Второй иерархический уровень - функции Фik через функции Psi[k,jk]:\n")
    for i in xrange(a.shape[0]):
        f.write("i = %d\n" % (i + 1))
        for k in xrange(3):
            f.write("Ф%d%d(x%d) = " % (i + 1, k + 1, k + 1))
            f.write("%.6f*Psi%d%d(x%d%d)" % (a[i][pos_of_xi_in_x(k, dimensions)], k + 1, 1, k + 1, 1))
            for j in xrange(1, dimensions[k]):
                if a[i][pos_of_xi_in_x(k, dimensions) + j] >= 0:
                    sign = "+"
                else:
                    sign = "-"
                f.write(" %s %.6f*Psi%d%d(x%d%d)" % (
                    sign, abs(a[i][pos_of_xi_in_x(k, dimensions) + j]), k + 1, j + 1, k + 1, j + 1))
            f.write("\n")
    f.write("\n")
    f.close()

def print_Fi_through_Fij(file, c):
    """print Fi through Fij"""
    f = open(file, "a")
    f.write("Верхний иерархический уровень - восстановленные функции Фi, выраженные через функции Фij:\n")
    for i in xrange(c.shape[0]):
        f.write("Ф%d(x1,x2,x3) = " % (i + 1))
        f.write("%.6f*Ф%d%d(x%d)" % (c[i][0], i + 1, 1, 1))
        for j in xrange(1, c.shape[1]):
            if c[i][j] >= 0:
                sign = "+"
            else:
                sign = "-"
            f.write(" %s %.6f*Ф%d%d(x%d)" % (sign, abs(c[i][j]), i + 1, j + 1, j + 1))
        f.write("\n")
    f.write("\n")
    f.close()

def print_Fi_through_polynomials(file, F_pol_coef, polynom_type, dimensions, degrees, startdegrees):
    """prints Fi through polynomials"""
    name = letter = ""
    if polynom_type == CHEBISHEV:
        name = "Чебышева"
        letter = "T"
    elif polynom_type == LEGENDRE:
        name = "Лежандра"
        letter = "P"
    elif polynom_type == LAGUERRE:
        name = "Лагерра"
        letter = "L"
    elif polynom_type == HERMITE:
        name = "Эрмита"
        letter = "H"

    f = open(file, "a")
    f.write("Восстановленные функции Фi, выраженные через полиномы %s:\n" % name)
    for i in xrange(F_pol_coef.shape[0]):
        f.write("Ф%d(x1,x2,x3) = " % (i + 1))
        for j in xrange(3):
            for k in xrange(dimensions[j]):
                for l in xrange(degrees[j] + 1):
                    if j == 0 and k == 0 and l == 0:
                        f.write("%.6f*%s%d(x%d%d)" % (F_pol_coef[i][0], letter, startdegrees[0], 1, 1))
                    else:
                        if F_pol_coef[i][pos_of_xi_in_all(j, dimensions, degrees) + k * (degrees[j] + 1) + l] >= 0:
                            sign = "+"
                        else:
                            sign = "-"
                        f.write(" %s %.6f*%s%d(x%d%d)" % (
                            sign,
                            abs(F_pol_coef[i][pos_of_xi_in_all(j, dimensions, degrees) + k * (degrees[j] + 1) + l]),
                            letter, startdegrees[j] + l, j + 1, k + 1))
        f.write("\n")
    f.write("\n")
    f.close()

def print_Fi_through_coord_coef(file, F_coord_coef, normed, dimensions, degrees, startdegrees):
    """prints Fi through coordinates (normed or initial)"""
    f = open(file, "a")
    enddegrees = (startdegrees[0] + degrees[0], startdegrees[1] + degrees[1], startdegrees[2] + degrees[2])

    if normed:
        f.write("Восстановленные функции Фi в форме многочленов для нормированных переменных:\n")
    else:
        f.write("Восстановленные функции Фi в форме многочленов для ненормированных переменных:\n")
    for i in xrange(F_coord_coef.shape[0]):
        f.write("Ф%d(x1,x2,x3) = " % (i + 1))
        res = 0
        for j in xrange(3):
            for k in xrange(dimensions[j]):
                for l in xrange(enddegrees[j] + 1):
                    if pos_of_xi_in_all(j, dimensions, degrees) + k * (degrees[j] + 1) + l == 1:
                        f.write("%e*x%d%d^%d" % (F_coord_coef[i][1], j + 1, k + 1, l))
                    elif l == 0:
                        res += F_coord_coef[i][pos_of_xi_in_all(j, dimensions, degrees) + k * (degrees[j] + 1) + l]
                    else:
                        if F_coord_coef[i][pos_of_xi_in_all(j, dimensions, degrees) + k * (degrees[j] + 1) + l] >= 0:
                            sign = "+"
                        else:
                            sign = "-"
                        f.write(" %s %e*x%d%d^%d" % (
                            sign,
                            abs(F_coord_coef[i][pos_of_xi_in_all(j, dimensions, degrees) + k * (degrees[j] + 1) + l]),
                            j + 1, k + 1, l))
        if res >= 0:
            sign = "+"
        else:
            sign = "-"
        f.write(" %s %e" % (sign, abs(res)))
        f.write("\n")
    f.write("\n")
    f.close()

def print_lamb(file, lamb, dimensions, degrees, startdegrees):
    """print matrix lambda"""
    f = open(file, "a")

    f.write("Векторы lambda (№ вектора, № координаты, степень полинома):\n\t")
    for k in xrange(3):
        for jk in xrange(dimensions[k]):
            for j in xrange(degrees[k] + 1):
                f.write("lambda[%d,%d,%d]\t" % (k + 1, jk + 1, startdegrees[k] + j))
    f.write("\n")

    for i in xrange(lamb.shape[0]):
        f.write("i = %d\t" % (i + 1))
        for k in xrange(3):
            for jk in xrange(dimensions[k]):
                for j in xrange(degrees[k] + 1):
                    f.write("%0.6f\t" % (lamb[i][pos_of_xi_in_all(k, dimensions, degrees) + jk * (degrees[k] + 1) + j]))
        f.write("\n")
    f.write("\n")
    f.close()

def print_a(file, a, dimensions):
    """print matrix a"""
    f = open(file, "a")

    f.write("Векторы a (№ вектора, № координаты):\n\t")
    for j in xrange(3):
        for k in xrange(dimensions[j]):
            f.write("a[%d,%d]\t\t" % (j + 1, k + 1))
    f.write("\n")

    for i in xrange(a.shape[0]):
        f.write("i = %d\t" % (i + 1))
        for j in xrange(3):
            for k in xrange(dimensions[j]):
                f.write("%0.6f\t" % (a[i][pos_of_xi_in_x(j, dimensions) + k]))
        f.write("\n")
    f.write("\n")
    f.close()

def print_c(file, c):
    """print matrix c"""
    f = open(file, "a")

    f.write("Векторы c (№ вектора):\n\t")
    for j in xrange(3):
        f.write("c[%d]\t\t" % (j + 1))
    f.write("\n")

    for i in xrange(c.shape[0]):
        f.write("i = %d\t" % (i + 1))
        for j in xrange(3):
            f.write("%0.6f\t" % (c[i][j]))
        f.write("\n")
    f.write("\n")
    f.close()

def print_residue(file, residue, residue3):
    """print residue results"""
    f = open(file, "a")

    f.write("\tМаксимальный модуль погрешности\tСредний модуль погрешности\n")

    for i in xrange(residue.shape[1]):
        f.write("i = %d\t%0.6f\t\t\t%0.6f\n" % (i + 1, max(residue[:, i]), np.mean(residue[:, i])))
    f.write("\nНорма невязки для ненормированных переменных:\n")
    for i in xrange(residue.shape[1]):
        f.write("i = %d\t%0.6f\n" % (i + 1, np.linalg.norm(residue3[:, i])))
    f.write("\n")
    f.close()

def print_all(lamb, a, c, F_pol_coef, F_norm_coef, F_initial_coef, residue, residue3, polynom_type, dimensions, degrees,
              startdegrees):
    """prints all results of calculations"""
    file = 'results.txt'
    f = open(file, "w")
    f.close()
    print_lamb(file, lamb, dimensions, degrees, startdegrees)
    print_a(file, a, dimensions)
    print_c(file, c)
    print_psi(file, lamb, polynom_type, dimensions, degrees, startdegrees)
    print_Fij(file, a, dimensions)
    print_Fi_through_Fij(file, c)
    print_Fi_through_polynomials(file, F_pol_coef, polynom_type, dimensions, degrees, startdegrees)
    print_Fi_through_coord_coef(file, F_norm_coef, True, dimensions, degrees, startdegrees)
    print_Fi_through_coord_coef(file, F_initial_coef, False, dimensions, degrees, startdegrees)
    print_residue(file, residue, residue3)


from numpy import inf
import numpy.random as random
from copy import deepcopy

from logger import log
from math import acos, sqrt

class AntPathData:
    """Содержимое запоминаемого пути муравья"""
    def __init__(self, v, weight, state):
        self.vertex = v
        self.weight = weight
        self.state = state

class AntPath:
    class PathNode:
        def __init__(self, data=None, prev=None, next=None):
            self.data = data
            self.next = self if next is None else next
            self.prev = self if prev is None else prev

    def __init__(self, v):
        self.sent = AntPath.PathNode()
        self.sent.next = AntPath.PathNode(v, self.sent, self.sent)
        self.sent.prev = self.sent.next

    class PathIter:
        def __init__(self, path):
            self.cur = path.start
            self.end = path.end

        def __next__(self):
            if self.cur == self.end.next:
                raise StopIteration

            ret = self.cur.data
            self.cur = self.cur.next
            return ret

    @property
    def start(self):
        return self.sent.next

    @property
    def end(self):
        return self.sent.prev

    @property
    def empty(self):
        return self.start == self.sent and self.end == self.sent

    def __iter__(self):
        return AntPath.PathIter(self)

    def append(self, data):
        new = AntPath.PathNode(data, self.end, self.sent)
        self.end.next = new
        self.sent.prev = new

    def extract(self, start, end):
        start.prev.next = end.next
        end.next.prev = start.prev
        cur = start
        while cur != end:
            cur = cur.next
            cur.prev.next = None
            cur.prev = None

    def pop(self):
        ret = self.end.data
        self.extract(self.end, self.end)
        return ret

    def clear(self):
        self.sent.prev = self.sent
        self.sent.next = self.sent

class Ant:
    """Класс, моделирующий поведение муравья"""
    def __init__(self, a, b, g, graph, robot, start, end):
        self.alpha = a
        self.beta = b
        self.gamma = g
        self.assoc_graph = graph
        self.robot = robot
        self.origin = self.robot.get_effector()

        self._path = AntPath(AntPathData(start,
                                         0.0,
                                         self.robot.state))

        self.target = end

        # мн-во посещенных вершин
        self.visited = set([start])
        # длина отступления
        self.fallback_len = 0
        # сколько еще нужно возвращаться после отступления
        self.required_fallback = 0

    @property
    def pos(self):
        return self._path.end.data

    @pos.setter
    def pos(self, value):
        self._path.append(value)

    @property
    def path(self):
        return self._path

    @property
    def path_len(self):
        ret = sum(v.weight for v in self.path)
        return ret

    @property
    def complete(self):
        return self.pos.vertex == self.target

    def _orient_angle(self, v, w):
        move_vec = tuple(w_i - v_i for w_i, v_i in zip(w, v))
        end_vec = tuple(e_i - p_i for e_i, p_i in zip(self.target,
                                                      self.pos.vertex))

        end_vec_len = sqrt(sum(c * c for c in end_vec))
        dot_pr = sum(a * b for a, b in zip(move_vec, end_vec))

        theta = acos(dot_pr / end_vec_len)
        return theta

    def edge_attractions(self, w_list, p_list, orn_list):
        def attraction(w, p, th):
            if w == inf:
                return 0.0
            else:
                d = 1/w
                ang = 1/(1+th)
                return p ** self.alpha * (d ** self.beta) * ang ** self.gamma

        return [attraction(w, p, th)
                for p, w, th in zip(p_list, w_list, orn_list)]

    def _fall_back(self):
        v = self.path.pop()
        if self.path.empty:
            if self.fallback_len == 1:
                raise RuntimeError('Something something terrible news!')
            else:
                self.path.append(v)
                self.fallback_len = 0
        else:
            self.robot.state = self.pos.state
            self.visited.remove(v.vertex)

    def pick_edge(self):
        """Совершает перемещение в одну из соседних точек в графе G"""

        step = self.robot.kin_eps
        v = self.pos.vertex
        G = self.assoc_graph

        eligible = set(G.get_adjacent(v)) - self.visited
        targets = list(eligible)
        weights = [G.get_weight(v, t)
                   for t in targets]
        phi = [G.get_phi(v, t)
               for t in targets]
        orients = [self._orient_angle(v, t)
                   for t in targets]
        # привлекательности ребер
        attrs = self.edge_attractions(weights, phi, orients)

        total_attr = sum(attrs)

        # некуда идти
        if total_attr == 0.0:
            log()['ATTR_DEBUG'].log('Total attr is 0, falling back')
            self.fallback_len += 1
            for i in range(self.fallback_len - self.required_fallback):
                self._fall_back()
            self.required_fallback = self.fallback_len
        # есть куда идти
        else:
            attr = [a / total_attr for a in attrs]

            # случайный выбор тут
            choice = random.choice(len(targets), p=attr)

            self.robot.move_to(
                tuple(o + step * v
                      for o, v in zip(self.origin, targets[choice])))

            # добавить в путь (вершина, вес, состояние)
            self.pos = AntPathData(targets[choice],
                                   weights[choice],
                                   self.robot.state)
            self.visited.add(targets[choice])
            if self.required_fallback > 0:
                self.required_fallback -= 1
            else:
                self.fallback_len = 0

    def reset_iter(self):
        self.robot.state = self.path.start.data.state
        self.visited = set()
        self.visited.add(self.path.start.data.vertex)

    def disable_deposit(self):
        v = self._path.start.data
        self._path.clear()
        self._path.append(v)

    def deposit_pheromone(self, Q):
        """Распространяет феромон по всем пройденным ребрам"""
        if self.complete:
            G = self.assoc_graph
            phi = Q / self.path_len
            log()['PHI_DEPOSIT'].log(f'{phi} pheromone.')
            n = self._path.start
            while n != self._path.end:
                cur = n.data.vertex
                nxt = n.next.data.vertex
                log()['PHI_DEPOSIT'].log(f'Edge ({cur}; {nxt})')
                log()['PHI_DEPOSIT'].log(f'Predep={G.get_phi(cur, nxt)}')
                G.add_phi(cur, nxt, phi)
                log()['PHI_DEPOSIT'].log(f'Postdep={G.get_phi(cur, nxt)}')
                n = n.next
        else:
            log()['PHI_DEPOSIT'].log('no pheromone.')

    def reset(self):
        """Возвращает муравья к начальному состоянию"""
        pos = self._path.start.data
        self._path.clear()
        self._path.append(pos)
        self.deposits = True
        self.visited = set()
        self.visited.add(pos.vertex)
        self.fallback_len = 0
        self.required_fallback = 0

    def clone(self):
        ret = Ant(self.alpha,
                  self.beta,
                  self.gamma,
                  self.assoc_graph,
                  self.robot,
                  self.pos.vertex,
                  self.target)
        ret._path = deepcopy(self._path)
        ret.visited = deepcopy(self.visited)
        ret.origin = self.origin
        ret.fallback_len = self.fallback_len
        ret.required_fallback = self.required_fallback
        return ret


import numpy as np
import numerical_impl_halbl_bloch_dipol_aprox as myfunction
from matplotlib import pyplot as plt
from matplotlib.widgets import Slider, RadioButtons,TextBox,Button
import tikzplotlib ## for tikzpicture export
from scipy import interpolate

numberBands=2
atomicTime=2.418884e-17
atomicEnergy=27.21139
atomicElec=5142.206
eVnorm=50*atomicEnergy

figRho, axRho = plt.subplots()
figRho.suptitle('One-body density matrix')
plt.subplots_adjust(left=0.25, bottom=0.35)

#### Sliders ####

axAmpDampOff = plt.axes([0.25, 0.25, 0.65, 0.03])
slAmpDampOff = Slider(axAmpDampOff, 'Off-dia-damping', 0., 100.0, valinit=00.)
axAmpDampGro = plt.axes([0.25, 0.21, 0.65, 0.03])
slAmpDampGro = Slider(axAmpDampGro, 'Ground-Damping', 0., 10.0, valinit=00.)

axAmpElec = plt.axes([0.25, 0.17, 0.65, 0.03])
slAmpElec = Slider(axAmpElec, '$|E|$', 0., 20.0, valinit=5*11/atomicElec*eVnorm)
axAmpDEn = plt.axes([0.25, 0.13, 0.65, 0.03])
slAmpDEn = Slider(axAmpDEn, '$\\Delta\\epsilon$', 0., 100.0, valinit=2/atomicEnergy*eVnorm)

#### Gaussian and plane wave specific parameters

axAmpOmega = plt.axes([0.25, 0.09, 0.25, 0.03])
slAmpOmega = Slider(axAmpOmega, 'Omega', 0., 10.0, valinit=2*np.pi*30.1e12*atomicTime*eVnorm)
axAmpPhase = plt.axes([0.65, 0.09, 0.25, 0.03])
slAmpPhase = Slider(axAmpPhase, 'Phase', 0., 2*np.pi, valinit=0.)

axAmpWidth = plt.axes([0.25, 0.05, 0.25, 0.03])
slAmpWidth = Slider(axAmpWidth, 'Width', 0., 10.0, valinit=50e-15/atomicTime/eVnorm)
axAmpMean = plt.axes([0.65, 0.05, 0.25, 0.03])
slAmpMean = Slider(axAmpMean, 'Mean', 0., 60., valinit=15.)

#### Radio Button ####

rax = plt.axes([0.025, 0.5, 0.15, 0.15])
radioElectrical = RadioButtons(rax, ('Gaussian', 'PlaneWave', 'Step', 'Constant'), active=1)

#### TextBox ####

initialValue = 2
axbox = plt.axes([0.1, 0.3, 0.05, 0.05])
text_box = TextBox(axbox, 'Number \nbands  ', initial=str(int(initialValue)))

#### Reset Butt ####

axReset = plt.axes([0.1, 0.8, 0.075, 0.05])
button_Reset = Button(axReset, 'Reset')

axSave = plt.axes([0.1, 0.7, 0.075, 0.05])
button_Save = Button(axSave, 'Save')

#### Create other figures ####

figPol, axPol = plt.subplots()
figPol.suptitle('Polarisation')

figPolDt, axPolDt = plt.subplots()
figPolDt.suptitle('Time derivative Polarisation')

figElec, axElec = plt.subplots()
figElec.suptitle('Electrical Field')

figEmission, axEmission = plt.subplots()
figEmission.suptitle("Emission spectrum of a two-level system")
####

timeElec = np.linspace(0,20,1000)
elecField = np.array(len(timeElec),dtype=object)

### Create rho plot double for tikzpicture export

figRhoTikz, axRhoTikz = plt.subplots()
#figRhoTikz.suptitle('One-body density matrix')
## Update function for silders
def update(val):

	#### setting parameters
    myfunction.damping_off = slAmpDampOff.val
    myfunction.damping_ground = slAmpDampGro.val
    myfunction.deltaEnergy = slAmpDEn.val
    myfunction.amplitudeElec = slAmpElec.val

    myfunction.omega = slAmpOmega.val
    myfunction.phase = slAmpPhase.val
    myfunction.width_gaussian = slAmpWidth.val
    myfunction.mean_gaussian = slAmpMean.val

    #### calculate time evolution and polarisation and time derivative of polarisation
    rhoTime,polarTime,polarDTime,analytics = myfunction.call1(numberBands,figRho, axRho, figPol, axPol, figPolDt, axPolDt)

    step = np.pi/(20*myfunction.omega)
    interpFct = interpolate.interp1d(rhoTime[0], polarTime.real, kind="cubic" )
    interpTime = np.arange(0, 30, step)
    interpPol = np.array([interpFct(t) for t in interpTime])

    frequencies = 2*np.pi*np.fft.rfftfreq(interpPol.size, step)
    polFour = np.fft.rfft(interpPol)
    emission = frequencies*polFour
    emission *= np.conj(emission)
    emission = emission.real
    emission = emission/max(emission)
    emission = np.transpose([frequencies/myfunction.omega, emission])
    emission = emission[1:]

    #clear figures
    freq_undamped = np.sqrt(myfunction.deltaEnergy**2+4.*myfunction.amplitudeElec**2)/(2.*np.pi)
    print(myfunction.deltaEnergy, myfunction.amplitudeElec,freq_undamped)
    axRho.clear()
    axPol.clear()
    axPolDt.clear()
    axElec.clear()
    axRhoTikz.clear()
    axEmission.clear()

    # plot new values
    myfunction.plotTimeEvolutionOneBodyDensity(rhoTime,figRho,axRho)
    scale = np.asarray([x*freq_undamped for x in rhoTime[0]])
    myfunction.plotTimeEvolutionOneBodyDensity([np.round((scale),3),np.round(rhoTime[1],3)],figRhoTikz,axRhoTikz)
    figRhoTikz.set_visible(False)
    #plt.figure(figRhoTikz.number)
    #tikzplotlib.save("testRho.tex", figureheight='\\figureHeightRho', figurewidth='\\figureWidthRho')

    myfunction.plotTimeEvolutionPolarisation([np.round((scale),3),np.round(polarTime,3)],figPol,axPol)
    myfunction.plotTimeEvolutionPolarisation(polarDTime,figPolDt,axPolDt, "$\\frac{d}{dt}$")
    if myfunction.flag_Gauss:
        myfunction.plotEmission(emission, figEmission, axEmission, "numerics", "solid")
        myfunction.plotEmission(analytics, figEmission, axEmission, "analytics", "dashed")

    # plot electric field
    plt.figure(figElec.number)
    elecField = np.asarray([np.dot(np.array([1.+0.*1j,1.+0.*1j,1.+0.*1j]/np.sqrt(3.)).T,myfunction.electricalField(t)) for t in timeElec])
    plt.plot(timeElec,np.real(elecField))

    figElec.canvas.draw_idle()
    figRho.canvas.draw_idle()
    figPol.canvas.draw_idle()
    figPolDt.canvas.draw_idle()
    figRhoTikz.canvas.draw_idle()
    figEmission.canvas.draw_idle()

# connect signal to update function
slAmpDampOff.on_changed(update)
slAmpDampGro.on_changed(update)
slAmpElec.on_changed(update)
slAmpDEn.on_changed(update)
slAmpOmega.on_changed(update)
slAmpPhase.on_changed(update)
slAmpMean.on_changed(update)

slAmpWidth.on_changed(update)
# update function for radio button
def update2(label):
	print(label)
	if (label == "Gaussian"):
		myfunction.flag_Gauss = True
		myfunction.flag_Smooth = False
		myfunction.flag_Plane = False
	elif(label == 'Step'):
		myfunction.flag_Gauss = False
		myfunction.flag_Smooth = True
		myfunction.flag_Plane = False

	elif(label == 'Constant'):
		myfunction.flag_Gauss = False
		myfunction.flag_Smooth = False
		myfunction.flag_Plane = False
	elif(label== 'PlaneWave'):
		myfunction.flag_Gauss = False
		myfunction.flag_Smooth = False
		myfunction.flag_Plane = True
	update(slAmpDampOff.val)
radioElectrical.on_clicked(update2)

## update function for textbox
def update_submit(text):
	global numberBands
	try:
		numberBands = int(text)
	except ValueError as ex:
		numberBands = initialValue
		text_box.set_val(str(initialValue))
	update(slAmpDampOff.val)

text_box.on_submit(update_submit)

# update function for reset button
def update_reset(dump):
	global numberBands,text_box
	numberBands = 2
	myfunction.flag_Gauss = True
	myfunction.flag_Smooth = False
	myfunction.flag_Plane = False
	myfunction.damping_off = 0.0
	myfunction.damping_ground = 0.0
	myfunction.deltaEnergy = 1.0
	myfunction.amplitudeElec = 1.0
	text_box.set_val("2")
	radioElectrical.set_active(0)

	slAmpDampOff.set_val(0.0)
	slAmpDampGro.set_val(0.0)
	slAmpOmega.set_val(0.0)
	slAmpElec.set_val(1.0)
	slAmpDEn.set_val(1.0)

button_Reset.on_clicked(update_reset)

def save(dump):
    global radioElectrical,slAmpDampOff,slAmpDampGro,slAmpElec,slAmpDEn,slAmpOmega
    plt.figure(figRhoTikz.number)
    axRhoTikz.set_xlabel("time $\\left[\\frac{2\\pi}{\\Omega}\\right]$")
    axRhoTikz.set_ylabel("matrix elements")
    name = str(radioElectrical.value_selected)+"_Omgea"+str(np.round(slAmpOmega.val,2))+ "_DampOff"+str(np.round(slAmpDampOff.val,2))\
    	+"_DampGro"+str(np.round(slAmpDampGro.val,2))+"_deltaEnergy"+str(np.round(slAmpDEn.val,2))+"_AmplitudeE"+str(np.round(slAmpElec.val,2))+".tex"

    tikzplotlib.save("rho_"+name, figureheight='\\figureHeightRho', figurewidth='\\figureWidthRho')
    plt.figure(figPol.number)
    axPol.set_xlabel("time $\\left[\\frac{2\\pi}{\\Omega}\\right]$")
    axPol.set_ylabel("polarization [at.u.]")
    figPol.suptitle("")
    tikzplotlib.save("pol_"+name, figureheight='\\figureHeightPol', figurewidth='\\figureWidthPol')
    figPol.suptitle("Polarization")

    return

button_Save.on_clicked(save)

plt.show()


#!/usr/bin/env python3
# pylint: disable=missing-docstring,no-self-use,invalid-name,broad-except,too-many-instance-attributes

import asyncio
import logging
import os
import re
import subprocess
import sys
import time
import traceback

from nio import (
    AsyncClient,
    SyncError,
    SyncResponse,
    InviteMemberEvent,
    RoomMessageText
)

logger = logging.getLogger('TinyMatrixBot')

class TinyMatrixBot:
    def shell_exec(self, args, env=None):
        env_copy = os.environ.copy()
        if env:
            env_copy.update(env)
        try:
            run = subprocess.run(
                args,
                stdout=subprocess.PIPE,
                env=env_copy,
                check=False,
                universal_newlines=True)
        except Exception as e:
            logger.error('exec %s failed: %s', args, str(e))
            return False
        output = run.stdout.rstrip()
        logger.debug('exec %s %s %s', args, env, output)
        if run.returncode != 0 or not output:
            return False
        return output

    scripts_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'scripts-enabled')
    _scripts = None

    def get_scripts(self):
        if self._scripts:
            return self._scripts
        if not os.path.isdir(self.scripts_path):
            logger.error('no scripts directory')
            return
        self._scripts = {}
        for file in os.listdir(self.scripts_path):
            script_path = os.path.join(self.scripts_path, file)
            if not os.access(script_path, os.R_OK) or not os.access(script_path, os.X_OK):
                continue
            config_output = self.shell_exec(script_path, {'CONFIG': '1'})
            if not config_output:
                continue
            logger.debug('script %s %s', script_path, config_output)
            self._scripts.update({script_path: config_output})
        return self._scripts

    async def on_error(self, response):
        logger.error(response)
        if self._client:
            await self._client.close()
        sys.exit(1)

    _initial_sync_done = False

    async def on_sync(self, _response):
        if not self._initial_sync_done:
            self._initial_sync_done = True
            for room in self._client.rooms:
                logger.info('room %s', room)
            logger.info('initial sync done, ready for work')

    accept_invites = None

    async def on_invite(self, room, event):
        if not self.accept_invites:
            user_domain = re.escape(self.user_id.split(':')[1])
            self.accept_invites = f':{user_domain}$'
        if not re.search(self.accept_invites, event.sender, re.IGNORECASE):
            logger.info('invite %s %s ignored', event.sender, room.room_id)
            return
        logger.info('invite %s %s', event.sender, room.room_id)
        await self._client.join(room.room_id)

    _last_event_timestamp = time.time() * 1000

    async def on_message(self, room, event):
        await self._client.update_receipt_marker(room.room_id, event.event_id)
        if event.sender == self._client.user_id:
            return
        if event.server_timestamp <= self._last_event_timestamp:
            return
        self._last_event_timestamp = event.server_timestamp
        scripts = self.get_scripts()
        if not scripts:
            logger.error('no scripts')
            return
        for script_path in scripts:
            if not re.search(scripts[script_path], event.body, re.IGNORECASE):
                continue
            logger.debug('trigger %s %s %s %s',
                room.room_id,
                event.sender,
                event.body,
                script_path)
            script_output = self.shell_exec(
                [script_path, event.body],
                {'TMB_ROOM_ID': room.room_id,
                'TMB_SENDER': event.sender,
                'TMB_BODY': event.body})
            if not script_output:
                continue
            await self._client.room_typing(room.room_id, True)
            for line in script_output.split('\n\n'):
                time.sleep(0.8)
                logger.debug('send %s %s', room.room_id, line)
                await self._client.room_send(
                    room_id=room.room_id,
                    message_type='m.room.message',
                    content={'msgtype': 'm.text', 'body': line})
            await self._client.room_typing(room.room_id, False)

    homeserver = None
    access_token = None
    user_id = None
    _client = None

    async def run(self):
        logger.info('connect %s', self.homeserver)
        self._client = AsyncClient(self.homeserver)
        self._client.access_token = self.access_token
        self._client.user_id = self.user_id
        self._client.device_id = 'TinyMatrixBot'
        self._client.add_response_callback(self.on_error, SyncError)
        self._client.add_response_callback(self.on_sync, SyncResponse)
        self._client.add_event_callback(self.on_invite, InviteMemberEvent)
        self._client.add_event_callback(self.on_message, RoomMessageText)
        await self._client.sync_forever(30000)
        await self._client.close()

if __name__ == '__main__':
    if 'TMB_DEBUG' in os.environ:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
    try:
        TMB = TinyMatrixBot()
        TMB.homeserver = os.environ['TMB_HOMESERVER']
        TMB.access_token = os.environ['TMB_ACCESS_TOKEN']
        TMB.user_id = os.environ['TMB_USER_ID']
        if 'TMB_SCRIPTS_PATH' in os.environ:
            TMB.scripts_path = os.environ['TMB_SCRIPTS_PATH']
        if 'TMB_ACCEPT_INVITES' in os.environ:
            TMB.accept_invites = os.environ['TMB_ACCEPT_INVITES']
        asyncio.run(TMB.run())
    except Exception:
        traceback.print_exc(file=sys.stdout)
        sys.exit(1)
    except KeyboardInterrupt:
        sys.exit(0)


import asyncio
from copy import copy
from typing import List

from stonky.api import Api
from stonky.settings import Settings
from stonky.stock import Stock

class StockStore:
    def __init__(self, api: Api, settings: Settings):
        self._stocks = {}
        self._api = api
        self._sort = settings.sort
        self._base_currency = settings.currency
        self._settings = settings
        self._raw_cash = None
        self._raw_positions = None
        self._raw_watchlist = None
        self._raw_tickets = None

    async def update(self):
        self._reset_raw_values()
        await self._update_quotes()
        if self._base_currency:
            await self._convert_currencies()

    @property
    def watchlist(self) -> List[Stock]:
        return self._try_sort(
            [
                stock
                for ticket, stock in self._stocks.items()
                if ticket in self._raw_watchlist
            ]
        )

    @property
    def positions(self) -> List[Stock]:
        results = []
        for ticket, count in self._raw_positions.items():
            stock = copy(self._stocks[ticket])
            stock.increase_count(count)
            results.append(stock)
        return self._try_sort(results)

    @property
    def profit_and_loss(self):
        pnl = {}
        for ticket, count in self._raw_positions.items():
            stock = copy(self._stocks[ticket])
            stock.increase_count(count)
            if stock.currency not in pnl:
                pnl[stock.currency] = stock
            else:
                pnl[stock.currency].amount_prev_close += stock.amount_prev_close
                pnl[stock.currency].delta_amount += stock.delta_amount
        results = []
        for pnl_line in pnl.values():
            pnl_line.delta_percent = (
                pnl_line.delta_amount / pnl_line.amount_prev_close
            )
            results.append(pnl_line)
        return results

    @property
    def balances(self):
        balances = {}
        for ticket, count in self._raw_positions.items():
            stock = self._stocks[ticket]
            if stock.currency not in balances:
                balances[stock.currency] = stock.amount_current * count
            else:
                balances[stock.currency] += stock.amount_current * count
        for currency, amount in self._raw_cash.items():
            if currency not in balances:
                balances[currency] = amount
            else:
                balances[currency] += amount
        return balances

    def _try_sort(self, stocks: List[Stock]):
        if self._sort:
            reverse = self._sort.value.endswith("_desc")
            sort, *_ = self._sort.value.rsplit("_desc")
            stocks.sort(key=lambda _: getattr(_, sort), reverse=reverse)
        return stocks

    def _reset_raw_values(self):
        self._raw_cash = copy(self._settings.cash)
        self._raw_positions = copy(self._settings.positions)
        self._raw_watchlist = copy(self._settings.watchlist)
        self._raw_tickets = set(self._settings.positions) | set(
            self._settings.watchlist
        )

    async def _update_quotes(self):
        futures = tuple(
            self._api.get_quote(ticket) for ticket in self._raw_tickets
        )
        self._stocks = {
            stock.ticket: stock for stock in await asyncio.gather(*futures)
        }

    async def _convert_currencies(self):
        used_currencies = set(self._raw_cash) | {
            stock.currency for stock in self.positions
        }
        forex = await self._api.get_forex_rates(
            self._base_currency, used_currencies
        )
        # convert balances
        base_amount = self._raw_cash.get(self._base_currency, 0.0)
        self._raw_cash = {
            self._base_currency: base_amount
            + sum(
                self._raw_cash[conversion_currency] / forex[conversion_currency]
                for conversion_currency in self._raw_cash
            )
        }
        # convert stocks
        for stock in self._stocks.values():
            if stock.currency is self._base_currency:
                continue
            conversion_rate = forex[stock.currency]
            stock.currency = self._base_currency
            stock.convert_currency(conversion_rate)


#!/usr/bin/env python3

import os
import select
import termios
import struct
import time

STDIN = 0
STDOUT = 1

def main():
    fd = os.open('/dev/tty', os.O_RDONLY)

    size = os.get_terminal_size(fd)
    os.write(STDOUT, struct.pack('<LL', size.columns, size.lines))

    old = termios.tcgetattr(fd)
    new = list(old)
    new[0] = new[0] & ~(termios.ICRNL)
    new[3] = new[3] & ~(termios.ECHO | termios.ICANON | termios.ISIG)

    try:
        termios.tcsetattr(fd, termios.TCSAFLUSH, new)

        while True:
            r, _, _ = select.select([STDIN, fd], [], [])
            if fd in r:
                try:
                    buf = os.read(fd, 64)
                except:
                    break
                if len(buf) == 0:
                    break
                os.write(STDOUT, buf)
            if STDIN in r:
                os.write(STDOUT, b'\x00')
                break
    finally:
        termios.tcsetattr(fd, termios.TCSAFLUSH, old)

if __name__ == '__main__':
    main()


import os, sys
from pythac.PFS0 import PFS0

def extract_nsp(fp):
    dest = os.path.join(os.path.dirname(fp.name), os.path.basename(fp.name).split('.')[0])
    nsp = PFS0(fp)
    nsp.extract(dest, disp=True)

def main(argc, argv):
    try:
        if argc < 2 or not os.path.isfile(argv[1]):
            raise ValueError('Usage is %s path/to/nsp.' % argv[0])
        extract_nsp(open(argv[1], 'rb'))
        return 0
    except Exception as e:
        print('%s: %s' % (e.__class__.__name__, e))
        return 1
    finally:
        print('\nPress enter to exit.')
        input()

if __name__ == '__main__':
    sys.exit(main(len(sys.argv), sys.argv))


# -*- coding: utf-8 -*-
from types import NoneType
from unittest import TestCase

import ddt
import mock

from edx_rest_api_client.auth import JwtAuth
from edx_rest_api_client.client import EdxRestApiClient

URL = 'http://example.com/api/v2'
SIGNING_KEY = 'edx'
USERNAME = 'edx'
FULL_NAME = 'édx äpp'
EMAIL = 'edx@example.com'
TRACKING_CONTEXT = {'foo': 'bar'}
ACCESS_TOKEN = 'abc123'
JWT = 'abc.123.doremi'

@ddt.ddt
class EdxRestApiClientTests(TestCase):
    """ Tests for the E-Commerce API client. """

    @ddt.unpack
    @ddt.data(
        ({'url': URL, 'signing_key': SIGNING_KEY, 'username': USERNAME,
          'full_name': FULL_NAME, 'email': EMAIL}, JwtAuth),
        ({'url': URL, 'signing_key': SIGNING_KEY, 'username': USERNAME, 'full_name': None, 'email': EMAIL}, JwtAuth),
        ({'url': URL, 'signing_key': SIGNING_KEY, 'username': USERNAME,
          'full_name': FULL_NAME, 'email': None}, JwtAuth),
        ({'url': URL, 'signing_key': SIGNING_KEY, 'username': USERNAME, 'full_name': None, 'email': None}, JwtAuth),
        ({'url': URL, 'signing_key': SIGNING_KEY, 'username': USERNAME}, JwtAuth),
        ({'url': URL, 'signing_key': None, 'username': USERNAME}, NoneType),
        ({'url': URL, 'signing_key': SIGNING_KEY, 'username': None}, NoneType),
        ({'url': URL, 'signing_key': None, 'username': None, 'oauth_access_token': None}, NoneType)
    )
    def test_valid_configuration(self, kwargs, auth_type):
        """
        The constructor should return successfully if all arguments are valid.
        We also check that the auth type of the api is what we expect.
        """
        api = EdxRestApiClient(**kwargs)
        self.assertEqual(auth_type, type(getattr(api._store["session"], "auth")))  # pylint: disable=protected-access

    @ddt.data(
        {'url': None, 'signing_key': SIGNING_KEY, 'username': USERNAME},
        {'url': None, 'signing_key': None, 'username': None, 'oauth_access_token': None},
    )
    def test_invalid_configuration(self, kwargs):
        """ If the constructor arguments are invalid, an InvalidConfigurationError should be raised. """
        self.assertRaises(ValueError, EdxRestApiClient, **kwargs)

    @mock.patch('edx_rest_api_client.auth.JwtAuth.__init__', return_value=None)
    def test_tracking_context(self, mock_auth):
        """ Ensure the tracking context is included with API requests if specified. """
        EdxRestApiClient(URL, SIGNING_KEY, USERNAME, FULL_NAME, EMAIL, tracking_context=TRACKING_CONTEXT)
        self.assertIn(TRACKING_CONTEXT, mock_auth.call_args[1].values())

    def test_oauth2(self):
        """ Ensure OAuth2 authentication is used when an access token is supplied to the constructor. """

        with mock.patch('edx_rest_api_client.auth.BearerAuth.__init__', return_value=None) as mock_auth:
            EdxRestApiClient(URL, oauth_access_token=ACCESS_TOKEN)
            mock_auth.assert_called_with(ACCESS_TOKEN)

    def test_supplied_jwt(self):
        """Ensure JWT authentication is used when a JWT is supplied to the constructor."""
        with mock.patch('edx_rest_api_client.auth.SuppliedJwtAuth.__init__', return_value=None) as mock_auth:
            EdxRestApiClient(URL, jwt=JWT)
            mock_auth.assert_called_with(JWT)


#类定义
class CPeople:
    name = ''
    age = 0
    __weight = 0

    #structure function

    def __init__(self, name, age, weight):
        self.name = name
        self.age = age
        self.weight = weight
    def speak(self):
        print("%s is speaking, I'm %d years old." %(self.name, self.age))
class CStudent(CPeople):
    grade = 0
    def __init__(self, name, age, weight, grade):
        CPeople.__init__(self, name, age, weight)
        self.grade = grade
    def speak(self):
        print("%s is peaking, and I'm a student." %(self.name))
class CSpeaker:
    topic = ''
    name = ''
    def __init__(self, name ,topic):
        self.name = name
        self.topic = topic
    def speak(self):
        print("%s is speaking, I'm a speaker, and my topic is %s." %(self.name, self.topic))

#多继承
class CSample(CSpeaker, CPeople):
    def __init__(self, name ,age, weight, topic):
        CSpeaker.__init__(self, name, topic)
        CPeople.__init__(self, name, age, weight)

p = CPeople('Tom', 10, 30)
p.speak()
s = CStudent('Bill', 20, 50, 89)
s.speak()

#测试多继承
t = CSample('Bob', 10, 30, 'Python')
t.speak()


# coding=utf-8

import kivy
from numpy.random import shuffle as 𐎣

𐎠𐎶=range
𐎠𐎷=len
#𐎠𐎸
#𐎠𐎹
𐎠𐎺=1
𐎠𐎻=list
𐎠𐎼=set
𐎠𐎽=str
𐎠𐎾=sorted
𐎠𐎿=__name__
#𐎠𐏀
𐎠𐏁=int
𐎠𐏂=bool

from operator import add
from itertools import chain
import decimal as 𐎠
𐎠.getcontext().prec=3
𐎡=𐎠.Decimal

from kivy.app import App as 𐎠𐎤
from kivy.uix.button import Button as 𐎠𐎦
from kivy.uix.gridlayout import GridLayout as 𐎠𐎧
from kivy.uix.label import Label as 𐎠𐎨
from kivy.uix.textinput import TextInput as 𐎠𐎩

class 𐎠𐎮(𐎠𐎤):
    def build(𐎠𐎸):
        𐎠𐎬 = 𐎠𐎬 = 𐎠𐎧(cols=𐎠𐎺+𐎠𐎺,padding=(𐎠𐎺+𐎠𐎺)*((𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺)+𐎠𐎺))
        𐎨 = ["rooms: ", "rounds: ", "breaking teams: "]

        global 𐎦
        𐎦,𐎧 = {},{}

        for 𐏃 in 𐎠𐎶(𐎠𐎷(𐎨)):
            𐎧[𐏃] = 𐎠𐎨(text="Number of "+𐎨[𐏃])
            𐎠𐎬.add_widget(𐎧[𐏃])
            𐎦[𐏃] =  𐎠𐎩(text='', multiline=𐎠𐏂(𐎠𐎺-𐎠𐎺))
            𐎠𐎬.add_widget(𐎦[𐏃])

        𐎠𐎸.𐎠𐎪 = 𐎠𐎨(text="")
        𐎠𐎬.add_widget(𐎠𐎸.𐎠𐎪)
        𐎠𐎭 = 𐎠𐎦(text="Compute")
        𐎠𐎬.add_widget(𐎠𐎭)
        𐎠𐎭.bind(on_press=𐎠𐎸.𐎠𐏀)
        return 𐎠𐎬

    def 𐎠𐏀(𐎠𐎸,𐎠𐎹):
        𐎠𐎸.𐎠𐎪.text = "\n.".join(𐎥(*[𐎠𐏁(𐎦[𐎠𐎫].text) for 𐎠𐎫 in 𐎠𐎶(𐎠𐎺+𐎠𐎺+𐎠𐎺)]))

def 𐎩(𐎲,𐎱):
    𐎲.sort()
    𐎳=[]
    for 𐎴 in 𐎠𐎶(𐎱):
        𐎳.append(𐎲[(𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺)*𐎴:(𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺)*𐎴+(𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺)])
    return 𐎳

def 𐎰(𐎶,𐎵):
    𐎫=[]
    𐎷=𐎩(𐎶,𐎵)
    for 𐎢 in 𐎠𐎶(𐎠𐎷(𐎷)):
        𐎣(𐎷[𐎢])
        for 𐎪 in 𐎠𐎶((𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺)):
            𐎫.append(𐎷[𐎢][𐎪]+𐎪)
    return 𐎫

def 𐎬(𐎭,𐎮,𐎯):
    𐎸=[𐎠𐎺-𐎠𐎺 for 𐎹 in 𐎠𐎶(𐎭*(𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺))]
    for 𐎹 in 𐎠𐎶(𐎮): 𐎸=𐎰(𐎸,𐎭)
    𐎸.sort()
    𐎺=𐎸[-𐎯]
    return (𐎺,𐎸[-𐎯:].count(𐎺),𐎸.count(𐎺))

def 𐎻(𐎼,𐎽,𐎾,𐎿):
    𐏀={}
    for 𐏁 in 𐎠𐎶(𐎿):
        𐏂=𐎬(𐎼,𐎽,𐎾)
        if 𐏂 in 𐏀:
            𐏀[𐏂]+=𐎠𐎺
        else:
            𐏀[𐏂]=𐎠𐎺
    return 𐏀

def 𐏈(𐏉):
    𐏋=𐎠𐎼([𐏊[𐎠𐎺-𐎠𐎺] for 𐏊 in 𐏉])
    𐏍={𐏌:𐎡(𐎠𐎺-𐎠𐎺) for 𐏌 in 𐏋}
    for 𐏎 in 𐎠𐎻(𐏉):
        for 𐏏 in 𐏋:
            if 𐏎[𐎠𐎺-𐎠𐎺]<𐏏:
                𐏍[𐏏]+=𐏉[𐏎]
            elif 𐏎[𐎠𐎺-𐎠𐎺]==𐏏:
                𐏍[𐏏]+=(𐎡(𐏉[𐏎]*𐏎[𐎠𐎺])/𐎡(𐏎[𐎠𐎺+𐎠𐎺]))
    return 𐏍

def 𐎠𐎰(𐎠𐎱,𐎠𐎥):
    𐎠𐎲=𐏈(𐎠𐎱)
    𐎠𐎳=[]
    for 𐎠𐎴 in 𐎠𐎾(𐎠𐎻(𐎠𐎲)):
        𐎠𐎳.append("Teams with "+𐎠𐎽(𐎠𐎴)+" points have a "+𐎠𐎽(𐎡((((𐎠𐎺+𐎠𐎺)*((𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺)+𐎠𐎺))**(𐎠𐎺+𐎠𐎺))*𐎠𐎲[𐎠𐎴])/𐎡(𐎠𐎥))+"% chance of breaking.")
    return 𐎠𐎳

def 𐎥(𐎠𐎠,𐎠𐎡,𐎠𐎢):
    𐎠𐎵=(((𐎠𐎺+𐎠𐎺)*((𐎠𐎺+𐎠𐎺)*(𐎠𐎺+𐎠𐎺)+𐎠𐎺))**(𐎠𐎺+𐎠𐎺+𐎠𐎺+𐎠𐎺))
    𐎠𐎣=𐎻(𐎠𐎠,𐎠𐎡,𐎠𐎢,𐎠𐎵)
    return 𐎠𐎰(𐎠𐎣,𐎠𐎵)

if 𐎠𐎿=='__main__':
    𐎠𐎮().run()