from uscope.planner.planner_util import get_planner
from uscope.planner.planner import PlannerStop
from uscope.benchmark import Benchmark
from uscope.motion.hal import AxisExceeded, MotionHAL, MotionCritical
from uscope.motion.plugins import get_motion_hal
from uscope.joystick import Joystick, JoystickNotFound
from uscope import cloud_stitch
from uscope import config
from uscope.imager.autofocus import choose_best_image
from PyQt5.QtCore import QThread, pyqtSignal
import traceback
import datetime
import queue
import threading
import time
from queue import Queue, Empty
import subprocess
from uscope.planner.planner_util import microscope_to_planner_config
from uscope.kinematics import Kinematics
from collections import OrderedDict

def dbg(*args):
    if len(args) == 0:
        print()
    elif len(args) == 1:
        print('threading: %s' % (args[0], ))
    else:
        print('threading: ' + (args[0] % args[1:]))

'''
Offloads controller processing to another thread (or potentially even process)
Makes it easier to keep RT deadlines and such
However, it doesn't provide feedback completion so use with care
(other blocks until done)
TODO: should block?
'''

class MotionThreadMotion(MotionHAL):
    def __init__(self, mt):
        self.mt = mt
        MotionHAL.__init__(self, log=mt.motion.log, verbose=mt.motion.verbose)

        # Don't re-apply pipeline (scaling, etc)
        self.configure({})

    def axes(self):
        return self.mt.motion.axes()

    def home(self, axes):
        self.mt.home(block=True)

    def _move_absolute(self, pos):
        self.mt.move_absolute(pos, block=True)

    def _move_relative(self, pos):
        self.mt.move_relative(pos, block=True)

    def _pos(self):
        # return self.mt.pos_cache
        return self.mt.pos()

    def settle(self):
        # No hardware to let settle
        pass

    def ar_stop(self):
        pass

class MotionThread(QThread):
    log_msg = pyqtSignal(str)

    def __init__(self, usc):
        QThread.__init__(self)
        self.usc = usc
        self.verbose = False
        self.queue = queue.Queue()
        self.motion = None
        self.running = threading.Event()
        self.idle = threading.Event()
        self.idle.set()
        self.normal_running = threading.Event()
        self.normal_running.set()
        self.lock = threading.Event()
        # Let main gui get the last position from a different thread
        # It can request updates
        self.pos_cache = None
        self._stop = False
        self._estop = False
        # XXX: add config directive
        self.allow_motion_reboot = False

        # Seed state / refuse to start without motion
        self.init_motion()

    def init_motion(self):
        self.motion = get_motion_hal(usc=self.usc, log=self.log)

    def log(self, msg):
        self.log_msg.emit(msg)

    def setRunning(self, running):
        if running:
            self.normal_running.set()
        else:
            self.normal_running.clear()

    def wait_idle(self):
        while True:
            time.sleep(0.15)
            if self.idle.is_set():
                break

    def command(self, command, *args, block=False, callback=None):
        command_done = None
        if block or callback:
            ready = threading.Event()
            ret = []

            def command_done(command, args, ret_e):
                ret.append(ret_e)
                ready.set()
                if callback:
                    callback()

        self.queue.put((command, args, command_done))
        if block:
            ready.wait()
            ret = ret[0]
            if type(ret) is Exception:
                raise Exception("oopsie: %s" % (ret, ))
            return ret

    def pos(self):
        # XXX: this caused crashes but I'm not sure why
        # Just offload to the thread to avoid this special case
        if 0:
            self.lock.set()
            ret = self.motion.pos()
            self.lock.clear()
            return ret
        else:
            return self.command("pos", block=True)

    def mdi(self, cmd):
        self.command("mdi", cmd)

    def jog(self, pos):
        self.command("jog", pos)

    def jog_lazy(self, pos):
        """
        Only jog if events haven't already stacked up high
        """
        if self.qsize() < 1:
            self.command("jog", pos)

    def stop(self):
        # self.command("stop")
        self._stop = True

    def estop(self):
        # self.command("estop")
        self._estop = True

    def home(self, block=False):
        self.command("home", block=block)

    def backlash_disable(self, block=False):
        self.command("backlash_disable", block=block)

    def backlash_enable(self, block=False):
        self.command("backlash_enable", block=block)

    def move_absolute(self, pos, block=False, callback=None):
        self.command("move_absolute", pos, block=block, callback=callback)

    def move_relative(self, pos, block=False, callback=None):
        self.command("move_relative", pos, block=block, callback=callback)

    def set_jog_rate(self, rate):
        self.command("set_jog_rate", rate)

    def update_pos_cache(self):
        self.command("update_pos_cache")

    def qsize(self):
        return self.queue.qsize()

    def queue_clear(self):
        while True:
            try:
                self.queue.get(block=False)
            except queue.Empty:
                break

    def get_planner_motion(self):
        return MotionThreadMotion(self)

    def shutdown(self):
        self.running.clear()

    def run(self):
        self.verbose and print("Motion thread started: %s" %
                               (threading.get_ident(), ))
        self.running.set()
        self.idle.clear()
        self.motion.on()

        def motion_status(status):
            # print("register_status_cb: via motion-status: %s" % (status,))
            self.pos_cache = status["pos"]

        self.motion.register_status_cb(motion_status)

        try:
            while self.running.is_set():
                self.lock.set()

                if not self.motion:
                    if not self.allow_motion_reboot:
                        self.log("Fatal error: motion controller is dead")
                        break
                    else:
                        # See if its back...
                        try:
                            self.init_motion()
                            self.motion.on()
                        except Exception as e:
                            self.log(
                                "Failed to reboot motion controller :( %s" %
                                (str(e), ))
                            time.sleep(3)
                        continue

                if self._estop:
                    self.motion.estop()
                    self.queue_clear()
                    self._estop = False
                    continue

                if self._stop:
                    self.motion.stop()
                    self.queue_clear()
                    self._stop = False
                    continue

                if not self.normal_running.isSet():
                    self.normal_running.wait(0.1)
                    continue
                try:
                    self.lock.clear()
                    (command, args, command_done) = self.queue.get(True, 0.1)
                except queue.Empty:
                    self.idle.set()
                    continue
                finally:
                    self.lock.set()

                self.idle.clear()

                def default(*args):
                    raise Exception("Bad command %s" % (command, ))

                def move_absolute(pos):
                    try:
                        self.motion.move_absolute(pos)
                    except AxisExceeded as e:
                        self.log(str(e))
                    return self.motion.pos()

                def move_relative(pos):
                    try:
                        self.motion.move_relative(pos)
                    except AxisExceeded as e:
                        self.log(str(e))
                    return self.motion.pos()

                def update_pos_cache():
                    pos = self.motion.pos()
                    self.pos_cache = pos
                    # print("register_status_cb: via update_pos_cache: %s" % (pos,))

                self.verbose and print("")
                self.verbose and print(
                    "process @ %s" % datetime.datetime.utcnow().isoformat())
                #print 'cnc thread: dispatch %s' % command
                # Maybe I should just always emit the pos
                f = {
                    'update_pos_cache': update_pos_cache,
                    'move_absolute': move_absolute,
                    'move_relative': move_relative,
                    'jog': self.motion.jog,
                    'pos': self.motion.pos,
                    'set_jog_rate': self.motion.set_jog_rate,
                    'home': self.motion.home,
                    'backlash_disable': self.motion.backlash_disable,
                    'backlash_enable': self.motion.backlash_enable,
                    # 'stop': self.motion.stop,
                    # 'estop': self.motion.estop,
                    'unestop': self.motion.unestop,
                    'mdi': self.motion.command,
                }.get(command, default)
                try:
                    ret = f(*args)
                # Depending on the motion controller this may be a bad idea
                # Only some of them retain the old coordinate system / may need re-home
                except MotionCritical as e:
                    print("")
                    print("ERROR: motion controller crashed w/ critical error")
                    print(traceback.format_exc())
                    self.motion.close()
                    self.motion = None
                    if command_done:
                        command_done(command, args, e)
                    continue
                except Exception as e:
                    print("")
                    print("WARNING: motion thread crashed")
                    print(traceback.format_exc())
                    if command_done:
                        command_done(command, args, e)
                    continue

                if command_done:
                    command_done(command, args, ret)

        finally:
            if self.motion:
                self.motion.stop()
                # self.motion.ar_stop()

"""
Sends events to the imaging and movement threads

rconfig: misc parmeters including complex objects
plannerj: planner configuration JSON. Written to disk
"""

class PlannerThread(QThread):
    plannerDone = pyqtSignal(dict)
    log_msg = pyqtSignal(str)

    def __init__(self, parent, planner_args, progress_cb):
        QThread.__init__(self, parent)
        self.planner_args = planner_args
        self.planner = None
        self.progress_cb = progress_cb

    def log(self, msg=""):
        #print 'emitting log %s' % msg
        #self.log_buff += str(msg) + '\n'
        self.log_msg.emit(str(msg))

    def setRunning(self, running):
        planner = self.planner
        if planner:
            planner.setRunning(running)

    def is_paused(self):
        if self.planner:
            return self.planner.is_paused()
        return False

    def pause(self):
        if self.planner:
            self.planner.pause()

    def unpause(self):
        if self.planner:
            self.planner.unpause()

    def shutdown(self):
        if self.planner:
            self.planner.stop()

    def run(self):
        ret = {
            "result": None,
        }
        try:
            self.log('Initializing planner!')
            # print("Planner thread started: %s" % (threading.get_ident(), ))

            self.planner = get_planner(log=self.log, **self.planner_args)
            self.planner.register_progress_callback(self.progress_cb)
            self.log('Running planner')
            b = Benchmark()
            self.log()
            self.log()
            self.log()
            self.log()
            ret["meta"] = self.planner.run()
            ret["result"] = "ok"
            b.stop()
            self.log('Planner done!  Took : %s' % str(b))
        except PlannerStop as e:
            ret["result"] = "stopped"
        except Exception as e:
            self.log('WARNING: planner thread crashed: %s' % str(e))
            traceback.print_exc()
            ret["result"] = "exception"
            ret["exception"] = e
            #raise
        finally:
            self.plannerDone.emit(ret)

class StitcherThread(QThread):
    # stitcherDone = pyqtSignal()
    log_msg = pyqtSignal(str)

    def __init__(self, parent=None):
        QThread.__init__(self, parent)
        self.queue = Queue()
        self.running = threading.Event()
        self.running.set()

    def log(self, msg):
        self.log_msg.emit(msg)

    def shutdown(self):
        self.running.clear()

    def cli_stitch_add(self, directory, command):
        j = {
            "type": "cli",
            "directory": directory,
            "command": command,
        }
        self.queue.put(j)

    # Offload uploads etc to thread since they might take a while
    def cloud_stitch_add(
        self,
        directory,
        access_key,
        secret_key,
        id_key,
        notification_email,
    ):

        j = {
            "type": "CloudStitch",
            "directory": directory,
            "access_key": access_key,
            "secret_key": secret_key,
            "id_key": id_key,
            "notification_email": notification_email,
        }
        self.queue.put(j)

    def run(self):
        while self.running:
            try:
                j = self.queue.get(block=True, timeout=0.1)
            except Empty:
                continue
            try:
                if j["type"] == "CloudStitch":
                    cloud_stitch.upload_dir(
                        directory=j["directory"],
                        id_key=j["id_key"],
                        access_key=j["access_key"],
                        secret_key=j["secret_key"],
                        notification_email=j["notification_email"],
                        log=self.log,
                        running=self.running)
                elif j["type"] == "cli":
                    self.log(
                        f"Stitch CLI: kicking off {j['command']} {j['directory']}"
                    )
                    # Hacky but good enough for now
                    # Check terminal for process output
                    print("")
                    print("")
                    print("")
                    print(
                        f"Stitch CLI: kicking off {j['command']} {j['directory']}"
                    )
                    subprocess.check_call([j['command'], j['directory']])
                    self.log(f"Stitch CLI: finished job")
                    print(f"Stitch CLI: finished job")
                else:
                    assert 0, j

            except Exception as e:
                self.log('WARNING: stitcher thread crashed: %s' % str(e))
                traceback.print_exc()
            finally:
                # self.stitcherDone.emit()
                pass

class ImageProcessingThread(QThread):
    log_msg = pyqtSignal(str)

    def __init__(self, motion_thread, ac, parent=None):
        QThread.__init__(self, parent)
        self.queue = Queue()
        self.running = threading.Event()
        self.running.set()
        self.motion_thread = motion_thread
        self.ac = ac
        self.imager = self.ac.imager
        self.kinematics = None

        self.kinematics = Kinematics(
            microscope=self.ac.microscope,
            log=self.log,
        )
        self.kinematics.configure()

    def log(self, msg):
        self.log_msg.emit(msg)

    def shutdown(self):
        self.running.clear()

    def command(self, command, block=False, callback=None):
        command_done = None
        if block or callback:
            ready = threading.Event()
            ret = []

            def command_done(command, ret_e):
                ret.append(ret_e)
                ready.set()
                if callback:
                    callback()

        self.queue.put((command, command_done))
        if block:
            ready.wait()
            ret = ret[0]
            if type(ret) is Exception:
                raise Exception("oopsie: %s" % (ret, ))
            return ret

    def auto_focus_coarse(self, callback=None):
        j = {
            "type": "auto_focus_coarse",
        }
        self.command(j, callback=callback)

    def auto_focus_fine(self, callback=None):
        j = {
            "type": "auto_focus_fine",
        }
        self.command(j, callback=callback)

    def move_absolute(self, pos):
        self.motion_thread.move_absolute(pos, block=True)
        self.kinematics.wait_imaging_ok()

    def pos(self):
        return self.motion_thread.pos()

    def auto_focus_pass(self, step_size, step_pm):
        """
        for outer_i in range(3):
            self.log("autofocus: try %u / 3" % (outer_i + 1,))
            # If we are reasonably confident we found the local minima stop
            # TODO: if repeats should bias further since otherwise we are repeating steps
            if abs(step_pm - fni) <= 2:
                self.log("autofocus: converged")
                return
        self.log("autofocus: timed out")
        """

        # Very basic short range
        start_pos = self.pos()["z"]
        steps = step_pm * 2 + 1

        # Doing generator allows easier to process images as movement is done / settling
        def gen_images():
            for focusi in range(steps):
                # FIXME: use backlash compensation direction here
                target_pos = start_pos + -(focusi - step_pm) * step_size
                self.log("autofocus round %u / %u: try %0.6f" %
                         (focusi + 1, steps, target_pos))
                self.move_absolute({"z": target_pos})
                im_pil = self.imager.get()["0"]
                yield target_pos, im_pil

        target_pos, fni = choose_best_image(gen_images())
        self.log("autofocus: set %0.6f at %u / %u" %
                 (target_pos, fni + 1, steps))
        self.move_absolute({"z": target_pos})

    def do_auto_focus_coarse(self):
        # MVP intended for 20x
        # 2 um is standard focus step size
        self.log("autofocus: coarse")
        self.auto_focus_pass(step_size=0.006, step_pm=3)
        self.log("autofocus: medium")
        self.auto_focus_pass(step_size=0.002, step_pm=3)
        self.log("autofocus: done")

    def do_auto_focus_fine(self):
        # MVP intended for 60x
        # 500 nm is standard focus step size
        self.log("autofocus: fine")
        self.auto_focus_pass(step_size=0.0005, step_pm=3)
        self.log("autofocus: done")

    def run(self):
        while self.running:
            try:
                j, command_done = self.queue.get(block=True, timeout=0.1)
            except Empty:
                continue
            try:
                if j["type"] == "auto_focus_coarse":
                    self.do_auto_focus_coarse()
                elif j["type"] == "auto_focus_fine":
                    self.do_auto_focus_fine()
                else:
                    assert 0, j

                if command_done:
                    command_done(j, None)

            except Exception as e:
                self.log('WARNING: image processing thread crashed: %s' %
                         str(e))
                traceback.print_exc()
                if command_done:
                    command_done(j, e)
            finally:
                # self.stitcherDone.emit()
                pass

class JoystickThread(QThread):
    joystickDone = pyqtSignal()
    log_msg = pyqtSignal(str)

    def __init__(self, ac):
        QThread.__init__(self)
        self.joystick = None
        self.ac = ac
        self.queue = Queue()
        self.running = threading.Event()
        self.running.set()
        try:
            self.joystick = Joystick(microscope=self.ac.microscope)
        except JoystickNotFound:
            raise JoystickNotFound()
        self.ac.microscope.joystick = self.joystick

    def log_info(self):
        self.log("Joystick")
        self.log(f"  Name: {self.joystick.joystick.name}")
        self.log(f"  Axes: {self.joystick.joystick.numaxes}")
        self.log(f"  Trackballs: {self.joystick.joystick.numballs}")
        self.log(f"  Hats: {self.joystick.joystick.numhats}")
        self.log(f"  Buttons: {self.joystick.joystick.numbuttons}")

    def log(self, msg):
        self.log_msg.emit(msg)

    def shutdown(self):
        self.running.clear()

    def run(self):
        while self.running:
            try:
                time.sleep(self.ac.bc.joystick.scan_secs())
                # It is important to check that the button is both enabled and
                # active before performing actions. This allows us to preserve
                # state by disabling and enabling the button only during scans.
                if self.ac.mw.mainTab.motion_widget.joystick_listener.joystick_executing:
                    #self.joystick.debug_dump()
                    self.joystick.execute()
            except Exception as e:
                self.log('WARNING: joystick thread crashed: %s' % str(e))
                traceback.print_exc()
            finally:
                self.joystickDone.emit()


#!/usr/bin/python3
"""Holberton School."""

class Rectangle:
    """Class that prints a Rectangle."""

    def __init__(self, width=0, height=0):
        """Initialize Function."""
        Rectangle.rectangle = {}
        self.__height__ = height
        self.__width__ = width

    @property
    def width(self):
        """Returns width variable."""
        return self.__width__

    @width.setter
    def width(self, value):
        if type(value) != int:
            raise TypeError("width must be an integer")
        if self.__width__ < 0:
            raise ValueError("width must be >= 0")
        self.__width__ = value

    @property
    def height(self):
        """Returns width variable."""
        return self.__height__

    @height.setter
    def height(self, value):
        if type(value) != int:
            raise TypeError("height must be an integer")
        if self.__height__ < 0:
            raise ValueError("height must be >= 0")
        self.__height__ = value


n1 = int(input("Digite o primeiro número: "))
n2 = int(input("Digite o segundo número: "))

#Sem Recursão
while n2 != 0:
	n1, n2 = n2, n1 % n2
	#Python <3
print ("Sem Recursão - MDC =", n1)

#Com Recursão
def mdc(x, y):
	if y == 0:
		return x
	else:
		return mdc(y, x % y)
print ("Com Recursão - MDC =", mdc(n1, n2))


string_for_reverse = "aaaaaa"
string_numbers = "This is 500 plus 300 700  "

def reverse_string(string):
    final_string = ''
    for i in range(1,len(string)+1):
        final_string += string[-i]
    return final_string

def is_pallidrome(string):
    if reverse_string(string) == string:
        return "Pallidrome"
    else:
        return " Not pallidrome"

def count_int_in_str(string):
    """Functions take string and search for integers inside of it and sum them up

    Args:
        string (str): string with numbers

    Returns:
        int: int of summed ints from string
        int: how many ints where inside string
    """
    result = 0
    number = ''
    int_found = 0
    last_integer = False
    for i in string:
        try:
            if int(i) or int(i) == 0:
                print(i)
                if last_integer:
                    number += i
                else:
                    number += i
                    last_integer = True

        except ValueError :
            last_integer = False
            if number:
                int_found += 1
                result += int(number)
                number = ''
            continue
    if type(string[-1]) is int:
        result += int(number)
    return result, int_found

def star_triangle(number):
    """creates star triangle with height of the argument

    Args:
        number (int): height of triangle
    """

    for i in range(number):
        for j in range(i, number):
            print('*', end=' ')
        print()

def sum_of_two(x,y,z):
    for i in x:
        for j in y:
            if i+j == z:
                return True
    return False

def fizzBuzz(number):
    for i in range(1,number+1):
        if i%4==0 and i%6 == 0:
            print('FizzBuzz')
        elif i%6==0:
            print('Buzz')
        elif i%4 == 0:
            print('Fuzz')
        else:
            print(i)

def dopelnienie(n):
    return 8999 - n

def czy_k(n,A,B):
    a1 = []
    b1 = []
    a2 = []
    b2 = []
    for k in range(n):
        for i in range(k):
            a1.append(A[i])
        for i in range(n-k,n):
            b1.append(B[i])
        for i in range(k,n):
            a2.append(A[i])
        for i in range(n-k):
            b2.append(B[i])
        if a1==b1 and a2==b2:
            return 'Prawda', k
        else:
            return "Fałsz"

def is_first_number(n):
    """ Ex 4.1 from matura 2020"""
    if n>4 and n%2 == 0:
        first_numbers = []
        possible_solutions = []
        dividers = []
        definite_solution = ()
        for liczba in range(2,n):
            if liczba % 2 != 0:
                ilosc_roznych_dzielnikow = 0
                for dzielnik in range(2,liczba):
                    if liczba % dzielnik == 0:
                        ilosc_roznych_dzielnikow += 1
                if ilosc_roznych_dzielnikow == 0:
                    first_numbers.append(liczba)

        for number in first_numbers:
            for second_number in first_numbers:
                if n == number + second_number:
                    possible_solutions.append((number,second_number,second_number-number))

        if len(possible_solutions) > 1:
            biggest_difference = 0
            for solution in possible_solutions:
                if solution[2] > biggest_difference:
                    biggest_difference = solution[2]

            for solution in possible_solutions:
                if biggest_difference == solution[2]:
                    return n, solution[0], solution[1]

        else:
            if len(first_numbers) == 2:
                return n, possible_solutions[0], possible_solutions[1]
            elif len(first_numbers) == 1:
                return n, possible_solutions[0], possible_solutions[0]

def couples(string):
    last_letter = string[0]
    length = 0
    word = ''
    list_of_words = []
    final_list_of_words = []
    i = 0
    biggest_length = 0
    for letter in string:
        if letter == last_letter and i != 1:
            length += 1
            word += letter
        else:
            last_letter = letter
            list_of_words.append((word,length))
            word = last_letter
            length = 1

    list_of_words.append((word,length))

    for word in list_of_words:
        if word[1] > biggest_length:
            biggest_length = word[1]

    for word in list_of_words:
        if word[1] == biggest_length:
            final_list_of_words.append(word)

    if len(final_list_of_words) > 1:
        final_list_of_words.remove(final_list_of_words[1])

    return final_list_of_words[0][0],final_list_of_words[0][1]

def jas_malogisa(numbers):
    for number in numbers:
        if number%2 == 0:
            return number

def power_of_three(numbers):
    powers_of_three = []
    for number in numbers:
        if number%3 == 0:
            for i in range(10):
                if 3**i == number:
                    powers_of_three.append(number)
    return len(powers_of_three)

def coma_separated_string_to_list(string):
    last_word = ''
    list_of_words = []
    for letter in string:
        if letter != ';':
            if letter != ',':
                last_word += letter
            else:
                last_word += '.'
        else:
            list_of_words.append(last_word)
            last_word = ''
    if last_word:
        list_of_words.append(last_word)
    return list_of_words

data = ['1;19;0;0;0','1;18;0;0;0','2;22;1;C;1','3;23,6;4;C;1','2;24;1;C;1','1;19;0;0;0']

def exercise_5_1(data):
    gt_eq_20 = 0
    for line in data:
        line_list = coma_separated_string_to_list(line)
        if float(line_list[1]) >= 20:
            gt_eq_20 += 1
    return gt_eq_20

import requests
import json

def does_site_exist(file_path):
    working_sites = []
    not_working_sites = []
    with open(file_path, "r") as file:
        for line in file:
            if requests.get(line[0:-1]).status_code == 200:
                working_sites.append(line[0:-1])
            else:
                not_working_sites.append(line[0:-1])
    return working_sites, not_working_sites

#working_sites, not_working_sites = does_site_exist('C:/Users/janek/Desktop/html vscode/web_sites.txt')

def change_list_into_conj_of_params(my_list, key="id"):
    conj_params = ''
    for param in my_list:
        if my_list.index(param) != len(my_list)-1:
            conj_params += f"{key}={param}&"
        else:
            conj_params += f"{key}={param}"
    return conj_params


# -*-coding: utf-8 -*-
from openerp import models, fields, api

class Session(models.Model):
	_name='openacademy.session'

	name = fields.Char(striing="Nom", required=True)

	start_date = fields.Date(string="Date de debut")

	duration = fields.Float(digit=(6,2), string="Duree", help="Duration in days")

	seats = fields.Float(string="Nombre de places")

	instructor_id = fields.Many2one('res.partner', string="Instructeur")

	course_id = fields.Many2one('openacademy.course', ondelete='cascade',
								string="Cours", required=True)

	attendee_ids = fields.Many2many('openacademy.attendee',
									string='Liste des participants ')
	taken_seats = fields.Float(string="Pourcentage de places prises",
							   compute='_taken_seats')

	state = fields.Selection([
			('draft','Draft'),
			('confirmed','Confirmed'),
			('done','Done'),
		], default='draft')

	@api.multi
	def action_draft(self):
		self.state='draft'

	@api.multi
	def action_confirm(self):
		self.state='confirmed'

	@api.multi
	def action_done(self):
		self.state='done'

	@api.depends('seats', 'attendee_ids')
	def _taken_seats(self):
		for p in self:
			if not p.seats:
				p.taken_seats=0.0
			else:
				p.taken_seats=100.0*len(p.attendee_ids)/p.seats

	@api.onchange('seats', 'attendee_ids')
	def ver(self):
		if self.seats<0:
			return{
				'warning':{
					'title':"Nombres de places incorrects",
					'message':"Le nombre ne saurai etre negatif",
				},

			}
		if self.seats<len(self.attendee_ids):
			return {
				'warning':{
					'title':"Trop de participants",
					'message':"Ajouter le nombre de places ou reduire le nombre de participants",
				},
			}


import sys
input=sys.stdin.readline

T=int(input())
for _ in range(T):
    N,K=map(int,input().split())
    before=input()
    after=input()
    flag=True
    ascii_list=[0 for _ in range(100)]
    for l in before:
        ascii_list[ord(l)-ord('a')]+=1
    for k in after:
        ascii_list[ord(k)-ord('a')]-=1
    # print(ascii_list)
    for i in ascii_list:
        if i!=0: flag=False
    for i in range(N):
        if before[i]!=after[i]:
            if i<K and N-i-1<K: flag=False; break;
    if flag: print("YES")
    else: print("NO")


# Single Element in a Sorted Array
# Array / Binary Search

# https://blog.csdn.net/fuxuemingzhu/article/details/79275636

# 异或
# runtime: faster than 46.02%
class Solution1:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        return reduce(lambda x, y: x^y, nums)

# iterate 遍历
# runtime: faster than 96.90%
class Solution2:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        for i in range(0, len(nums)-1, 2):
            if nums[i] != nums[i+1]:
                return nums[i]
        return nums[-1]

# Binary Search
# runtime: faster than 88.60%
class Solution3:
    def singleNonDuplicate(self, nums: List[int]) -> int:
        l, r = 0, len(nums)-1
        while(l<r):
            mid = l + (r-l)//2
            if mid%2 == 1:
                mid -= 1
            if nums[mid] != nums[mid+1]:  # single element exists in the left
                r = mid
            else:  # single element exists in the right
                l = mid + 2
        return nums[l]


"""
输入两个数  求最大公约数和最小公倍数
"""
def get_gcd(num01,num02):
    """
    求最大公约数
    :param num01:第一个数
    :param num02: 第二个数
    :return: 返回最大公约数
    """
    if num01 > num02:
        for i in range(num02,0,-1):
            if num01 % i == 0 and num02 % i == 0:
                return i
    else:
        # get_gcd(num02,num01)
        for i in range(num01,0,-1):
            if num01 % i == 0 and num02 % i == 0:
                return i

def get_mcm(num01,num02):
    """
    求最小公倍数
    :param num01:
    :param num02:
    :return: 返回最小公倍数
    """
    if num01 > num02:
        for i in range(num01, num01*num02+1):
            if i % num01 == 0 and i % num02 == 0:
                return i
    else:
        # get_gcd(num02,num01)
        for i in range(num02, num01 * num02 + 1):
            if i % num01 == 0 and i % num02 == 0:
                return i

if __name__ =="__main__":
    print(get_gcd(12,36))
    print(get_mcm(12,36))
    print(12*36/get_gcd(12,36))

Demo/第一季案例/第六章/6.3公约数公倍数.py

6.3公约数公倍数.py


import os
import shutil
from git import Repo
from urllib.request import urlretrieve

from flask import current_app
from flask_script import Command
from flask_script import Manager

class VendorDownload(Command):
    """Download vendor libraries"""

    def _delete_path(self, path):
        if os.path.exists(path):
            if os.path.isfile(path):
                os.remove(path)
            else:
                shutil.rmtree(path)

    def _git_download(self, location, vendor_path):
        print('- assets: downloading ' + location)
        repo_name = location.rsplit('/', 1)[-1]
        destination_path = os.path.join(vendor_path, repo_name)
        self._delete_path(destination_path)
        Repo.clone_from(location, destination_path)

    def _file_download(self, location, vendor_path):
        print('- assets: downloading ' + location)
        file_name = location.rsplit('/', 1)[-1]
        file_path = os.path.join(vendor_path, file_name)
        self._delete_path(file_path)
        urlretrieve(location, file_path)

    def run(self):
        """
        Downloads the configured assets
        """

        from app.assets import ASSET_RESOURCES

        vendor_path = os.path.join(current_app.config['BASE_DIR'], 'app', 'assets', 'vendor')

        for resource in ASSET_RESOURCES:
            if resource['type'] == 'git':
                self._git_download(resource['location'], vendor_path)
            elif resource['type'] == 'file':
                self._file_download(resource['location'], vendor_path)

VendorManager = Manager(usage='Manages vendor libraries')
VendorManager.add_command('download', VendorDownload())


'''
https://leetcode.com/problems/implement-trie-prefix-tree/
A trie (pronounced as "try") or prefix tree is a tree data structure used to efficiently store and retrieve keys in a dataset of strings.
There are various applications of this data structure, such as autocomplete and spellchecker.

Implement the Trie class:
Trie() Initializes the trie object.
void insert(String word) Inserts the string word into the trie.
boolean search(String word) Returns true if the string word is in the trie (i.e., was inserted before), and false otherwise.
boolean startsWith(String prefix) Returns true if there is a previously inserted string word that has the prefix prefix, and false otherwise.

Example 1:
Input
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
Output
[null, null, true, false, true, null, true]
'''
'''
Time:O(n)
Space:O(n)
'''
class TrieNode:
    def __init__(self, char = ''):
        self.char = char
        self.children = {}
        self.isEnd = False

class Trie:
    def __init__(self):
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        root = self.root
        for ch in word:
            if ch in root.children:
                root = root.children[ch]
            else:
                newnode = TrieNode(ch)
                root.children[ch] = newnode
                root = newnode
        root.isEnd = True

    def search(self, word: str) -> bool:
        root = self.root
        for ch in word:
            if ch in root.children:
                root = root.children[ch]
            else:
                return False
        return root.isEnd

    def startsWith(self, prefix: str) -> bool:
        root = self.root
        for ch in prefix:
            if ch in root.children:
                root = root.children[ch]
            else:
                return False
        return True


import sys
from itertools import permutations as p, product as P, combinations_with_replacement as h
# from itertools import permutations, combinations, product, combinations_with_replacement

ip = sys.stdin.readline
n, m = map(int, ip().split())
r = range(1, 7)

if m == 1:
    C = P(r, repeat=n)
elif m == 2:
    C = h(r, n)
else:
    C = p(r, n)

for c in C:
    print(*c)

# case = permutations(range(1, n+1), k)
# case = combinations(range(1, n+1), k)
# case = product(range(1, n+1), repeat=k)
# case = combinations_with_replacement(range(1, n+1), k)

# for c in case:
#     print(*c)


import socket
import sys
import re
import struct
import binascii

if __name__=='__main__':

    if len(sys.argv) != 4:
        print("Usage: %s ip port userlist" % sys.argv[0])
        sys.exit(1)

    f = open(sys.argv[3])
    usernames = f.readlines()

    for username in usernames:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((sys.argv[1], int(sys.argv[2])))

        Identity = b"\x00\x04\x1D\xA5"
        s.send(Identity)
        IdentifyResp = s.recv(1024)

        funcMap  = "DCF7FACFFFE400000000000000000000"
        platform = b"WinNT"
        language = b"dscenu.txt"
        username = username.rstrip().upper().encode()

        SignOn = b"\x1A\xA5\x67\x00\x00\x00\x05\x07\x01\x00\x05"+struct.pack('!H',len(username)) +struct.pack('!H',len(platform)+len(username))+b"\x00\x00\x01" +struct.pack('!H',len(platform)+len(username))+struct.pack('!H',len(language))+b"\x2A\x3F"+binascii.unhexlify(funcMap)+platform+username+language
        SignOn = struct.pack('!H',len(SignOn)+2)+SignOn

        print("[~] Trying '%s'" % username.decode())

        s.send(SignOn)
        SignOnResp = s.recv(1024)
        if chr(SignOnResp[8]) == "\x00":
            print("\n[+] User '%s' found!\n" % username.decode())

        s.close()

    f.close()


def po(a,l):
    ans=[]
    for i in range(0,l):
        ans.append(a[i]*a[i])
    return sorted(ans)

s=int(input())
p=list(map(int,input().split()))
print(*po(p,s))


# -*- encoding: utf-8 -*-
import timeit

import runez

from . import TestSettings

class BenchmarkedFunction(object):
    def __init__(self, name, function, iterations):
        self.name = name
        self.function = function
        self.iterations = iterations
        self.error = None
        self.seconds = None

    def __repr__(self):
        return self.report()

    def resolved_call(self):
        result = self.function()
        if isinstance(result, Exception):
            raise result

    def run(self):
        t = timeit.Timer(stmt=self.resolved_call)
        if TestSettings.stacktrace:
            self.seconds = t.timeit(self.iterations)
            return

        try:
            self.seconds = t.timeit(self.iterations)

        except Exception as e:
            self.error = e

    def report(self, fastest=None, indent=""):
        message = "%s%s: " % (indent, self.name)
        if self.error:
            return "%s%s" % (message, TestSettings.represented(self.error, size=-len(message)))

        if self.seconds is None:
            return "%s%s" % (message, runez.red("no result"))

        info = ""
        if fastest and self.seconds and fastest.seconds and self.seconds != fastest.seconds:
            info = runez.dim(" [x %.1f]" % (self.seconds / fastest.seconds))

        unit = u"μ"
        x = self.seconds / self.iterations * 1000000
        if x >= 999:
            x = x / 1000
            unit = "m"

        if x >= 999:
            x = x / 1000
            unit = "s"

        return "%s%s: %.3f %ss/i%s" % (indent, self.name, x, unit, info)

class BenchmarkRunner(object):
    def __init__(self, functions, target_name=None, iterations=100):
        self.benchmarks = []
        for name, func in functions.items():
            self.benchmarks.append(BenchmarkedFunction(name, func, iterations))

        self.target_name = target_name
        self.fastest = None

    def run(self, ):
        for bench in self.benchmarks:
            bench.run()
            if bench.seconds is not None:
                if self.fastest is None or self.fastest.seconds > bench.seconds:
                    self.fastest = bench

    def report(self):
        result = []
        indent = ""
        if self.target_name:
            indent = "  "
            result.append("%s:" % self.target_name)

        for bench in self.benchmarks:
            result.append(bench.report(fastest=self.fastest, indent=indent))

        return "\n".join(result)


import time
start = time.time()
#PART EXERCISE 07
from sklearn.datasets import make_moons
X,y=make_moons(n_samples=10000, noise=0.4, random_state=42)
from sklearn.model_selection import train_test_split
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)
from sklearn.tree import DecisionTreeClassifier
param_grid={'max_depth':[3,5,7,10,15],'min_samples_leaf':[1,2,3]} #Run DecisionTreeClassifier for each combination of max_depth and min_sample_leaf
from sklearn.model_selection import GridSearchCV                     #Finds the best combination of hyperparameters using cross-vaidation
grid_search=GridSearchCV(DecisionTreeClassifier(random_state=42),
                        param_grid,cv=4,                             #Creates the function to find the best model for TreeClassifier using 4 folds
                        scoring='accuracy',n_jobs=1)                #n_jobs=-1: the number of jobs is set to the number of CPU cores
grid_search.fit(X_train,y_train)
print(grid_search.best_estimator_)
grid_search.best_estimator_.fit(X_train,y_train)                                     #Runs GridSearch
from sklearn.metrics import accuracy_score
y_pred = grid_search.best_estimator_.predict(X_test)
print(accuracy_score(y_test, y_pred))

#PART EXERCISE 08
#a Continuing the previous exercise, generate 1,000 subsets of the training
# set, each containing 100 instances selected randomly. Hint: you can use
# Scikit-Learn’s ShuffleSplit class for this.
from sklearn.model_selection import ShuffleSplit
#Yields indices to split data into training and test sets
mini_sets=[]
rs=ShuffleSplit(n_splits=1000,train_size=100,random_state=42)
#n_splits: numbers of re-shuffling and splittings
#train_size
for mini_train_index, mini_test_index in rs.split(X_train):
    X_mini_train = X_train[mini_train_index]
    y_mini_train = y_train[mini_train_index]
    mini_sets.append((X_mini_train, y_mini_train))

#b Train one Decision Tree on each subset, using the best hyperparameter
# values found above. Evaluate these 1,000 Decision Trees on the test set.
# Since they were trained on smaller sets, these Decision Trees will
# likely perform worse than the first Decision Tree, achieving only about
# 80% accuracy.
from sklearn.base import clone
forest=[clone(grid_search.best_estimator_) for _ in range(1000)]
#forest is a list of 1000 models, all the same best_estimator_
accuracy_scores=[]

for tree, (X_mini_train, y_mini_train) in zip(forest, mini_sets):
    tree.fit(X_mini_train, y_mini_train)                         #Train each model with the mini_sets
    y_pred = tree.predict(X_test)                                #Predict using the whole train_set
    accuracy_scores.append(accuracy_score(y_test, y_pred))       #Accuracy measurement for each model

import numpy as np
print(np.mean(accuracy_scores))

#c Now comes the magic. For each test set instance, generate the
# predictions of the 1,000 Decision Trees, and keep only the most
# frequent prediction (you can use SciPy’s mode() function for this).
# This gives you majority-vote predictions over the test set
Y_pred = np.empty([1000, len(X_test)], dtype=np.uint8)  #Creates the empty matrix to receive the predictions

for tree_index,tree in enumerate(forest):               #For each tree model
    Y_pred[tree_index]=tree.predict(X_test)             #Each model predict the output for the test_set

from scipy.stats import mode
y_pred_majority_votes,n_votes=mode(Y_pred, axis=0)      #Selects the most predicted output

#d Evaluate these predictions on the test set: you should obtain a
# slightly higher accuracy than your first model (about 0.5 to 1.5%
# higher).
print(accuracy_score(y_test, y_pred_majority_votes.reshape([-1])))

end = time.time()
print(end - start)


"""
CoinMarketCapService implements all the apis from CoinMarketCap to get the required data
"""

import requests

from tradesense.models.crypto import Crypto

class CoinMarketCapService:
    """
    CoinMarketCapService - Handles all the requests for CoinMarketCap
    """

    def __init__(self, crypto: Crypto):
        self.crypto = crypto

    def get_market_pairs(self):
        """
        Get all the market_pairs from different exchanges based on some filters
        We can set the currency, crypto name, limit results and sort on the key that
        we want

        We sort based on price on descending order because we want to make maximum returns
        :return:
        """
        url = (
            "https://api.coinmarketcap.com/data-api/v3/cryptocurrency/market-pairs/latest?slug={slug}"
            "&start=1&quoteCurrencyId={quote_currency_id}&limit={limit}&category=spot&centerType=all"
            "&sort={sort}&direction={direction}".format(
                slug=self.crypto.slug,
                quote_currency_id=self.crypto.quote_currency_id,
                limit=self.crypto.limit,
                sort=self.crypto.sort,
                direction=self.crypto.sort_direction,
            )
        )

        payload = {}
        headers = {
            "authority": "api.coinmarketcap.com",
            "accept": "application/json, text/plain, */*",
            "accept-language": "en-IN,en-US;q=0.9,en;q=0.8,hi-IN;q=0.7,hi;q=0.6,en-GB;q=0.5",
            "cache-control": "no-cache",
            "dnt": "1",
            "origin": "https://coinmarketcap.com",
            "platform": "web",
            "referer": "https://coinmarketcap.com/",
            "sec-ch-ua": '"Not/A)Brand";v="99", "Google Chrome";v="115", "Chromium";v="115"',
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": '"Windows"',
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-site",
            "sec-gpc": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
            "Chrome/115.0.0.0 Safari/537.36",
            "x-request-id": "0ceaf88618924507884ce85bec07e176",
        }

        response = requests.request("GET", url, headers=headers, data=payload)

        return response.json()["data"]["marketPairs"]


import parse_cards
import numpy as np
import wscreenshot
import time
import cv2
import os

INIT = 0
WAIT = 1
RUN = 2
END = 3
DEBUG = False
WINTEXT = '天天爱掼蛋'
CARDS = ['Joker', 'A', 'K', 'Q', 'J', '10', '9', '8', '7', '6', '5', '4', '3', '2']
CARD_NUMS = [8] * (len(CARDS))
CARD_NUMS[CARDS.index('Joker')] = 4

class DEBUGWS:
    def __init__(self):
        self.d = 'images5'
        img_files = os.listdir(self.d)
        self.img_files = sorted(img_files)
        # self.images = [cv2.imread(os.path.join(d, f)) for f in img_files]
        self.index = 0

    def screenshot(self):
        fname = os.path.join(self.d, self.img_files[self.index])
        img = cv2.imread(fname)
        self.index += 5
        self.index %= len(self.img_files)
        return fname.split('.')[0], img

class JiPaiQi:
    def __init__(self, is_debug=False, do_record=False):
        self.is_debug = is_debug
        self.do_record = do_record
        self.status = WAIT
        self.prev_who = None
        self.who = None
        self.ws = None
        self.my_cards = None
        self.remain_cards = None
        self.out_cards = [[0] * len(CARDS), [0] * len(CARDS), [0] * len(CARDS), [0] * len(CARDS)]
        self.start_timestamp = 'temp'

        self.init()

    def init(self):
        self.prev_who = None
        self.who = None
        self.ws = None
        self.my_cards = None
        self.remain_cards = CARD_NUMS.copy()

        if self.is_debug:
            self.ws = DEBUGWS()
            self.start_timestamp = self.ws.img_files[0].split('.')[0]
        else:
            while True:
                try:
                    self.ws = wscreenshot.Screenshot(WINTEXT)
                except Exception:
                    time.sleep(1)
                    continue
                print('ws created.')
                break
            self.start_timestamp = str(int(time.time() * 10))
        if self.do_record and not os.path.exists(self.start_timestamp):
            os.mkdir(self.start_timestamp)
        self.status = INIT
        print('-----------------init---------------')

    def run(self):
        if not DEBUG:
            timestamp = str(int(time.time()))
            img = self.ws.screenshot()
            if self.do_record:
                cv2.imwrite(os.path.join(self.start_timestamp, timestamp + '.png'), img)
            img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        else:
            timestamp, img = self.ws.screenshot()
            img_gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

        if self.status == INIT:
            is_game_start = parse_cards.parse_game_start(img_gray)
            if is_game_start:
                self.status = WAIT
                print(timestamp, 'game_start')
                return True
            else:
                time.sleep(0.01)
                return False
        elif self.status == WAIT:
            res = parse_cards.parse_clock(img_gray)
            if not res:
                time.sleep(0.01)
                return False
            else:
                direct_num, is_start_clock = res
                if not is_start_clock:
                    print(timestamp, 'error: is_start_clock False', timestamp)
                self.who = direct_num
                self.status = RUN
                self.my_cards = parse_cards.parse_big_cards(img_gray)
                self.my_cards = [x[2] for x in self.my_cards]
                self.my_cards = sorted(self.my_cards)
                for card in self.my_cards:
                    self.remain_cards[CARDS.index(card[1:])] -= 1
                print(timestamp, 'start_clock', self.my_cards, self.remain_cards)
                return True
        elif self.status == RUN:
            if parse_cards.parse_game_start(img_gray):
                self.init()
                return True
            res = parse_cards.parse_clock(img_gray)
            if not res:
                time.sleep(0.01)
                return False
            else:
                direct_num, is_start_clock = res
                self.prev_who, self.who = self.who, direct_num
                if self.prev_who != self.who:
                    # todo: "不出" 与解析失败的区别
                    cards = parse_cards.parse_small_cards(img_gray, self.prev_who)
                    cards = [x[2] for x in cards]
                    cards = sorted(cards)
                    for card in cards:
                        self.remain_cards[CARDS.index(card[1:])] -= 1
                        self.out_cards[self.prev_who][CARDS.index(card[1:])] += 1
                    print(timestamp, self.prev_who, cards, self.remain_cards)
                    return True
                else:
                    time.sleep(0.01)
                    return False
        else:
            return False

if __name__ == '__main__':
    jipaiqi = JiPaiQi()
    while True:
        jipaiqi.run()


"importe le module ArgumentParser"
from argparse import ArgumentParser

# Voici la représentation des Gobblets, n'hésitez pas à l'utiliser.
# 1 pour le joueur 1, 2 pour le joueur 2.
GOBBLET_REPRÉSENTATION = {
    1: ["▫", "◇", "◯", "□"],
    2: ["▪", "◆", "●", "■"],
}

def interpréteur_de_commande():
    "interprète la commande "
    parser = ArgumentParser()
    parser.add_argument('IDUL', help ='Idul du joueur')
    parser.add_argument('-l',dest = 'lister', help = 'lister les parties existantes')
    return parser.parse_args()

def formater_un_gobblet(gobblet):
    "formate un gobblet"
    if gobblet == []:
        return "   "

    return f" {((GOBBLET_REPRÉSENTATION[gobblet[0]])[gobblet[1]])} "

def formater_un_joueur(joueur):
    "formate un joeur"
    jo = joueur['nom']
    j = joueur['piles']
    return f"{jo}: {formater_un_gobblet(j[0])} {formater_un_gobblet(j[1])} {formater_un_gobblet(j[2])}"

def formater_plateau(plateau):
    "formate le plateau"
    lig = 4
    rep = ''
    for i in plateau[:-1] :
        lig -= 1
        listeligne = []
        for u in i:
            listeligne.append(formater_un_gobblet(u))
        rep += (f"{lig}{'|'.join(listeligne)}"+'\n'+' ───┼───┼───┼───'+'\n')

    if plateau[-1]:
        lig -= 1
        listeligne = []
        for u in plateau[-1]:
            listeligne.append(formater_un_gobblet(u))
        rep += (f"{lig}{'|'.join(listeligne)}"+'\n'+f"  {0}   {1}   {2}   {3} ")
    return rep

def formater_jeu(plateau, joueur):
    "formate le jeu"
    longueur = []
    for j in joueur:
        lm = len(j['nom'])
        longueur.append(lm)
    lmax = max(longueur)+3
    esp = max(longueur)

    nbr = ' '*(lmax)+"0   1   2 "+'\n'
    j0 = ' '*(esp-longueur[0])+f"{formater_un_joueur(joueur[0])}"+'\n'
    j1 = ' '*(esp-longueur[1])+f"{formater_un_joueur(joueur[1])}"+'\n'+'\n'
    grille = f"{formater_plateau(plateau)}"
    return nbr+j0+j1+grille

def formater_les_parties(parties):
    "formate les parties"
    rep = ''
    num = 0
    party = parties['parties']
    for dic in party:
        num += 1
        rep += f"{num} : {dic['date']}, {(dic['joueurs'])[0]} vs {(dic['joueurs'])[1]}"
        if dic['gagnant'] is not None:
            rep += f", gagnant:{dic['gagnant']}"
        rep += '\n'
    return rep

def récupérer_le_coup():
    "récupère le coup"
    orig =input('Donnez le numéro de la pile (p) ou la position sur le plateau (x,y):')
    if len(orig) <= 2 :
        origine = int(orig)
    else:
        origine = [int(orig[0]),int(orig[-1])]
    dest = input ('Où voulez-vous placer votre gobelet (x,y):')
    destination = [int(dest[0]),int(dest[-1])]
    return origine, destination


class polynomial():
    monomials = None
    def __init__(self):
        self.monomials = []

    def append(self, poli):
        if type(poli) in (list, tuple):
            for m in poli:
                self.append(m)
        elif type(poli) == polynomial:
            for m in poli.monomials:
                self.append(m)
        else:
            self.monomials.append(poli)

    def __mul__(self, other):
        res = polynomial()
        for m1 in self.monomials:
            if type(other) == monomial:
                res.append(m1*other)
            elif type(other) == polynomial:
                for m2 in other.monomials:
                    res.append(m1*m2)
            else:
                print("polynomial.__mul__ (%s) not implemented"%str(type(other)))
                raise NotImplementedError

        return res

    def __add__(self, other):
        if type(other) == monomial:
            p = polynomial()
            for m in self.monomials:
                p.append(m)
            p.append(other)
            return p
        elif type(other) == polynomial:
            p = polynomial()
            for m in self.monomials:
                p.append(m)
            for m in other.monomials:
                p = p + m
            return p
        else:
            print("polynomial.__add__ (%s) not implemented"%str(type(other)))
            raise NotImplementedError

    def __sub__(self, other):
        if type(other) == monomial:
            p = polynomial()
            for m in self.monomials:
                p.append(m)
            other.coefficient = -other.coefficient
            p.append(other)
            return p
        elif type(other) == polynomial:
            p = polynomial()
            for m in self.monomials:
                p.append(m)
            for m in other.monomials:
                p = p - m
            return p
        else:
            print("polynomial.__sub__(%s) not implemented"%str(type(other)))
            raise NotImplementedError

    def __pow__(self, n):
        #self.coefficient **= n
        #self.literal_part = self.literal_part * n
        p = self*self
        for i in range(0,n-1):
            p*=self
        return p

    def __truediv__(self, other):
        if type(other) == monomial:
            p = polynomial()
            for m in self.monomials:
                p.append(m/other)
            return p
        elif type(other) == polynomial:
            f = algebraic_fraction(self, other)
            return f
        else:
            print("polynomial.__truediv__(%s) not implemented"%str(type(other)))
            raise NotImplementedError

    def sort_by_variable(self, letter):
        self.monomials = [v for v in sorted(self.monomials, key=lambda item: item.degree_for_letter(letter), reverse=True)]
        for m in self.monomials:
            if type(m) == polynomial:
                m.sort_by_variable(letter)

    def replace(self, letter, other_poly):
        p = polynomial()
        print("n monomi:", len(self.monomials))
        for m1 in self.monomials:
            p.append(m1.replace(letter, other_poly))

        return p

    def sum_and_substract(self):
        p = polynomial()
        while len(self.monomials) > 0:
            res = self.monomials[0]
            del self.monomials[0]

            if type(res) == polynomial:
                res.sum_and_substract()

            else:
                ii = 0
                while ii < len(self.monomials):
                    if type(self.monomials[ii]) == polynomial:
                        ii+=1
                        continue

                    if res == self.monomials[ii]:
                        res += self.monomials[ii]
                        del self.monomials[ii]
                    else:
                        ii+=1
            p.append(res)

        for m in p.monomials:
            self.monomials.append(m)

    def __str__(self):
        self.sum_and_substract()
        res = ''
        res = ' '.join([str(x) for x in self.monomials])
        return res

    def __repr__(self):
        return str(self)

    def __len__(self):
        return len(self.monomials)

    def degree(self):
        res = 0
        for m in self.monomials:
            res = max(res, len(m.literal_part))
        return res

    def degree_for_letter(self, letter):
        res = 0
        for m in self.monomials:
            res = max(res, m.degree_for_letter(letter))
        return res

    def to_complete_for_letter(self, letter):
        self.sort_by_variable(letter)
        p = polynomial()
        i = 0
        for deg in range(self.degree_for_letter(letter), -1,-1):
            if i<len(self.monomials) and self.monomials[i].degree_for_letter(letter) == deg:
                p.append(self.monomials[i])
                i += 1
            else:
                p.append( monomial(0,letter*deg) )
        return p

class algebraic_fraction(polynomial):
    denominator = None
    def __init__(self, _numerator = None, _denominator = None):
        polynomial.__init__(self)
        if _numerator:
            self.append(_numerator)

        self.denominator = polynomial()
        if _denominator:
            self.denominator.append(_denominator)
        else:
            self.denominator.append(monomial(1,''))

    def __add__(self, other):
        print("algebraic_fraction.__add__(%s) not implemented"%str(type(other)))
        raise NotImplementedError

    def __sub__(self, other):
        print("algebraic_fraction.__sub__(%s) not implemented"%str(type(other)))
        raise NotImplementedError

    def __mul__(self, other):
        print("algebraic_fraction.__mul__(%s) not implemented"%str(type(other)))
        raise NotImplementedError

    def __truediv__(self, other):
        print("algebraic_fraction.__truediv__(%s) not implemented"%str(type(other)))
        raise NotImplementedError

    def div_by_letter(self, letter):
        Q = polynomial()
        R = polynomial()
        for m in self.monomials:
            R.append(m)
        if self.denominator.degree_for_letter(letter) > self.degree_for_letter(letter):
            return R

        R.sort_by_variable(letter)
        self.denominator.sort_by_variable(letter)

        R = R.to_complete_for_letter(letter)
        #D = self.denominator

        while R.degree_for_letter(letter) >= self.denominator.degree_for_letter(letter):
            i = 0
            #for m in self.denominator.monomials:
            Q.append(R.monomials[0] / self.denominator.monomials[0])

            R.monomials = R.monomials[1:] #eliminazione termine grado massimo
            riporto = polynomial()
            for mm in self.denominator.monomials:
                riporto.append(mm*Q.monomials[-1])

                #la sottrazione viene fatta sotto
                #riporto[-1].coefficient -= riporto[-1].coefficient
            riporto.monomials = riporto.monomials[1:]

            ii = 0
            _R = polynomial()
            for mm in R.monomials:
                if len(riporto.monomials) > ii:
                    _R.append(mm - riporto.monomials[ii])
                else:
                    _R.append(monomial(mm.coefficient, mm.literal_part))
                ii += 1
            R = _R

        return Q,R

    def __str__(self):
        #self.sum_and_substract()
        res = ''
        res = ' '.join([str(x) for x in self.monomials])
        if len(self.denominator) > 0:
            #if it is not a denominator 1
            if not (len(self.denominator) == 1 and (self.denominator.degree() == 0)  and (self.denominator.monomials[0].coefficient == 1)):
                res = '+(' + res + ')/(' + str(self.denominator) + ')'
        return res

    def __repr__(self):
        return str(self)

    def sort_by_variable(self, letter):
        polynomial.sort_by_variable(self, letter)
        polynomial.sort_by_variable(self.denominator, letter)

    def replace(self, letter, other_poly):
        n = polynomial.replace(self, letter, other_poly)
        d = polynomial.replace(self.denominator, letter, other_poly)
        return algebraic_fraction(n, d)

    def sum_and_substract(self):
        polynomial.sum_and_substract(self)
        polynomial.sum_and_substract(self.denominator)

    def degree_for_letter(self, letter):
        n = polynomial.degree_for_letter(self, letter)
        d = polynomial.degree_for_letter(self.denominator, letter)
        return max(n, d)

class monomial():
    coefficient = 0
    literal_part = None
    def __init__(self, c, l):
        self.coefficient = c
        self.literal_part = l

    def sort_literal_part(self):
        letters_aggregated = {}
        for l in self.literal_part:
            if not l in list(letters_aggregated.keys()):
                letters_aggregated[l] = ''
            letters_aggregated[l] = letters_aggregated[l] + l
        self.literal_part = ''
        for k in sorted(list(letters_aggregated.keys())):
            self.literal_part += letters_aggregated[k]

    def __eq__(self, other):
        if not type(other) == monomial:
            return False

        for l in self.literal_part:
            if not self.literal_part.count(l) == other.literal_part.count(l):
                return False
        for l in other.literal_part:
            if not self.literal_part.count(l) == other.literal_part.count(l):
                return False
        return True

    def __add__(self, other):
        if type(other) != monomial:
            return other + self

        #si puo' sommare solo quando la parte letterale e' uguale tra i due monomi
        if self == other:
            return monomial(self.coefficient + other.coefficient, self.literal_part)
        else:
            p = polynomial()
            p.append(self)
            p.append(other)
            return p

    def __sub__(self, other):
        if type(other) == polynomial:
            p = polynomial()
            p.append(self)
            return p-other

        if type(other) != monomial:
            print("monomial.__sub__(%s) not implemented"%str(type(other)))
            raise NotImplementedError

        #si puo' sottrarre solo quando la parte letterale e' uguale tra i due monomi
        if self == other:
            return monomial(self.coefficient - other.coefficient, self.literal_part)
        else:
            p = polynomial()
            p.append(self)
            other.coefficient = -other.coefficient
            p.append(other)
            return p

    def __mul__(self, other):
        if type(other) == polynomial:
            return other*self

        if type(other) != monomial:
            print("monomial.__mul__(%s) not implemented"%str(type(other)))
            raise NotImplementedError

        return monomial(self.coefficient * other.coefficient, self.literal_part + other.literal_part)

    def __pow__(self, n):
        #self.coefficient **= n
        #self.literal_part = self.literal_part * n
        return monomial(self.coefficient**n, self.literal_part * n)

    def __truediv__(self, other):
        if type(other) == polynomial:
            p = polynomial()
            p.append(self)
            return p/other

        if type(other) != monomial:
            print("monomial.__truediv__(%s) not implemented"%str(type(other)))
            raise NotImplementedError

        other_copy = monomial(other.coefficient, other.literal_part)

        cof = self.coefficient
        let = self.literal_part
        #self.coefficient /= other_copy.coefficient
        cof /= other_copy.coefficient
        for l in self.literal_part:
            #self.literal_part = self.literal_part.replace(l, '', other_copy.count(l))
            let = let.replace(l, '', other_copy.literal_part.count(l))
            other_copy.literal_part = other_copy.literal_part.replace(l, '')

        other_copy.coefficient = 1
        m = monomial(cof, let)
        if len(other_copy.literal_part)>0:
            f = algebraic_fraction(m, other_copy)
            return f
        return m

    def replace(self, letter, other):
        m_res = monomial(self.coefficient, self.literal_part.replace(letter, ''))

        if type(other) == monomial:
            for i in range(0,self.literal_part.count(letter)):
                m_res = m_res*other
            return m_res

        if type(other) == polynomial:
            for i in range(0,self.literal_part.count(letter)):
                m_res = m_res*other
            return m_res
        return self

    def __str__(self):
        self.sort_literal_part()

        if self.coefficient == 0:
            return ''
        sign = ('+' if self.coefficient>0 else '-')
        cof = str(abs(self.coefficient)) if self.coefficient != 1.0 else ''

        if self.coefficient == 1.0:
            if len(self.literal_part) < 1:
                cof = '1'
        else:
            if len(self.literal_part) > 0:
                cof += '*'
        return  sign + cof + '*'.join([c for c in self.literal_part])

    def __repr(self):
        return str(self)

    def degree(self):
        return len(self.literal_part)

    def degree_for_letter(self, letter):
        return self.literal_part.count(letter)

p = (monomial(9,'aaa') + monomial(10,'aay') + monomial(6,'ayy')+monomial(4,'yyy')) / (monomial(3,'aa') + monomial(-1,'ay') + monomial(2,'yy'))
print(p)
print(p.div_by_letter('a'))

p=monomial(1,'xxxx')+monomial(1,'x')-monomial(1,'')+monomial(2,'xx')
d=monomial(1,'xx') + monomial(1,'') + monomial(1,'x')
r = p/d
print(r)
r = r.div_by_letter('x')
print(r)

p = monomial(1,'axxx') -monomial(0.5,'ax') + monomial(3,'axx')
print(p/monomial(-0.5,'ax'))

p = (monomial(2,"x") + monomial(1,"y") + monomial(1,"yy"))*monomial(-1,"y")/(monomial(1,'xy') + monomial(3,'yy') - monomial(1,'xx'))
p.sum_and_substract()
p.sort_by_variable('y')
print(p)
p.sort_by_variable('x')
print(p)

pc = polynomial()
#c = -X*X -Y*Y -a*X -b*Y
pc.append([ monomial(-1,"XX"), monomial(-1,"YY"), monomial(-1,"aX"), monomial(-1,"bY")])

pa = polynomial()
pa.append([ monomial(1,"aaBB") / monomial(1,"AA"), monomial(4,"bBC")/monomial(1,"AA"), monomial(-2, "abB")/monomial(1,"A"), monomial(4,"aC")/monomial(1,"A"), monomial(1,"bb"), monomial(-4,"c"), monomial(-4,"BBc")/monomial(1,"AA"), monomial(-4,"CC")/monomial(1,"AA")])
pa = pa.replace("c", pc) #+aaBB/AA -2abB/A +4aC/A +4BBa*X/AA +4a*X +4bBC/AA +bb +4X*X +4Y*Y +4b*Y +4BBX*X/AA +4BBY*Y/AA +4BBb*Y/AA -4CC/AA = 0 #equazione secondo grado calcoliamo il delta in a

pA = monomial(1,'a') - monomial(1,'o')
pa = pa.replace("A", pA)

print(pa)
for i in range(0, len(pa)):
    if type(pa.monomials[i]) == algebraic_fraction:
        print("dividing by A: " + str(pa.monomials[i]))
        res = pa.monomials[i].div_by_letter('a')
        print("result: " + str(res))
        pa.append(res[1]/pa.monomials[i].denominator)
        pa.monomials[i] = res[0]
pa.sort_by_variable('a')
print(pa)

#delta1a=BB/AA
deltaa = monomial(1, 'BB') / monomial(1,'AA')
#delta1b=-2bB/A +4C/A +4BBX/AA +4X
deltab = monomial(-2, 'bB') / monomial(1,'A') + monomial(4, 'C') / monomial(1,'A') + monomial(4, 'BBX') / monomial(1,'AA') + monomial(4,'X')
#delta1c=           +4bBC/AA                  +bb               +4X*X            +4Y*Y             +4b*Y             +4BBX*X/AA                            +4BBY*Y/AA                               +4BBb*Y/AA                          -4CC/AA
deltac = monomial(4, 'bBC') / monomial(1,'AA') + monomial(1,'bb') + monomial(4,'XX') + monomial(4,'YY') + monomial(4,'bY') + monomial(4,'BBXX') / monomial(1,'AA') + monomial(4,'BBYY') / monomial(1,'AA') + monomial(4,'BBbY') / monomial(1,'AA') -monomial(4,'CC') / monomial(1,'AA')
delta = deltab*deltab - monomial(4,'')*deltaa*deltac
#sol = (deltab*deltab - math.sqrt(delta))/(monomial(2,'')*deltaa)
#+aaRR/TT +4bRG/TT -2abR/T +4aG/T  +bb +4X*X +4Y*Y +4a*X +4b*Y +4RRX*X/TT +4RRY*Y/TT +4RRa*X/TT +4RRb*Y/TT -4GG/TT = 0
print(delta)
#+(+20.0AAAAAAAAAABBbb -80.0AAAAAAAAAABCb -160.0AAAAAAAABBBXb -160.0AAAAAAAABXb -80.0AAAAAAAAABXb +80.0AAAAAAAAAACC +320.0AAAAAAAABBCX +320.0AAAAAAAACX +160.0AAAAAAAAACX +320.0AAAAAABBBBXX +640.0AAAAAABBXX +320.0AAAAAAABBXX +320AAAAAAXX +320AAAAAAAXX +80AAAAAAAAXX -64.0AAAAAAAAAABBBCb -64.0AAAAAAAAAAABBBCb -16.0AAAAAAAAAAAABBBCb -16.0AAAAAAAAAAAABBbb -16.0AAAAAAAAAAAAABBbb -4.0AAAAAAAAAAAAAABBbb -64.0AAAAAAAAAAAABBXX -64.0AAAAAAAAAAAAABBXX -16.0AAAAAAAAAAAAAABBXX -64.0AAAAAAAAAAAABBYY -64.0AAAAAAAAAAAAABBYY -16.0AAAAAAAAAAAAAABBYY -64.0AAAAAAAAAAAABBYb -64.0AAAAAAAAAAAAABBYb -16.0AAAAAAAAAAAAAABBYb -64.0AAAAAAAAAABBBBXX -64.0AAAAAAAAAAABBBBXX -16.0AAAAAAAAAAAABBBBXX -128.0AAAAAAAABBBBYY -128.0AAAAAAAAABBBBYY -32.0AAAAAAAAAABBBBYY -192.0AAAAAABBBBYb -192.0AAAAAAABBBBYb -48.0AAAAAAAABBBBYb +256.0AAAABBCC +256.0AAAAABBCC +64.0AAAAAABBCC)/(+4AA +4AAA +6AAAA)
#+(+20.0AAAAAAAAAABBbb -80.0AAAAAAAAAABCb -160.0AAAAAAAABBBXb -160.0AAAAAAAABXb -80.0AAAAAAAAABXb +80.0AAAAAAAAAACC +320.0AAAAAAAABBCX +320.0AAAAAAAACX +160.0AAAAAAAAACX +320.0AAAAAABBBBXX +640.0AAAAAABBXX +320.0AAAAAAABBXX +320AAAAAAXX +320AAAAAAAXX +80AAAAAAAAXX -64.0AAAAAAAAAABBBCb -64.0AAAAAAAAAAABBBCb -16.0AAAAAAAAAAAABBBCb -16.0AAAAAAAAAAAABBbb -16.0AAAAAAAAAAAAABBbb -4.0AAAAAAAAAAAAAABBbb -64.0AAAAAAAAAAAABBXX -64.0AAAAAAAAAAAAABBXX -16.0AAAAAAAAAAAAAABBXX -64.0AAAAAAAAAAAABBYY -64.0AAAAAAAAAAAAABBYY -16.0AAAAAAAAAAAAAABBYY -64.0AAAAAAAAAAAABBYb -64.0AAAAAAAAAAAAABBYb -16.0AAAAAAAAAAAAAABBYb -64.0AAAAAAAAAABBBBXX -64.0AAAAAAAAAAABBBBXX -16.0AAAAAAAAAAAABBBBXX -128.0AAAAAAAABBBBYY -128.0AAAAAAAAABBBBYY -32.0AAAAAAAAAABBBBYY -192.0AAAAAABBBBYb -192.0AAAAAAABBBBYb -48.0AAAAAAAABBBBYb +256.0AAAABBCC +256.0AAAAABBCC +64.0AAAAAABBCC)/+2AA(+1 +2A +3AA)
#+(+10.0AAAAAAAABBbb -40.0AAAAAAAABCb -80.0AAAAAABBBXb -80.0AAAAAABXb -40.0AAAAAAABXb +40.0AAAAAAAACC +160.0AAAAAABBCX +160.0AAAAAACX +80.0AAAAAAACX +160.0AAAABBBBXX +320.0AAAABBXX +160.0AAAAABBXX +160AAAAXX +160AAAAAXX +40AAAAAAXX -32.0AAAAAAAABBBCb -32.0AAAAAAAAABBBCb -8.0AAAAAAAAAABBBCb -8.0AAAAAAAAAABBbb -8.0AAAAAAAAAAABBbb -2.0AAAAAAAAAAAABBbb -32.0AAAAAAAAAABBXX -32.0AAAAAAAAAAABBXX -8.0AAAAAAAAAAAABBXX -32.0AAAAAAAAAABBYY -32.0AAAAAAAAAAABBYY -8.0AAAAAAAAAAAABBYY -32.0AAAAAAAAAABBYb -32.0AAAAAAAAAAABBYb -8.0AAAAAAAAAAAABBYb -32.0AAAAAAAABBBBXX -32.0AAAAAAAAABBBBXX -8.0AAAAAAAAAABBBBXX -64.0AAAAAABBBBYY -64.0AAAAAAABBBBYY -16.0AAAAAAAABBBBYY -96.0AAAABBBBYb -96.0AAAAABBBBYb -24.0AAAAAABBBBYb +128.0AABBCC +128.0AAABBCC +32.0AAAABBCC)/(+1 +2A +3AA)

"""

Python 3.10.0 (tags/v3.10.0:b494f59, Oct  4 2021, 19:00:18) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
++(+aaBB)/(+AA) +(+4.0bBC)/(+AA) +(-2.0abB)/(+A) +(+4.0aC)/(+A) +bb +-4XX -4YY -4aX -4bY +(+-4.0BBXX -4.0BBYY -4.0BBaX -4.0BBbY)/(+AA) +(-4.0CC)/(+AA)
SyntaxError: invalid decimal literal
a = 1
b=2
c=3
A = 10
B = 20
C = 30
X = 100
Y = 200
++(+a*a*B*B)/(+A*A) +(+4.0*b*B*C)/(+A*A) +(-2.0*a*b*B)/(+A) +(+4.0*a*C)/(+A) +b*b ++4*X*X +4*Y*Y +4*a*X +4*b*Y +(++4.0*B*B*X*X +4.0*B*B*Y*Y +4.0*B*B*a*X +4.0*B*B*b*Y)/(+A*A) +(-4.0*C*C)/(+A*A)
1010024.0
+a*a*B*B/(A*A) -2*a*b*B/A +4*a*C/A +4*B*B*a*X/(A*A) +4a*X +4*b*B*C/(A*A) +b*b +4*X*X +4*Y*Y +4*b*Y +4*B*B*X*X/(A*A) +4*B*B*Y*Y/(A*A) +4*B*B*b*Y/(A*A) -4*C*C/(A*A)
SyntaxError: invalid decimal literal
+a*a*B*B/(A*A) -2*a*b*B/A +4*a*C/A +4*B*B*a*X/(A*A) +4*a*X +4*b*B*C/(A*A) +b*b +4*X*X +4*Y*Y +4*b*Y +4*B*B*X*X/(A*A) +4*B*B*Y*Y/(A*A) +4*B*B*b*Y/(A*A) -4*C*C/(A*A)
1010024.0
sorted('dac')
['a', 'c', 'd']
128/2
64.0
192/2
96.0
delta1a=B*B/(A*A)
delta1b=-2*b*B/A +4*C/A +4*B*B*X/(A*A) +4*X
delta1c=+4*b*B*C/(A*A) +b*b +4*X*X +4*Y*Y +4*b*Y +4*B*B*X*X/(A*A) +4*B*B*Y*Y/(A*A)
delta1b*delta1b - 4.0*delta1a*delta1c
-12010416.0
+(+10.0AAAAAAAABBbb -40.0AAAAAAAABCb -80.0AAAAAABBBXb -80.0AAAAAABXb -40.0AAAAAAABXb +40.0AAAAAAAACC +160.0AAAAAABBCX +160.0AAAAAACX +80.0AAAAAAACX +160.0AAAABBBBXX +320.0AAAABBXX +160.0AAAAABBXX +160AAAAXX +160AAAAAXX +40AAAAAAXX -32.0AAAAAAAABBBCb -32.0AAAAAAAAABBBCb -8.0AAAAAAAAAABBBCb -8.0AAAAAAAAAABBbb -8.0AAAAAAAAAAABBbb -2.0AAAAAAAAAAAABBbb -32.0AAAAAAAAAABBXX -32.0AAAAAAAAAAABBXX -8.0AAAAAAAAAAAABBXX -32.0AAAAAAAAAABBYY -32.0AAAAAAAAAAABBYY -8.0AAAAAAAAAAAABBYY -32.0AAAAAAAAAABBYb -32.0AAAAAAAAAAABBYb -8.0AAAAAAAAAAAABBYb -32.0AAAAAAAABBBBXX -32.0AAAAAAAAABBBBXX -8.0AAAAAAAAAABBBBXX -64.0AAAAAABBBBYY -64.0AAAAAAABBBBYY -16.0AAAAAAAABBBBYY -96.0AAAABBBBYb -96.0AAAAABBBBYb -24.0AAAAAABBBBYb +128.0AABBCC +128.0AAABBCC +32.0AAAABBCC)/(+2*A +3*A*A)

"""


import snscrape.modules.twitter as sntwitter
import pandas as pd
from langdetect import detect

# Creando la lista donde se almacenaron los Tweets  de la keyword a buscar.
tweets_list = []
keywords = 'TopGunMaverick'

# Usando TwitterSearchScraper para hacer scrape data y agregar tweets a la lista
for i,tweet in enumerate(sntwitter.TwitterSearchScraper(f'{keywords} since:2022-05-25 until:2022-05-27').get_items()):
    if i>11700:
        break
    tweets_list.append([tweet.date, tweet.content, tweet.user])

# Creando el DataFrame con la lista de tweets
tweets_df = pd.DataFrame(tweets_list, columns=['Datetime', 'Text', 'Username'])
print(tweets_df)

#----LANGUAGE DETECTION-----

lang_list = []
for tweet in tweets_df.Text:
    lang = detect(tweet)
    lang_list.append(lang)

df = pd.DataFrame({'tweet': tweets_df.Text, 'lang': lang_list})
df_es = df.loc[df['lang'] == 'es']
df_en = df.loc[df['lang'] == 'en']

#----EXPORT TO CSV-----

df.to_csv(f'{keywords}.csv')
df_es.to_csv(f'{keywords}_ES.csv')
df_en.to_csv(f'{keywords}_EN.csv')


from ctypes import c_ssize_t
import nltk
nltk.download('popular')
from nltk.stem import WordNetLemmatizer
lemmatizer = WordNetLemmatizer()
import pickle
import numpy as np
from autocorrect import Speller
spell = Speller(lang='en')
from keras.models import load_model
model = load_model('model.h5')
import json
import random
import itertools
from flask import Flask, render_template, request
intents = json.loads(open('data.json',encoding="utf8").read())
words = pickle.load(open('texts.pkl','rb'))
classes = pickle.load(open('labels.pkl','rb'))

def clean_up_sentence(sentence):
    # tokenize the pattern - split words into array
    sentence_words = nltk.word_tokenize(sentence)
    # stem each word - create short form for word
    sentence_wordsL = [lemmatizer.lemmatize(word.lower()) for word in sentence_words]
    if "and" in sentence_words:
        sentence_wordsL = [lemmatizer.lemmatize(spell(word.lower())) for word in sentence_words]
        i=sentence_words.index("and")
        sentence_words1=sentence_wordsL[:i]
        sentence_words2=sentence_wordsL[i+1:]
        return (sentence_words1,sentence_words2)
    else :
        return sentence_wordsL

# return bag of words array: 0 or 1 for each word in the bag that exists in the sentence
def bow(sentence, words, show_details=True):
    # tokenize the pattern
    sentence_words = clean_up_sentence(sentence)
    if str(type(sentence_words))=='<class \'list\'>':
    # bag of words - matrix of N words, vocabulary matrix
        bag = [0]*len(words)
        for s in sentence_words:
            for i,w in enumerate(words):
                if w == s:
                    # assign 1 if current word is in the vocabulary position
                    bag[i] = 1
                    if show_details:
                        print ("found in bag: %s" % w)
        return np.array(bag)
    else :
        bag1 = [0]*len(words)
        bag2 = [0]*len(words)
        for (s,p) in zip(sentence_words[0],sentence_words[1]):
            for i,w in enumerate(words):
                if w == s:
                    # assign 1 if current word is in the vocabulary position
                    bag1[i] = 1
                    if show_details:
                        print ("found in bag: %s" % w)
                if w == p :
                     bag2[i] = 1
        return (np.array(bag1) , np.array(bag2))

def predict_class(sentence, model):
    # filter out predictions below a threshold
    p = bow(sentence, words,show_details=False)
    if str(type(p)) == '<class \'numpy.ndarray\'>':
        res = model.predict(np.array([p]))[0]
        ERROR_THRESHOLD = 0.25
        results = [[i,r] for i,r in enumerate(res) if r>ERROR_THRESHOLD]
        # sort by strength of probability
        results.sort(key=lambda x: x[1], reverse=True)
        return_list = []
        for r in results:
            return_list.append({"intent": classes[r[0]], "probability": str(r[1])})
        return return_list
    elif str(type(p)) == '<class \'tuple\'>' :
        res1 = model.predict(np.array([p[0]]))[0]
        ERROR_THRESHOLD = 0.25
        results1 = [[i1,r1] for i1,r1 in enumerate(res1) if r1>ERROR_THRESHOLD]
        # sort by strength of probability
        results1.sort(key=lambda x: x[1], reverse=True)
        return_list1 = []
        for r1 in results1:
            return_list1.append({"intent": classes[r1[0]], "probability": str(r1[1])})
        res2 = model.predict(np.array([p[1]]))[0]
        ERROR_THRESHOLD = 0.25
        results2 = [[i2,r2] for i2,r2 in enumerate(res2) if r2>ERROR_THRESHOLD]
        # sort by strength of probability
        results2.sort(key=lambda x: x[1], reverse=True)
        return_list2 = []
        for r2 in results2:
            return_list2.append({"intent": classes[r2[0]], "probability": str(r2[1])})
        return (return_list1 , return_list2)

def getResponse(ints, intents_json):
 if str(type(ints))=='<class \'list\'>':
  try:
    tag = ints[0]['intent']
    list_of_intents = intents_json['intents']
    for i in list_of_intents:
        if(tag == i['tag']):
            result = random.choice(i['responses'])
  except IndexError:
    result ='Sorry i can\'t understand you '
 elif str(type(ints))=='<class \'tuple\'>':
      try :
        tag1 = ints[0][0]['intent']
        tag2 = ints[1][0]['intent']
        list_of_intents = intents_json['intents']
    #result=str(ints)
    #return result

        for i in list_of_intents:
            if(tag1==i['tag']):
                result1 = random.choice(i['responses'])

        for i in list_of_intents:
            if(tag2==i['tag']):
                result2 = random.choice(i['responses'])
        result= result1 + " and " + result2
      except IndexError:
        result ='Sorry i can\'t understand your question '
 return result

def chatbot_response(msg):
    ints = predict_class(msg, model)
    res = getResponse(ints, intents)
    return res

app = Flask(__name__)
app.static_folder = 'static'

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/get")
def get_bot_response():
    userText = request.args.get('msg')
    return chatbot_response(userText)

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=80)


class Utilities:

    @staticmethod
    def to_dict(obj):
        # result = dict()
        # for prop, value in vars(obj).items():
        #     result[prop] = str(value)
        # return result
        res = {column.key: getattr(obj, attr)
               for attr, column in obj.__mapper__.c.items()}
        return res

    @staticmethod
    def verify_parameters(jsonP, params):
        for param, value in jsonP.items():
            if param in params and value is None:
                return None
        return jsonP


import pandas as pd
from Bio import SearchIO
import os
import re
import sqlite3

conn = sqlite3.connect('NFixDB')
c = conn.cursor()

c.execute('CREATE TABLE IF NOT EXISTS nitrogenase_i3 (GenomeID varchar, SeqID varchar, EValue float, BitScore float, GeneName varchar, GTDB_Tax varchar, NCBI_TaxID number, NCBI_Tax varchar)')
conn.commit()

c.execute('CREATE TABLE IF NOT EXISTS nonNitrogenase_i3 (GenomeID varchar, SeqID varchar, EValue float, BitScore float, GeneName varchar, GTDB_Tax varchar, NCBI_TaxID number, NCBI_Tax varchar)')
conn.commit()
'''
df = pd.DataFrame(pd.read_table('/projects/raw_lab/databases/GTDB/ar53_metadata_r207.tsv'))
df2 = pd.DataFrame(pd.read_table('/projects/raw_lab/databases/GTDB/bac120_metadata_r207.tsv'))

frame = [df, df2]
complete_df = pd.concat(frame)

complete_df = complete_df[['gtdb_genome_representative', 'gtdb_taxonomy', 'ncbi_taxid', 'ncbi_taxonomy_unfiltered']].copy()
complete_df.columns = ['GenomeID', 'GTDB_Tax', 'NCBI_TaxID', 'NCBI_Tax']
complete_df.to_csv("complete_taxonomy.tsv", sep = "\t")
'''
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

complete_df = pd.DataFrame(pd.read_table('complete_taxonomy.tsv'))

result_target = []
query_id = []
hit_id = []
evalue = []
bitscore = []

#OOR stands for "Out Of Range", AKA the values that do not meet our E-value threshold
oor_target = []
oor_queryid = []
oor_hitid = []
oor_evalue = []
oor_bitscore = []

#parse through files in output directory
directory = 'bac120_ar53_results_i3'
for filename in os.listdir(directory):
    f = os.path.join(directory, filename)
    reg = r'^([\w]+_[\w]+.[\w])'
    regex = re.match(reg, filename).group()
    if os.path.isfile(f):
        #parse file using SearchIO/HmmerIO
        for result in SearchIO.parse(f, 'hmmer3-text'):
            for item in result.hits:
                reg2 = r'([a-zA-Z]+)_([a-zA-Z]+)-([a-zA-Z]+)_([a-zA-Z]+)'
                regex2 = re.match(reg2, result.id).group(2)
                #check the evalue cutoff and append the data to the corresponding lists
                if item.evalue < 9.9e-10:
                    result_target.append(regex)
                    query_id.append(regex2)
                    hit_id.append(item.id)
                    evalue.append(item.evalue)
                    bitscore.append(item.bitscore)
                #if it does not meet the evalue cutoff, append it to the OOR lists
                else:
                    oor_target.append(regex)
                    oor_queryid.append(regex2)
                    oor_hitid.append(item.id)
                    oor_evalue.append(item.evalue)
                    oor_bitscore.append(item.bitscore)

evalue_dict = {'GenomeID' : result_target, 'GeneName' : query_id, 'SeqID' : hit_id, 'EValue' : evalue, 'Bitscore' : bitscore}
evalue_df = pd.DataFrame(evalue_dict).sort_values('EValue')
evalue_df = pd.merge(evalue_df, complete_df, on = "GenomeID", how = "left")

oor_dict = {'GenomeID' : oor_target, 'GeneName' : oor_queryid, 'SeqID' : oor_hitid, 'EValue' : oor_evalue, 'Bitscore' : oor_bitscore}
oor_df = pd.DataFrame(oor_dict).sort_values('EValue')
oor_df = pd.merge(oor_df, complete_df, on = "GenomeID", how = "left")

evalue_df.to_csv("evalue_taxonomy_i3.tsv", sep = "\t")
evalue_df.to_sql('nitrogenase_i3', conn, if_exists = 'replace')

oor_df.to_csv("oor_taxonomy_i3.tsv", sep = "\t")
oor_df.to_sql('nonNitrogenase_i3', conn, if_exists = 'replace', index = False)

'''
c.execute("SELECT * FROM nitrogenase")
for row in c.fetchall():
    print(row)

c.execute("SELECT * FROM nonNitrogenase")
for row in c.fetchall():
    print(row)

print(evalue_df)
print()
print(oor_df)'''


# -*- coding: utf-8 -*-

from socialoauth.sites.base import OAuth2

class FacebookApp(OAuth2):
    GRAPH_URL        = 'https://graph.facebook.com'
    AUTHORIZE_URL    = 'https://www.facebook.com/dialog/oauth'
    ACCESS_TOKEN_URL = '{0}/oauth/access_token'.format(GRAPH_URL)

    def build_api_url(self, url):
        return url

    def build_api_data(self, **kwargs):
        data = {
            'access_token': self.access_token,
            'fields': 'name,gender,picture.type(large)'
        }
        data.update(kwargs)
        return data

    def parse_token_response(self, res):
        self.access_token = res['accessToken']
        self.expires_in = int(res['expiresIn'])
        self.uid = res['userID']
        self.refresh_token = None

        res = self.api_call_get(self.GRAPH_URL+'/me')

        self.name = res['name']
        self.avatar = res['picture']['data']['url']
        self.avatar_large = self.avatar
        self.gender = res['gender'] == u"male" and "M" or "F"


import os

from flask import Blueprint, Flask, render_template
from .sitemap import sitemap_blueprint
from flask_webpack import Webpack
from filters import filters

brigade = Blueprint('brigade', __name__)

def detect_webpack_manifest_path(expected_path):
    path = os.path.abspath(expected_path)
    if os.path.exists(path):
        return path
    else:
        raise Exception("Webpack Build Missing -- Make sure webpack is running. " \
                "Start it with `webpack --watch`")

def create_app():
    app = Flask(__name__, static_folder='build/public/', static_url_path='/assets')
    app.config['SECRET_KEY'] = 'sekrit!'
    app.config['WEBPACK_MANIFEST_PATH'] = detect_webpack_manifest_path('./brigade/build/manifest.json')

    webpack = Webpack()
    webpack.init_app(app)

    if 'SERVER_NAME' in os.environ:
        app.config['SERVER_NAME'] = os.environ['SERVER_NAME']
    if 'SITEMAP_URL_SCHEME' in os.environ:
        app.config['SITEMAP_URL_SCHEME'] = os.environ['SITEMAP_URL_SCHEME']
    app.config['SITEMAP_INCLUDE_RULES_WITHOUT_PARAMS'] = True

    app.register_blueprint(brigade)
    app.register_blueprint(filters)
    app.register_blueprint(sitemap_blueprint)

    @app.errorhandler(404)
    def page_not_found(e):
        return render_template('404.html'), 404

    return app

from . import views # noqa:E402


import crawl_prices
import models

prices = crawl_prices.crawl_bitcoin()

for row in prices['dataset']['data']:
    models.add_price_point(
    code='BTC',
    date=row[0],
    open=row[1],
    high=row[2],
    low=row[3],
    close=row[4],
    volume_local=row[5],
    volume_currency=row[6],
    weighted_price=row[7]
    )


# every parent node have only two children node and the one on left must be smaller or equal to the parent node and right node must be equal or greater than the parent node, also no two node have same value

class Node:
	def __init__(self, data):
		self.data = data
		self.parent = None
		self.right = None
		self.left = None

class BinarySearchTree:
	add_new_node = Node
	def __init__(self):
		self.root = None

	def insert(self, data):
		node = self.add_new_node(data)
		if self.root is None:
			self.root = node
			return

		current = self.root
		while current:
			if current.data >= data:
				if current.left is None:
					current.left = node
					node.parent = current
					return
				current = current.left
			else:
				if current.right is None:
					current.right = node
					node.parent = current
					return
				current = current.right

if __name__ == '__main__':
	bst = BinarySearchTree()
	bst.insert(20)
	bst.insert(9)
	bst.insert(25)
	bst.insert(5)
	bst.insert(12)
	bst.insert(11)
	bst.insert(11)
	bst.insert(11)
	bst.insert(11)
	bst.insert(11)
	bst.insert(11)
	bst.insert(11)

	print(bst.root.right.right.data)


"""
File      : office.py
Date      : February, 2017
Author    : eugene liyai
Desc      : Office class that holds office specification and attributes

"""

# ============================================================================
# necessary imports
# ============================================================================

from room import Room

class Office(Room):
    '''
            Office class inherits from Room super class.
            The class inherits all attributes and
            methods from the parent class.
            Initiates a Office room instance.
    '''

    def __init__(self, name):

        super(Office, self).__init__(
            roomname=name, roomtype='OFFICE', roomspace=6)

    # ============================================================================
    # add to room
    # ============================================================================
    def update_room_space(self):
        '''
                Livingroom.update_office_space()

                updates the space available in the office instance.
        '''
        update_space = None
        roomspace = self.get_room_space()

        if roomspace:
            self.set_room_space(roomspace - 1)
            update_space = True
        else:
            update_space = False

        return update_space

    # ============================================================================
    # remove from room
    # ============================================================================
    def free_room_space(self):
        '''
                Livingroom.free_office_space()

                frees up space in the office instance.
        '''
        free_space = False
        roomspace = self.get_room_space()

        if 0 <= roomspace < 6:
            self.set_room_space(roomspace + 1)
            free_space = True

        return free_space


from sonzo.telnet import TelnetServer, TelnetProtocol
import logging
import time

LMAGENTA = chr(27) + "[1;35m"
WHITE    = chr(27) + "[37m"
LGREEN   = chr(27) + "[1;32m"
LOGIN    = "\n\r\n\r\n\r                             {}Welcome to Sonzo Chat!\n\r\n\r{}"

class ChatClient(TelnetProtocol):
    """
    Custom server side client object inherited from sonzo.SonzoClient.

    This client IS NOT an actual client side telnet client.
    """
    def _init_(self, sock, addr):
        # Overridden medthod
#        SonzoClient.__init__(self, sock, addr)
        self.name = addr

    def onConnect(self):
        # Overridden medthod
        logging.info(" {} has connected.".format(self.addrport()))

        for user in USERLIST:
            systemMessage(user, "{} has joined the chat!\n\r".format(self.addrport()))
        USERLIST.append(self)
        systemMessage(self, LOGIN.format(LMAGENTA, WHITE))

    def onDisconnect(self):
        # Over-ridden medthod
        logging.info(" {} disconnecting.".format(self.addrport()))
        USERLIST.remove(self)
        for user in USERLIST:
            if user is not self:
                systemMessage(user, "{} logged off.\n\r".format(self.addrport()))

    def dataRecieved(self, data):
        """
        Overriden function.  Called when data is recieved from client.
        """
        chat(self, data)

    def disconnect(self):
        """
        Disconnect user.
        """
        systemMessage(self, "Goodbye!\n\r")
        self._new_messages = False
        self._connected = False

def color(c, color):
    if c._ansi:
        return color
    else:
        return ""

def chat(client, msg):
    #Check to see if someone issues a command.
    if msg.startswith("=a".lower()):
        client.setANSIMode()
        systemMessage(client, "ANSI: {}\n\r".format(client._ansi))
        logging.info(" {} changing ANSI to: {}.".format(client.addrport(), client._ansi))
        return
    if msg.startswith("/quit".lower()):
        client.disconnect()
        return
    if msg.startswith("~".lower()):
        logging.info(" {} changing character mode to: {}.".format(client.addrport(), client._character_mode))
        client.setCharacterMode()
        client.systemMessage("Character Mode is now: {}\n\r".format(client._character_mode))
        return
    if msg.startswith("/runlater".lower()):
        chatsrvr.callLater("Ran 2 seconds later.", func=print, runtime=2)
    if msg.startswith("/install".lower()):
        chatsrvr.install("Fart!", func=print)
    # If no command, say it in the chat room.
    for c in USERLIST:
        sendMessage(client, c, msg)

def sendMessage(sender, client, message):
    message = "{}{} says, {}{}".format(color(sender, LGREEN), sender.addrport(), color(client, WHITE), message)
    client.send(message)

def systemMessage(client, message):
    client.send(message)

if __name__ == '__main__':
    logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
    USERLIST = []
    chatclient = ChatClient
    chatsrvr = TelnetServer(clientclass=chatclient, address='', port=23)
    logging.info(" Sonzo Chat Server starting up...")
    # Example of adding a looping call.
    tensecondloop = chatsrvr.loopingCall("Looping at 10 seconds", func=print)
    tensecondloop.start(10)

    chatsrvr.run()


from setuptools import setup, find_packages
import sys, os

f = open('README.rst')
long_description = f.read().strip()
long_description = long_description.split('split here', 1)[1]
f.close()

version = '0.3.0'

setup(name='didit',
      version=version,
      description="Lightweight, commandline tool to remember what I did last week",
      long_description=long_description,
      classifiers=[
          "Development Status :: 5 - Production/Stable",
          "Environment :: Console",
          "Intended Audience :: Developers",
          "Intended Audience :: End Users/Desktop",
          "Intended Audience :: System Administrators",
          "License :: OSI Approved :: GNU General Public License (GPL)",
          "Natural Language :: English",
          "Topic :: Office/Business :: News/Diary",
          "Topic :: Text Processing :: Markup",
          "Topic :: Utilities",
      ],
      keywords='',
      author='Ralph Bean',
      author_email='ralph.bean@gmail.com',
      url='http://github.com/ralphbean/didit',
      license='GPLv3+',
      packages=find_packages(exclude=['ez_setup', 'examples', 'tests']),
      include_package_data=True,
      zip_safe=False,
      scripts=[
          "scripts/didit-remember",
          "scripts/didit-report"
      ],
      install_requires=[
          "mako",
          # -*- Extra requirements: -*-
      ],
      entry_points="""
      # -*- Entry points: -*-
      """,
      )


# from periods.period import TimeInterval as Period
from django.urls import path
from django.shortcuts import redirect

from directory.views import forms, list, remote_search, working_calendar

urlpatterns = [
    path('remote_search/<str:model_name>/', remote_search.RemoteSearch.as_view(), name='remote_search'),

    path('mlm_agent/', list.ModelList.as_view(), name='mlm_agent_list', kwargs=dict(model_name='agent')),
    path('working_calendar/', working_calendar.WorkingCalendarView.as_view(), name='working_calendar'),

    path('<str:model_name>/', list.ModelList.as_view(), name='model_list'),
    path('<str:model_name>/<int:pk>/', list.ModelDetail.as_view(), name='model_detail'),
    path('<str:parent_model_name>/<int:parent_pk>/relation/<str:related_name>/',
         list.ModelList.as_view(), name='model_relation_list'),

    # path('<str:parent_name>/<int:parent_id>/<str:model_name>/list', views.ListTemplate.as_view(),
    #      name='child_model_list'),

    # path('<str:parent_name>/<str:parent_id>/<str:model_name>/action/<str:action>',
    #      views_forms.ModelActions.as_view(), name='model_action'),

    path('<str:model_name>/<str:action>/', forms.ModelActions.as_view(), name='model_action'),
    path('<str:model_name>/<str:action>/<int:pk>/', forms.ModelActions.as_view(), name='model_instance_action'),

    path('', lambda request: redirect('directory:model_list', model_name='person'), name='directory_index'),
]


#!/usr/bin/env python
try:
	import queue
except ImportError:
	import Queue as queue
import subprocess
import sys
import threading
import time

# read arguments
try:
	_, taskfile, concurrent, duration = sys.argv
	duration = float(duration)
	concurrent = int(concurrent)
except:
	print ("Usage: %s TASKFILE NUMBER_OF_CONCURRENT_INVOCATIONS TIMELIMIT_SECONDS")
	exit(1)

def submit_jobstep():
	while True:
		task = q.get()
		if task is None:
			break
		walltime, cmd = task
		if walltime + time.time() > deadline:
			print ('Skipped: %s %s' % (walltime, cmd))
		else:
			print ('Started: %s %s' % (walltime, cmd))
			process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
			process.wait()
			print ('Completed: %s %s %s' % (process.returncode, walltime, cmd))
		q.task_done()

# set deadline
deadline = time.time() + duration

# start workers
q = queue.Queue()
workers = []
for i in range(concurrent):
    w = threading.Thread(target=submit_jobstep)
    w.start()
    workers.append(w)

walltimes, cmds = [], []
with open(taskfile) as fh:
	for line in fh:
		walltime, cmd = line.strip().split(' ', 1)
		walltimes.append(int(walltime))
		cmds.append(cmd)
tasks = sorted(zip(walltimes, cmds), key=lambda _: _[0])
for task in tasks:
	q.put(task)

q.join()
for i in range(concurrent):
	q.put(None)
for worker in workers:
	worker.join()