import time

from config import Configuration as Cfg

def print_obj_and_acc(objective, accuracy, which_set):

    objective_str = '{} objective:'.format(which_set.title())
    accuracy_str = '{} accuracy:'.format(which_set.title())
    print("{:32} {:.5f}".format(objective_str, objective))
    print("{:32} {:.2f}%".format(accuracy_str, accuracy))

def performance(nnet, which_set, print_=False):

    objective = 0
    accuracy = 0
    batches = 0
    for batch in nnet.data.get_epoch(which_set):
        inputs, targets, _ = batch
        err, acc = nnet.forward(inputs, targets)
        objective += err
        accuracy += acc
        batches += 1

    objective /= batches
    accuracy *= 100. / batches

    if print_:
        print_obj_and_acc(objective, accuracy, which_set)

    return objective, accuracy

def performance_val_avg(nnet, layer):

    C = Cfg.C.get_value()

    val_objective = 0
    val_accuracy = 0

    for batch in nnet.data.get_epoch_val():
        inputs, targets, _ = batch
        err, acc = layer.hinge_avg(inputs, targets)
        val_objective += err
        val_accuracy += acc

    val_objective /= nnet.data.n_val
    val_accuracy *= 100. / nnet.data.n_val

    val_objective += layer.norm_avg() / (2. * C)
    for other_layer in nnet.trainable_layers:
        if other_layer is not layer:
            val_objective += other_layer.norm() / (2. * C)

    return val_objective, val_accuracy

def hinge_avg(nnet, layer):

    train_objective = 0
    train_accuracy = 0
    for batch in nnet.data.get_epoch_train():
        inputs, targets, _ = batch
        new_err, new_acc = layer.hinge_avg(inputs, targets)

        train_objective += new_err
        train_accuracy += new_acc

    train_objective *= 1. / nnet.data.n_train
    train_accuracy *= 100. / nnet.data.n_train

    return train_objective, train_accuracy

def primal_avg(nnet, layer):

    train_objective, train_accuracy = hinge_avg(nnet, layer)

    train_objective += layer.warm_reg_avg()

    return train_objective, train_accuracy

def performance_train_avg(nnet, layer):

    C = Cfg.C.get_value()

    train_objective, train_accuracy = hinge_avg(nnet, layer)

    train_objective += layer.norm_avg() / (2. * C)

    for llayer in nnet.trainable_layers:
        if llayer is not layer:
            train_objective += llayer.norm() / (2. * C)

    return train_objective, train_accuracy

def checkpoint(nnet, layer):

    if nnet.data.dataset_name == "imagenet":
        return

    C = Cfg.C.get_value()

    hinge_loss, train_accuracy = hinge_avg(nnet, layer)

    primal_objective = hinge_loss + layer.warm_reg_avg()

    train_objective = hinge_loss + layer.norm_avg() / (2. * C)

    for other_layer in nnet.trainable_layers:
        if other_layer is not layer:
            train_objective += other_layer.norm() / (2. * C)

    dual_objective = layer.get_dual()

    val_objective, val_accuracy = performance_val_avg(nnet, layer)

    train_objective = float(train_objective)
    train_accuracy = float(train_accuracy)
    val_objective = float(val_objective)
    val_accuracy = float(val_accuracy)
    primal_objective = float(primal_objective)
    hinge_loss = float(hinge_loss)
    dual_objective = float(dual_objective)

    t = time.time() - nnet.clock

    nnet.log['time_stamp'].append(t)
    nnet.log['layer_tag'].append(layer.name)

    nnet.log['train_objective'].append(train_objective)
    nnet.log['train_accuracy'].append(train_accuracy)

    nnet.log['val_objective'].append(val_objective)
    nnet.log['val_accuracy'].append(val_accuracy)

    nnet.log['primal_objective'].append(primal_objective)
    nnet.log['hinge_loss'].append(hinge_loss)
    nnet.log['dual_objective'].append(dual_objective)

    print("Pass %i - Epoch %i - Layer %s" %
          (nnet.pass_, len(nnet.log['time_stamp']), layer.name))
    print_obj_and_acc(train_objective, train_accuracy, which_set='train')
    print_obj_and_acc(val_objective, val_accuracy, which_set='val')

    if Cfg.draw_on_board:
        data_dict = {'Objective': train_objective,
                     'Accuracy': train_accuracy,
                     'Primal Objective': primal_objective,
                     'Hinge Loss': hinge_loss,
                     'Dual Objective': dual_objective}
        nnet.board_monitor_train.add_scalar_dict(data_dict)
        data_dict = {'Objective': val_objective,
                     'Accuracy': val_accuracy}
        nnet.board_monitor_val.add_scalar_dict(data_dict)

def check_dual(nnet, layer):

    dual_objective = layer.get_dual()
    t = time.time() - nnet.clock
    nnet.log['dual_objective'].append(dual_objective)

    nnet.log['time_stamp'].append(t)
    nnet.log['layer_tag'].append(layer.name)


message = """
Simultaneous eqn solver

     Ax + By = C
     Dx + Ey = F"""
print(message)

# a = int(input("A = "))
# b = int(input("B = "))
# c = int(input("C = "))
# d = int(input("D = "))
# e = int(input("E = "))
# f = int(input("F = "))

req_ver = ["A = ", "B = ", "C = ", "D = ", "E = ", "F = "]
v = {}  # v stores the variables needed for the calc.

while True:
 for i in req_ver:
  print(i, end="")
  check = False
  while True:  # This block checks to make sure the userInput is an integer
   try:
    z = int(input())
    check = True
   except ValueError:
    print(f"Please input an interger value for {i[0]}")
    print(i, end="")
   if check:  # Break the checking loop after confirmation
    break
  v[i[0]] = z
 if len(v) == 6: # Break the entire loop after i got the required variables "v"
  break

Y = (v["F"] *v["A"]-v["D"]*v["C"])/(v["E"]*v["A"]-v["D"]*v["B"])
X = (v["B"] *v["F"]-v["E"]*v["C"])/(v["B"]*v["D"]-v["E"]*v["A"])
print(f"Y = {Y}\nX = {X}")


#!/usr/bin/env python
# -*- coding: utf-8 -*-
from abc import ABCMeta, abstractmethod
from bson.binary import Binary
import math
import pickle

import numpy
import six

@six.add_metaclass(ABCMeta)
class PoolInterface():
    """
    Pool interface defintion

    """
    @abstractmethod
    def add(self, state, action, reward, next_state, done,
            next_actions=None, priority=1):
        """
        Pool is used to store experience data, like:
          (state, action, reward, next_state). It must contains 4 things :
            state: state of environment
            action: executed action with given state
            reward: feedback of action with given state
            next_state: next state of environment after executing action
        These 2 things is optional:
            next_actions: available actions of next state
            priority: priority (loss) of this record
        """
        pass

    @abstractmethod
    def remove(self, record_id):
        """
        Remove record from pool with record_id
        """
        pass

    @abstractmethod
    def sample(self, size):
        """
        Sample records from pool with given size.
        """
        pass

    @abstractmethod
    def update(self, priorities):
        """
        Update each records' priority
        """
        pass

    @abstractmethod
    def size(self):
        """
        Get size of current pool
        """
        pass

    @abstractmethod
    def amount(self):
        """
        Get number of records in pool
        """
        pass

    @abstractmethod
    def all(self):
        """
        Get all experiences of pool by generator
        """
        pass

class MemoryPool(PoolInterface):
    """
    MemoryPool uses `dict` to store experience data. Data can be sampled
    after it add to pool. Sample method is biased random sampling with
    priority.

    Args:
        pool_size (int): sepcify size of memory pool. `0` for unlimited
            (default: 0)

    Returns:
        MemoryPool object

    Examples:
        # Init pool
        >>> mpool = MemoryPool(3000)
        # Add data to pool
        >>> mpool.add(
                state=[1, 2, 3], action=3, reward=100, next_state=[4, 5, 6]
            )
        # Sample data for training
        >>> records = mpool.sample(30)
        >>> print(len(records))
        30
        # Update priority of data
        >>> priorities = [(key1, 10), (key2, 0), (key3, 9), ...]
        >>> mpool.update(priorities)
    """

    def __init__(self, pool_size=0):
        if isinstance(pool_size, int):
            if pool_size < 0:
                raise TypeError("Pool size should be positive integer")
            self._size = pool_size

        self._experiences = {}
        self._q_front = 0

    def add(self, state, action, reward, next_state, done,
            next_actions=None, priority=1, info=None):
        """
        Add new data to experience pool.

        Args:
            state: any type as long as it can describe the state of environment
            action: any type as long as it can represent executed action with
                above state
            reward: also free type for action feedback
            next_state: Like state but it is for describing next state
            next_actions: For next state's actions (Default: None),
            priority: It specify the priority of data (Default: 0)

        Returns:
            amount: record number in pool

        Examples:
            >>> mpool.add(
                    state=[0, 0, 1], action=1,
                    reward=100, next_state=[1, 0, 0]
                )
            >>> mpool.add(
                    state={'a': 1, 'b': 0}, action=3,
                    reward=-1, next_state={'a': -1, 'b': 1},
                    next_actions=[3, 1, 0], priority=3.5
                )

        """
        if numpy.isnan(priority):
            priority = 1e-3
        elif priority < 1e-3:
            priority = 1e-3
        elif priority > 1e+3:
            priority = 1e+3

        if self._q_front > six.MAXSIZE:
            self._q_front = 0

        while self._q_front in self._experiences:
            self._q_front += 1

        self._experiences[self._q_front] = {
            'state': state,
            'action': action,
            'reward': reward,
            'next_state': next_state,
            'next_actions': next_actions,
            'done': done,
            'priority': priority,
            'info': info,
        }

        if self.amount() > self.size() > 0:
            min_p = 1e+9
            min_key = 0
            for key, record in self._experiences.items():
                if record['priority'] < min_p:
                    min_p = record['priority']
                    min_key = key
            self.remove(min_key)
        return self.amount()

    def remove(self, key):
        """
        Remove record from pool with key.

        Args:
            key: the key of record in dictionary

        Returns:
            None

        Examples:
            # Remove 100th data in pool
            >>> pool.remove(100)

        """
        return self._experiences.pop(key)

    def sample(self, size):
        """
        Sample records from pool with given size.

        Args:
            size (int): sampling size

        Returns:
            samples (list):
                [
                (index, {'state': ..., 'action': ..., 'reward': ...,
                 'next_state': ..., 'next_actions': ..., 'priority': ...,}),
                (...),
                ]

        Examples:
            # Biased random sampling 100 records
            >>> pool.sample(100)

        """
        dist = []
        keys = []
        for k, record in self._experiences.items():
            dist.append(record['priority'])
            keys.append(k)

        sum_d = float(sum(dist))
        prob = [item / sum_d for item in dist]

        if size > 0:
            if size > self.amount():
                size = self.amount()
            keys = numpy.random.choice(
                keys, size=size, p=prob, replace=False
            )
        else:
            keys = []

        for k in keys:
            yield k, self._experiences[k]

    def update(self, priorities):
        """
        Update each records' priority

        Args:
            priorities (list):
                [
                 (index, priority),
                 (...),
                 ...
                ]

        Returns:
            None

        Examples:
            >>> pool.update([
                    (0, 10),
                    (1, 0),
                    (2, 3)
                ])

        """
        for key, priority in priorities:
            if numpy.isnan(priority):
                p = 1e-3
            elif priority < 1e-3:
                p = 1e-3
            elif priority > 1e+3:
                p = 1e+3
            else:
                p = priority

            try:
                self._experiences[key]['priority'] = p
            except:
                pass

    def size(self):
        """
        Get size of current pool

        Args:
            None

        Returns:
            pool_size (int): limited size of pool

        Examples:
            >>> mpool = MemoryPool(300)
            >>> print(mpool.size())
            300

        """
        return self._size

    def amount(self):
        """
        Get number of records in pool

        Args:
            None

        Returns:
            number (int): number of records

        Examples:
            >>> mpool = MemoryPool(300)
            >>> print(mpool.size())
            300
            >>> print(mpool.amount())
            0
            >>> mpool.add(1, 2, 3, 4)
            >>> print(mpool.amount())
            1

        """
        return len(self._experiences)

    def all(self):
        """
        Get all experiences of pool by generator

        Args:
            None

        Returns:
            record (dict): experience record

        Examples:
            >>> mpool = MemoryPool(300)
            >>> for item in mpool.all():
                    print(item)
            {'state': ...}
            {'state': ...}
            ...

        """
        for key, record in self._experiences.items():
            yield key, record

class MongoPool(PoolInterface):
    """
    MongoPool store experience data to db. Data must be numpy array.

    Args:
        collection (pymongo.collection.Collection): Specific collection for
            storing experience data
        pool_size (int): sepcify size of pool. `0` for unlimited
            (default: 0)

    Returns:
        MongoPool object

    Examples:
        # Init pool
        >>> client = MongoClient()
        >>> mpool = MongoPool(client['DB']['Collection'])
        # Add data to pool
        >>> mpool.add(
                state=[1, 2, 3], action=3, reward=100, next_state=[4, 5, 6]
            )
        # Sample data for training
        >>> records = mpool.sample(30)
        >>> print(len(records))
        30
        # Update priority of data
        >>> priorities = [(id1, 10), (id2, 0), (id3, 9), ...]
        >>> mpool.update(priorities)
    """

    def __init__(self, collection, pool_size=0):
        if isinstance(pool_size, int):
            if pool_size < 0:
                raise TypeError("Pool size should be positive integer")
            self._size = pool_size

        self._collection = collection

    def add(self, state, action, reward, next_state, done,
            next_actions=None, priority=1, info=None):
        """
        Add new data to experience pool.

        Args:
            state: any type as long as it can describe the state of environment
            action: any type as long as it can represent executed action with
                above state
            reward: also free type for action feedback
            next_state: Like state but it is for describing next state
            next_actions: For next state's actions (Default: None),
            priority: It specify the priority of data (Default: 0)

        Returns:
            amount: record number in pool

        Examples:
            >>> mpool.add(
                    state=[0, 0, 1], action=1,
                    reward=100, next_state=[1, 0, 0]
                )
            >>> mpool.add(
                    state={'a': 1, 'b': 0}, action=3,
                    reward=-1, next_state={'a': -1, 'b': 1},
                    next_actions=[3, 1, 0], priority=3.5
                )

        """
        if numpy.isnan(priority):
            priority = 1e-3
        elif priority < 1e-3:
            priority = 1e-3
        elif priority > 1e+3:
            priority = 1e+3

        last_record = self._get_last()
        if last_record:
            index = last_record['index'] + 1
        else:
            index = 0

        data = {
            'index': index,
            'state': Binary(pickle.dumps(state)),
            'action': Binary(pickle.dumps(action)),
            'reward': Binary(pickle.dumps(reward)),
            'next_state': Binary(pickle.dumps(next_state)),
            'next_actions': Binary(pickle.dumps(next_actions)),
            'done': done,
            'priority': priority,
            'info': info,
        }

        self._collection.insert_one(data)
        if self.amount() > self.size() > 0:
            min_p = 1e+9
            min_index = 0
            for i, record in enumerate(self._experiences):
                if record['priority'] < min_p:
                    min_p = record['priority']
                    min_index = i
            self.remove(min_index)
        return self.amount()

    def remove(self, record_id):
        """
        Remove record from pool with record_id.

        Args:
            record_id: the index of data

        Returns:
            None

        Examples:
            # Remove 100th data in pool
            >>> pool.remove(100)

        """
        self._collection.remove({'index': record_id})

    def sample(self, size):
        """
        Sample records from pool with given size.

        Args:
            size (int): sampling size

        Returns:
            samples (list):
                [
                (index, {'state': ..., 'action': ..., 'reward': ...,
                 'next_state': ..., 'next_actions': ..., 'priority': ...,}),
                (...),
                ]

        Examples:
            # Biased random sampling 100 records
            >>> pool.sample(100)

        """
        dist = []
        indexes = []
        for record in self._collection.find({}, {'index': 1, 'priority': 1}):
            dist.append(record['priority'])
            indexes.append(record['index'])

        sum_d = float(sum(dist))
        prob = [item / sum_d for item in dist]

        if size > 0 and indexes:
            if size > len(indexes):
                size = len(indexes)

            indexes = numpy.random.choice(
                indexes,
                size=size, p=prob, replace=False
            )
            indexes = indexes.tolist()
        else:
            indexes = []

        samples = list()
        for record in self._collection.find({'index': {'$in': indexes}}):
            record['state'] = pickle.loads(record['state'])
            record['action'] = pickle.loads(record['action'])
            record['reward'] = pickle.loads(record['reward'])
            record['next_state'] = pickle.loads(record['next_state'])
            record['next_actions'] = pickle.loads(record['next_actions'])
            samples.append((record['index'], record))
        return samples

    def update(self, priorities):
        """
        Update each records' priority

        Args:
            priorities (list):
                [
                 (index, priority),
                 (...),
                 ...
                ]

        Returns:
            None

        Examples:
            >>> pool.update([
                    (0, 10),
                    (1, 0),
                    (2, 3)
                ])

        """
        for index, priority in priorities:
            if numpy.isnan(priority):
                p = 1e-3
            elif priority < 1e-3:
                p = 1e-3
            elif priority > 1e+3:
                p = 1e+3
            else:
                p = priority

            self._collection.update_one(
                {"index": index}, {"$set": {"priority": p}}
            )

    def size(self):
        """
        Get size of current pool

        Args:
            None

        Returns:
            pool_size (int): limited size of pool

        Examples:
            >>> mpool = MemoryPool(300)
            >>> print(mpool.size())
            300

        """
        return self._size

    def amount(self):
        """
        Get number of records in pool

        Args:
            None

        Returns:
            number (int): number of records

        Examples:
            >>> mpool = MemoryPool(300)
            >>> print(mpool.size())
            300
            >>> print(mpool.amount())
            0
            >>> mpool.add(1, 2, 3, 4)
            >>> print(mpool.amount())
            1

        """
        return self._collection.count()

    def all(self):
        """
        Get all experiences of pool by generator

        Args:
            None

        Returns:
            record (dict): experience record

        Examples:
            >>> mpool = MemoryPool(300)
            >>> for item in mpool.all():
                    print(item)
            {'state': ...}
            {'state': ...}
            ...

        """
        condition = {"$query": {}, "$orderby": {"id": 1}}
        for record in self._collection.find(condition):
            record['state'] = pickle.loads(record['state'])
            record['action'] = pickle.loads(record['action'])
            record['reward'] = pickle.loads(record['reward'])
            record['next_state'] = pickle.loads(record['next_state'])
            record['next_actions'] = pickle.loads(record['next_actions'])
            yield record

    def _get_last(self):
        condition = {"$query": {}, "$orderby": {"index": -1}}
        return self._collection.find_one(condition)


"""
BABY - The Assistant
    - This is a very basic assistant sofware
    made mojorly with pygame that recognizes users voice commands only in
    english language on keyword and some direct statement basis and
    gives relevant information is possible.
    -It's name is a pun.

What it can do?
    - Search for anything on the internet.
    - Ask her to open any website on webbrowser.
    - Ask her to play any song by the keyword "play".
    - Find discriptions of various personalities by the keyword "who is".
    - Tell the time.
    - Tell the Date.
    - Tell the Day of Week.
    - User can tell her that its their birthday and see the magic.
    - Ask her to tell a joke.
    - Many more interesting tasks.

Project Details:
    Started on - 19 Dec, 2020
    Created By - Om Gupta
    Supported OS - Microsoft Windows
    Modules Used:
        - Standard Library Modules:
            -sys
            -os
            -time
            -datetime
            -random
            -webbrowser
        - Additional Modules:
            - pygame
            - speech_recognition
            - pyttsx3
            - pywhatkit
            - wikipedia
            - googlesearch
            - joke
            - pyjokes
"""

# Importing Required Standard Lib Modules
from math import fabs
import random, sys, os, datetime, webbrowser
import time as t

# Safe importing the Additional Modules
def downloadModule(module = "") -> str: #Give module name as in documentation in strings
    """
    Installs the module through command line using pip.
    """
    os.system('cls')
    try:
        os.system('cmd /c "pip -v"')
        os.system('cls')
    except:
        print('\n\t`pip` COMMAND NOT FOUND WHICH IS NEEDED FOR DOWNLOADING MODULE! \n')
        try:
            os.system('cmd /c "curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py"')
        except:
            print('\n\n\t KINDLY INSTALL PIP MANUALLY!\n\n\n')

        os.system('cmd /c "python get-pip.py"')

    print('\n\tDOWNLOADING MISSING MODULE : '+module+' :\n')
    os.system('cmd /c "pip install ' + module)
    os.system('cls')

try:
    import pygame as p
    os.system('cls')
except:
    downloadModule("pygame")
    import pygame as p
    os.system('cls')

try:
    import speech_recognition
except:
    downloadModule("SpeechRecognition")
    import speech_recognition

try:
    import pyaudio #For using Microphone as source
except:
    downloadModule("pipwin")
    os.system('cmd /c "py -m pipwin install pyaudio')
    os.system('cls')

try:
    import pyttsx3 #For converting text to speech
except:
    downloadModule("pypiwin32")
    downloadModule("wheel")
    downloadModule("-U setuptools")
    downloadModule("pyttsx3==2.90")
    import pyttsx3

try:
    import pywhatkit
except:
    downloadModule("pywhatkit")
    import pywhatkit

try:
    import wikipedia
except:
    downloadModule("wikipedia")
    import wikipedia

try:
    import googlesearch
except:
    downloadModule("beautifulsoup4")
    downloadModule("google --user")
    import googlesearch

try:
    import pyjokes as pj
except:
    downloadModule("pyjokes")
    import pyjokes as pj

try:
    from joke.jokes import icanhazdad
except:
    downloadModule("axju-jokes")
    from joke.jokes import icanhazdad

# Required only while Packaging
def resource_path(relative_path):
    """ Get absolute path to resource, works for dev and for PyInstaller """
    try:
        # PyInstaller creates a temp folder and stores path in _MEIPASS
        base_path = sys._MEIPASS
    except Exception:
        base_path = os.path.abspath(".")

    return os.path.join(base_path, relative_path)

resource_path('Fonts\Font.ttf')
resource_path('Sounds\click.mp3')
resource_path('Sounds\listen.mp3')
resource_path('Images\Background.png')
resource_path('Images\micdown.png')
resource_path('Images\iconSmall.png')
resource_path('Images\listen.png')
resource_path('Images\hoverbutton.png')

def about(introMsg = "Hi i am baby, I am the creation of Mr.Om Gupta. What I can do? Search for anything on the internet, open any website, play any song, find any personalities' summary, tell the time, Date and Day of Week, wish you HAPPY BIRTHDAY, make you laugh with a joke and many more interesting stuff! ------To close me you can say bye bye or go or any such line")-> str:
    """
    Small discription of the project which is spoken when called.
    """
    p.mouse.set_cursor(p.SYSTEM_CURSOR_WAITARROW)

    blitPara(introMsg, wordsPerLine=7, lineSpacing=120)
    speakText(introMsg.replace("Om Gupta","Owm Goopta"))
    # speakText("Hi i am baby, I am the creation of Mr.Owm Goopta.")

def intro():
    """
    For introduction
    """
    blitBig("Hi!", 200, 200)
    speakText("Hi!")
    p.display.update(screen.fill("black"))

    blitBig("I'm", 200, 180)
    blitBig("Baby",170,290)
    speakText("I'm Baby")
    p.display.update(screen.fill("black"))

    blitBig("I'd love to help",x=30,y=200)
    blitBig("you!",180,310)
    speakText("I'd love to help you")
    p.display.update(screen.fill("black"))

def blit(text, x=100, y=100):
    """
    Display `text` on screen.

    Keyword arguments:

    * x - x-coordinate of text
    * y - y-coordinate of text
    """
    txt = smallFont.render(text, True, (30, 30, 30))
    p.display.update(screen.blit(txt, (x, y)))

def blitBig(text, x=100, y=100):
    """
    Display `text` on screen.

    Keyword arguments:

    * x - x-coordinate of text
    * y - y-coordinate of text
    """
    txt = bigFont.render(text, True, (255, 255, 255))
    p.display.update(screen.blit(txt, (x, y)))

def blitPara(text, wordsPerLine = 5, lineSpacing = 100):
    """
    Display paragraph `text` on screen.

    Keyword arguments:

    * wordsPerLine - (number) Number of words to be written in a single line
    * lineSpacing - (number) Space between two lines
    """
    x = text.split()
    a = 0
    b = wordsPerLine
    for i in range(len(x)):
        n = x[a:b]
        r = ''
        for j in n:
            r += j + ' '
        p.display.update(blit(r, 60, lineSpacing))
        a += wordsPerLine
        b += wordsPerLine
        lineSpacing += 20

def cleanText(text, erase):
    """
    Erases a part of the `text`.

    Arguments:

    * text - (string) a string which has to be cleaned
    * erase - (string) Part of text to be erased
    """
    new_text = text.replace(erase, '')
    return new_text

def speakText(text):
    """
    Converts string in `text` to speech.
    """
    engine.say(text)
    engine.runAndWait()

def playSound(filename) ->str:
    """
    Plays the audio file at `filename`
    """
    p.mixer.music.load(filename)
    p.mixer.music.play()

def listen():
    """
    Prepares microphone for listening to a command and
    returns the command if command started with `baby`
    """
    try:
        with speech_recognition.Microphone() as source:

            p.mouse.set_cursor(p.SYSTEM_CURSOR_WAITARROW)
            listener.adjust_for_ambient_noise(source)
            p.mouse.set_cursor(p.SYSTEM_CURSOR_ARROW)

            p.display.update(screen.blit(listening, (0, 0)))
            blit("Listening...")

            playSound("Sounds\listen.mp3")

            voice = listener.listen(source, timeout=5)
            command = listener.recognize_google(voice)
            command = command.lower()
            print("\nCommand:\n",command,"\n")
            if 'baby' in command:
                command = cleanText(command, 'baby')
                return command
            else:
                speakText("Please call my name baby, and then give the command")
    except:
        speakText("Your words are not clear or your mike isn't connected")
        speakText("please try again")

def googleit(text) -> str:
    """
    Search the given query string using Google and opens it in the default browser
    """
    try:
        url = googlesearch.search(text, tld='com', lang='en', num=1, stop=1, pause=2.0)
        for i in url:
            print(i)
            webbrowser.open(i)
    except :
        webbrowser.open("https://www.google.com/search?q="+text)

def actionBaby():
    """
    Initiate fetching and analyzation of command from user.
    """
    try:
        runState = True

        # Setting mic button up
        t.sleep(.1)
        p.display.update(screen.blit(background, (0, 0)))
        p.display.update(screen.blit(credits,(385,570)))
        p.display.update(screen.blit(aboutIcon, (485, 5)))

        # Fetch the command from user
        os.system("cls")
        command = listen()

        # Resetting the screen
        p.display.update(screen.blit(background, (0, 0)))
        p.display.update(screen.blit(credits,(385,570)))
        p.display.update(screen.blit(aboutIcon, (485, 5)))

        # ANALYSING THE COMMAND

        # Command types for direct interaction
        disrespectfulStatements = [
            'are you mad',
            'are you crazy',
            'have you gone nuts',
            'get lost']

        healthQuestions = [
            "how are you",
            "what's up",
            "what you doing",
            "are you okay"]

        userAffectionQuestions = [
                "do you like me",
                "do you love me",
                "what do you think about me"
            ]

        exitStatements = [
            "you can leave",
            "close yourself",
            "you may leave",
            "you can go now",
            "exit yourself",
            "bye bye",
            "you can go"
            ]

        # Keyword based analysis of command
        if 'play' in command:
            song = command.replace('play', '')
            p.display.update(blitPara('Playing' + song + ' for you...'))
            speakText('Playing' + song + ' for you')
            pywhatkit.playonyt(song)

        elif 'search' in command:
            command = command.replace("search ", "")
            p.mouse.set_cursor(p.SYSTEM_CURSOR_WAITARROW)

            p.display.update(blit("Please wait..."))
            p.display.update(blitPara('Searching ' + command + '...'))

            speakText("Please wait")
            speakText('Searching ' + command)

            if 'search for' in command:
                command = cleanText(command, 'search for')
                googleit(command)
            elif 'search google for' in command:
                command = cleanText(command, 'search google for')
                googleit(command)
            elif 'search google for what is' in command:
                command = cleanText(command, 'search google for what is')
                googleit(command)
            elif 'search the internet for' in command:
                command = cleanText(command, 'search the internet for')
                googleit(command)
            elif 'search the web for' in command:
                command = cleanText(command, 'search the web for')
                googleit(command)
            else:
                googleit(command)

        elif 'time' in command:
            time = datetime.datetime.now().strftime('%I:%M %p')  # 01 : 01 AM
            p.display.update(blit('It is ' + time))
            time = time.replace(":", " ")
            if 'AM' in time:
                time = time.replace('AM', 'A M')
            if 'PM' in time:
                time = time.replace('PM', 'P M')
            if '0' in time[0] or '0' in time[3]:
                time = time.replace('0', ' ')
            speakText('it is' + time)

        elif "date" in command:
            date = datetime.datetime.now().date()
            p.display.update(blit("Today is " + str(date)))
            speakText("Today is " + str(date))

        elif "your name" in command:
            p.display.update(blit("My name is baby ... just baby"))
            speakText('My name is baby, just baby.')

        elif "birthday" in command:
            p.display.update(blit("Happy Birthday to you"))
            speakText("Happy Birth day to you")
            speakText("here is a song for you ")
            songListHBD = [
                "Best Happy Birthday To You | Happy Birthday Songs Remix 2020",

                "Birthday Song ❤ Best Good Wishes For Your Birthday 2021 WhatsApp Happy Bday Lyrics Video for adults",

                "Aww Tera Happy Bday|ABCD 2 |Varun Dhawan Shraddha Kapoor |Sachin - Jigar |D.Soldierz | Birthday song"
            ]
            selectedSongHBD = random.choice(songListHBD)
            pywhatkit.playonyt(selectedSongHBD)
            speakText('in joy.')

        elif 'day' in command:
            day_name = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
            day = datetime.datetime.weekday(datetime.datetime.today())
            p.display.update(blit("Today is " + day_name[day]))
            speakText("today is " + day_name[day])

        elif 'who created you' in command :
            blit('Om Gupta created me')
            speakText('owm goopta created me.')

        elif 'who is ' in command:
            print(command)
            try:
                person = command.replace('who is ', '')
                print(person)
                if 'om gupta' in command:
                    blit('Om Gupta is my creator.')
                    speakText('Owm Goopta is my creator')
                else:
                    blit(person.upper(),50,50)
                    info = wikipedia.summary(person, sentences = 2)
                    print(info)

                    blitPara(info)

                    s = info.split(".")
                    for j in s:
                        speakText(j)
            except:
                p.display.update(blit("This is what I found on internet..."))
                p.mouse.set_cursor(p.SYSTEM_CURSOR_WAITARROW)
                speakText("This is what I found on internet")
                cleanText(command, 'who is ')
                googleit(command)

        elif "website of" in command:
            try:
                search = command.replace("open", "")
            except:
                pass

            p.display.update(blit("Please wait... Opening", x=60,y=80))

            blitPara(search)

            p.mouse.set_cursor(p.SYSTEM_CURSOR_WAITARROW)

            speakText("Please wait")
            speakText("Opening" + search)
            googleit(search)

        elif "joke" in command:
            joke_received = random.choice([pj.get_joke('en','neutral'),icanhazdad()])
            blitPara(joke_received,6)
            speakText(joke_received)
            t.sleep(2)

        # Direct Interactions - at last because requires more checking
        elif [i for i in disrespectfulStatements if i in command] :
            blit('Sorry! Have I done anything wrong?')
            speakText('Sorry! Have I done anything wrong?')

        elif [i for i in healthQuestions if i in command]:
            blitPara("I'm absolutely fine and really happy to see you.", wordsPerLine=7)
            speakText("I'm absolutely fine ,and really happy to see you.")

        elif [i for i in userAffectionQuestions if i in command]:
            blitPara("Yeah boss I really like you.", wordsPerLine= 7)
            speakText("Yeahh BOSS! I reeally like you.")

        elif [i for i in exitStatements if i in command]:
            blitPara("Ok boss! see you soon")
            speakText("Ok boss! see you soon")
            runState = False

        elif not command:
            """
            This will be triggered if only `baby` was spoken
            and no instruction was passed
            """
            p.display.update(blit("Sorry, I didn't get it. Please try again"))
            speakText("Sorry, I didn't get it. Please try again")

        else:
            command = cleanText(command, command.split()[0]+" ")

            p.display.update(blit("Please wait..."))
            p.display.update(blit("Checking for " + command+ " on the internet", 70, 130))
            speakText("Please wait")
            speakText("Checking for " + command + " on the internet")
            webbrowser.open("https://www.google.com/search?q="+command)

        return runState
    except:

        return runState

# Main
if __name__ == "__main__":

    # Initiating SpeechRecognition engine
    listener = speech_recognition.Recognizer()
    engine = pyttsx3.init()
    voices = engine.getProperty('voices')
    engine.setProperty('voice', voices[1].id) # For changing voice to Female
    engine.setProperty('rate', 170) # for changing rate of speech

    # Initiating pyGame
    p.init()
    clock = p.time.Clock()
    p.display.set_caption("Baby - The Assistant")
    icon = p.image.load("Images\iconSmall.png")
    p.display.set_icon(icon)

    # Setting Up Window
    resolution = (500, 600)
    screen = p.display.set_mode(resolution)
    w = screen.get_width()
    h = screen.get_height()

    # Loading Images
    background = p.image.load('Images\Background.png')
    micDown = p.image.load('Images\micdown.png')
    micHover = p.image.load('Images\hoverbutton.png')
    listening = p.image.load('Images\listen.png')

    # Fonts
    font = p.font.Font("Fonts\Montserrat-Bold.ttf", 20)
    smallFont = p.font.Font("Fonts\Montserrat-Bold.ttf", 15)
    bigFont = p.font.Font("Fonts\Montserrat-Bold.ttf", 56)

    aboutIcon = font.render("?", True, (100, 0, 0))
    aboutIconHover = font.render("?", True, (200, 0, 0))
    credits = smallFont.render("by Om Gupta", True, (90, 90, 90))

    #Click region radius
    radius = 50

    ##Main
    action = True #For running main while loop
    firstLoop = True #to check for first iteration of loop

    while action:
        # Itroductory part for first loop
        if firstLoop:
            intro()
            firstLoop = False

        # Setting up the background
        screen.blit(background, (0, 0))
        screen.blit(credits,(385,570))
        screen.blit(aboutIcon, (485, 5))

        # Getting mouse position
        mouse = p.mouse.get_pos()

        if w // 2 - radius <= mouse[0] <= w // 2 + radius and h - 100 - radius <= mouse[1] <= h - 100 + radius:
            """
            Triggered while hovering on mic button
            """
            p.mouse.set_cursor(p.SYSTEM_CURSOR_HAND)
            screen.blit(micHover, (0, 0))

        elif 465 <= mouse[0] <= 500 and 0 <= mouse[1] <= 30:
            """
            Triggered while hovering on About button
            """
            p.mouse.set_cursor(p.SYSTEM_CURSOR_HAND)
            screen.blit(aboutIconHover, (485, 5))

        elif 385 <= mouse[0] <= 500 and 570 <= mouse[1] <= 590:
            """
            Triggered while hovering on `by Om Gupta`
            """
            p.mouse.set_cursor(p.SYSTEM_CURSOR_HAND)

        else:
            p.mouse.set_cursor(p.SYSTEM_CURSOR_ARROW)

        for event in p.event.get():
            if event.type == p.QUIT:
                engine.stop()
                action = False
            if event.type == p.MOUSEBUTTONDOWN:
                if w // 2 - radius <= mouse[0] <= w // 2 + radius and h - 100 - radius <= mouse[1] <= h - 100 + radius:
                    """
                    Triggered when Mic button is clicked
                    """
                    playSound("Sounds\click.mp3")
                    p.display.update(screen.blit(micDown, (0, 0)))

                    action = actionBaby()

                elif 465 <= mouse[0] <= 500 and 0 <= mouse[1] <= 30:
                    """
                    Triggered when About button is clicked
                    """
                    about()
                elif 385 <= mouse[0] <= 500 and 570 <= mouse[1] <= 590:
                    webbrowser.open("https://www.instagram.com/aaumgupta/")

        p.display.flip()

    # Closing pyGame
    p.quit()
    # Closing the Window
    sys.exit()


#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@file               :ledock_utils.py
@Description:       : ledock准备工作,分割任务
@Date               :2023/2/22 18:47:25
@Author             :lyzeng
@mail               :pylyzeng@gmail.com
@version            :1.0
'''
from pathlib import Path
from typing import List
import subprocess

def generate_ledock_file(receptor:Path, l_list_outfile:Path, out_file:Path, l_list: Path,
                         x=[0, 0], y=[0, 0], z=[0, 0], n_poses=20,rmsd=1.0):
    rmsd = str(rmsd)
    x = [str(x) for x in x]
    y = [str(y) for y in y]
    z = [str(z) for z in z]
    n_poses = str(n_poses)
    l_list_outfile.write_text(l_list.as_posix()) # only for one molecular docking, otherwise change this part

    file = [
        'Receptor\n',
        receptor.as_posix() + '\n\n',
        'RMSD\n',
        rmsd + '\n\n',
        'Binding pocket\n',
        x[0], ' ', x[1], '\n',
        y[0], ' ', y[1], '\n',
        z[0], ' ', z[1], '\n\n',
        'Number of binding poses\n',
        n_poses + '\n\n',
        'Ligands list\n',
        l_list_outfile.as_posix() + '\n\n',
        'END']
    print(f'save ledock config: {out_file.as_posix()}')
    out_file.write_text(''.join(file))

def box_vina_to_ledock(center_x, center_y, center_z, size_x, size_y, size_z):
    # 计算 LeDockBox 中的坐标值
    minX = round(center_x - size_x / 2, 2)
    maxX = round(center_x + size_x / 2, 2)
    minY = round(center_y - size_y / 2, 2)
    maxY = round(center_y + size_y / 2, 2)
    minZ = round(center_z - size_z / 2, 2)
    maxZ = round(center_z + size_z / 2, 2)

    # 构造 LeDockBox 字符串
    LeDockBox = "*********LeDock Binding Pocket*********\n" + \
                "Binding pocket\n%.1f %.1f\n%.1f %.1f\n%.1f %.1f\n" % (minX, maxX, minY, maxY, minZ, maxZ)
    print(LeDockBox)

    return minX, maxX, minY, maxY, minZ, maxZ

def config_vina2ledock(vina_file: Path, out_path: Path):
    # test one instance
    if not vina_file.exists(): raise FileNotFoundError("File not found: " + vina_file.as_posix())
    # extract box infos
    content_list = [i for i in vina_file.read_text().splitlines() if i]  # read vina config
    center_x, center_y, center_z, size_x, size_y, size_z = [float(content.split(" = ")[1]) for content in
                                                            content_list[2:8]]
    center_x = round(center_x, 2)
    center_y = round(center_y, 2)
    center_z = round(center_z, 2)
    size_x = round(size_x, 2)
    size_y = round(size_y, 2)
    size_z = round(size_z, 2)
    minX, maxX, minY, maxY, minZ, maxZ = box_vina_to_ledock(center_x, center_y, center_z, size_x, size_y, size_z)
    # extract ligand infos
    # 去掉_to_pdbqt 将_ploar.pdbqt变为_polar.pdb
    lig_content = content_list[1].split('=')[1].strip().replace('molecular_polar_mol2_to_pdbqt',
                                                                'molecular_polar_mol2', ).replace('_ploar.pdbqt',
                                                                                '_polar.mol2')
    lig_content = out_path.parent.joinpath(lig_content)
    if not lig_content.exists(): raise FileNotFoundError("File not found: " + lig_content.as_posix())
    # extract protein infos
    pro_content = out_path.parent.joinpath(content_list[0].split('=')[1].strip().replace('_pdbqt', '').replace('pdbqt', 'pdb'))
    if not pro_content.exists(): raise FileNotFoundError("File not found: " + pro_content.as_posix())
    liglst = out_path.joinpath(vina_file.stem + '.list')
    ledock_config_file = out_path.joinpath(vina_file.stem + '.in')
    generate_ledock_file(receptor=pro_content, x=[minX, maxX], y=[minY, maxY], z=[minZ, maxZ], n_poses=20,
                         l_list=lig_content, l_list_outfile=liglst,
                         out_file=ledock_config_file)

def ledock_split(ledock_results: Path, option='-spli'):
    ledock_binary = '/home/lyzeng/ledock_benchmark/ledock_linux_x86'
    res = subprocess.run([ledock_binary, option, ledock_results.as_posix()])
    if res.returncode != 1:
        return res

def split_main():
    ledock_results = list(Path('/home/lyzeng/ledock_benchmark/molecular_polar_mol2').glob('*.dok'))
    file = ledock_results[0]
    split_res = list(map(lambda x: x!=None ,[ledock_split(i) for i in ledock_results]))

if __name__ == '__main__':
    ...


from typing import Dict, List
from particle import Particle
from random import uniform, random

class Swarm:
    def __init__(self, params:Dict):
        self.params = params
        self.best_particle:Particle = None
        self.best_adaptation:float = float('inf')
        self.configurate_particles()

    def configurate_particles(self):
        self.swarm:List[Particle] = [
            Particle(
                (
                    [
                        uniform(
                            self.params['cost_function']['min_x'],
                            self.params['cost_function']['max_x']
                        )
                        for _ in range(self.params['dimensions'])
                    ]
                ),
                self.params['algorithm']['inertia_weight'],
                self.params['algorithm']['cognitive_coef'],
                self.params['algorithm']['social_coef'],
                list(self.params['cost_function']['equation'].values())[0]
            )
            for _ in range(self.params['population_size'])
        ]

    def update_best_particle(self):
        for p in self.swarm:
            p.calc_adaptation()
            best_swarm_adaptation = (
                float('inf')
                if self.best_particle == None
                else self.best_particle.best_adaptation
            )
            if p.best_adaptation < best_swarm_adaptation:
                self.best_particle = p
                self.best_adaptation = p.best_adaptation

    def update_swarm_pos(self):
        cognitive_rand, social_rand = random(), random()
        for p in self.swarm:
            p.update_position(
                self.best_particle.pos,
                cognitive_rand,
                social_rand,
                (
                    self.params['cost_function']['min_x'],
                    self.params['cost_function']['max_x']
                )
            )

    def get_positions(self):
        return [
            p.pos for p in self.swarm
        ]


from models.models import Department, Employee
import random
from datetime import datetime
from setup import db
from datetime import date
import pickle
# from numpy import np
# import random
from flask import Flask, request, render_template
from collections import Counter

# import random
from flask import Flask, request
from collections import Counter

app = Flask(__name__)
departments = []
count = 0

def correct_request(req_args, model_args):
    return Counter(req_args) == Counter(model_args)

@app.route('/', methods=['POST', 'GET'])
def index():
    global count
    flask_request = request
    if flask_request.method == 'GET':
        dept_args = Departments.dept_args
        # return {'Departments': dept_args}
        return {'departments': departments, 'Departments': dept_args}
    if flask_request.method == 'POST':
        req_args = flask_request.args.to_dict()
        model_args = Departments.dept_args
        print(f'req_args = {req_args}')
        print(f'model_args = {model_args}')
        print(correct_request(req_args.keys(), model_args))
        if correct_request(req_args.keys(), model_args):
            count += 1
            dep_name = req_args['name']
            dep_num = req_args['num']
            # department = Departments(dep_name, dep_num)
            department = {'id': count, 'name': dep_name, 'num': dep_num}
            departments.append(department)
            print(departments)
            return flask_request.args
        else:
            return 'Wrong request'

# app = Flask(__name__)
# departments = []
# count = 0
#
#
# def correct_request(req_args, model_args):
#     return Counter(req_args) == Counter(model_args)
#
#
# @app.route('/', methods=['POST', 'GET'])
# def index():
#     global count
#     flask_request = request
#     if flask_request.method == 'GET':
#         # dept_args = Departments.dept_args
#         # return {'Departments': dept_args}
#         # return {'departments': departments, 'Departments': dept_args}
#         return render_template('index.html', departments=departments)#, n=name1, m=name2, list=l)
#     if flask_request.method == 'POST':
#         req_args = flask_request.args.to_dict()
#         model_args = Departments.dept_args
#         print(f'flask_request: {flask_request.args}')
#         print(f'req_args = {req_args}')
#         print(f'model_args = {model_args}')
#         print(correct_request(req_args.keys(), model_args))
#         if correct_request(req_args.keys(), model_args):
#             count += 1
#             dep_name = req_args['name']
#             dep_num = req_args['num']
#             # department = Departments(dep_name, dep_num)
#             department = {'id': count, 'name': dep_name, 'num': dep_num}
#             departments.append(department)
#             print(departments)
#             return flask_request.args
#         else:
#             return 'Wrong request'
def add_dept_to_empl():
    depts = [1, 2, 4, 5, 43]
    # print(datetime.now().date())
    employees = Employee.query.all()
    for empl in employees:
        i = random.randint(0, 4)
        empl.id_empl_dept = depts[i]

def add_birth_to_empl():
    employees = Employee.query.all()
    for empl in employees:
        year = random.randint(1970, 2001)
        month = random.randint(1, 12)
        day = random.randint(1, 30)

        print(date(year, month, day))
        empl.birthday = date(year, month, day)

def calculate_age(born):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

def get_average_salary(id_dept):
    department = Department.query.filter_by(id_dept=id_dept).first()
    employees = department.employees
    salary = 0
    for employee in employees:
        salary += employee.salary
    return (salary / len(employees)).__round__(2)

def foo(*args):
    return (args)

def populate():
    departments = ['research, counter, administration, advertisement', 'education']
    path = '/home/artem/programming/python/epam2021/final/final05_python_2021/department-app/static/blnrs.pckl'
    employees = []
    with open(path, 'rb') as file:
        blnrs = pickle.load(file)
        for blnr in blnrs:
            employees.append(blnr.get('commonName'))
    for empl in employees:
        year = random.randint(1970, 2001)
        month = random.randint(1, 12)
        day = random.randint(1, 30)

        birthday = date(year, month, day)
        e = Employee(name=empl, salary=random.randint(1, 10) * 1000, birthday=birthday, id_empl_dept=random.randint(1, 3))
        db.session.add(e)
        db.session.commit()
    return employees

if __name__ == '__main__':
    date_ = 3
    populate()
    print(populate())
    # int(None)
    # t = '1', '2', '3'
    # print(foo())
    # a, b, c = t
    # m = map(lambda x: int(x), t)
    # z = zip(t, m)
    # print(dict(z))
    # x = int(None)
    # try:
    #     date_ = date(1979-04-25)
    # except TypeError as te:
    #     date_ = date(1, 1, 1)
    # print(date_)
    # print(get_average_salary(1))
    # employees = Employee.query.all()
    # def foo(a):
    #     print(a)
    # l = [1, 2, 3]
    # m = map(print, l)
    # tuple(m)
    # print('\n ************************************************************************************************\n')
    # print(f'm = {list(m)}')
    # print(f'l = {l}')
    # ees = list(map(lambda employee: employee.birthday.year >= 1983, [employee for employee in employees ]))#if employee.birthday.year >= 1983]))
    # ees = [employee for employee in employees if datetime(1983, 8, 5) <= employee.birthday <= datetime(1983, 8, 5)]
    # print(ees)
    # for employee in employees:
    #     if employee.birthday.year == 1983:
    #         print(employee)
    # for el in dir(Employee.birthday):
    #     print(el)
    # add_birth_to_empl()
    # add_dept_to_empl()
    # print(e2.birthday.year)
    # e1.id_empl = 10000
    # e2.birthday = datetime.now().date()
    # e2.id_empl_dept = 1
    d1 = Department.query.filter_by(id_dept=1).first()
    print(d1)
    # d1.title = 'study'
    # db.session.add(e2)
    # db.session.add(d1)
    # db.session.commit()
    # print(d1.employees)
    # for empl in d1.employees:
    #     print(f'{empl.name}, {empl.salary}, {empl.birthday.year}')
    # print(d1.employees)


from mesa.visualization.ModularVisualization import VisualizationElement
import numpy as np

from ants.agents.ant_agent import AntAgent

class HistogramModule(VisualizationElement):
    local_includes = ["ants/view/histogram_module.js"]

    def __init__(self, bins, canvas_height, canvas_width):
        self.canvas_height = canvas_height
        self.canvas_width = canvas_width
        self.bins = bins
        new_element = "new HistogramModule({}, {}, {})"
        new_element = new_element.format(bins,
                                         canvas_width,
                                         canvas_height)
        self.js_code = "elements.push(" + new_element + ");"

    def render(self, model):
        all_agents = model.schedule.agents
        # get all agents that are Ants
        ants = [a for a in all_agents if isinstance(a, AntAgent)]
        life_vals = [agent.life_left() * 100 for agent in ants]
        hist = np.histogram(life_vals, bins=self.bins)[0]
        return [int(x) for x in hist]


import logging
from champ import error, readmap
import os

log = logging.getLogger(__name__)

def main(clargs):
    # validate and/or create directories
    if not os.path.isdir(clargs.fastq_directory):
        error.fail("The given fastq directory does not exist.")
    if not os.path.isdir(clargs.output_directory):
        os.makedirs(clargs.output_directory)

    readmap.main(clargs)


#This is a loom simulator to help me design different patterns for my traditional 4-pulley European upright loom. The pedals are labeled A 1 2 3 4 B

class Loom:

    def __init__(self, thread_count, under=' -', over='- '):
        self._thread_count = thread_count
        self.weaving = self.weave()
        self._over = over
        self._under = under

    @property
    def thread_count(self):
        return self._thread_count

    @thread_count.setter
    def thread_count(self, new_num):
        if type(new_num) is not int:
            raise ValueError("You must enter a number")
        self._thread_count = new_num

    # @property
    # def over(self):
    #     return self._over
    #
    # @over.setter
    # def over(self, new_over):
    #     self._over = new_over
    #
    # @property
    # def under(self):
    #     return self._under
    #
    # @under.setter
    # def under(self, under):
    #     self._under = under

    def A(self):
        a = '- '
        # a = self.over + self.under
        return a*self.thread_count + '\n'

    def B(self):
        # b = self.under + self.over
        b = ' -'
        return b*self.thread_count + '\n'

    def one(self):
        one = '-   '
        return one*(int(self.thread_count/2)) + '\n'

    def two(self):
        two = ' -  '
        return two*(int(self.thread_count/2)) + '\n'

    def three(self):
        three = '  - '
        return three*(int(self.thread_count/2)) + '\n'

    def four(self):
        four = '   -'
        return four*(int(self.thread_count/2)) + '\n'

    def reverse(self):
        return_str = ""
        for i in self.weaving:
            if i == '-':
                return_str += ' '
            if i == ' ':
                return_str += '-'
            if i == '\n':
                return_str += '\n'
        return return_str

    def weave(self):
        usr = ''
        return_str = ""
        print("Type A B 1 2 3 4 to press pedals of your virtual loom; press any other key to stop and see what you've made")
        while usr == "" or usr == "A" or usr == "B" or usr == '1' or usr == '2' or usr == '3' or \
            usr == '4':
            usr = input("what pedal would you like to push? \n")
            if usr == 'A':
                return_str += self.A()
            if usr == 'B':
                return_str += self.B()
            if usr == '1':
                return_str += self.one()
            if usr == '2':
                return_str += self.two()
            if usr == '3':
                return_str += self.three()
            if usr == '4':
                return_str += self.four()
        return return_str

    def __str__(self):
        return self.weaving

if __name__ == "__main__":

    # l = Loom(10)
    # print(l)
    # print(l.reverse())
    l0 = Loom(100)
    print(l0)
    print(l0.reverse())


"""
An on-disk ljson implementation.
"""

import json, os
from .generic import Header, LjsonTable, LjsonSelector,  row_matches, LjsonQueryResult
from collections import deque
from threading import RLock

class Table(LjsonTable):
	"""
	An on-disk ljson table.

	One should **not** use the constructor to open
	a file but instead use the static method from_file.

	WARNING: ``file_`` **must** be opened in ``w+`` mode!
	"""
	can_detach_after_fromfile = False

	def __init__(self, header, file_, is_headless = False):
		self._headless = is_headless
		self.header = header
		self.file = file_
		self._file_pointer_stack = deque()
		self._loop_file_pointer_stack = deque()
		self._lock = RLock()

	@staticmethod
	def open(filename):
		"""
		Equivalent to ``Table.from_file(open(filename, "r+"))``
		"""
		if(not os.path.exists(filename)):
			raise IOError("cannot open {} for reading: does not exist".format(filename))
		fin = open(filename, "r+")
		header, _headless = Header.from_file(fin)
		return Table(header, fin, _headless)

	@classmethod
	def _from_file(cls, fin):
		"""
		WARNING: ``file_`` **must** be opened in ``r+`` mode!
		"""
		header, _headless = Header.from_file(fin)
		return cls(header, fin, _headless)

	def __getitem__(self, dct):
		for k in dct:
			if(not k in self.header.descriptor):
				raise KeyError("unknow key: {}".format(k))

		return Selector(self.header, dct, self)
	def __next__(self):
		with self._lock:
			seek_after = self.file.tell()
			self.file.seek(self._loop_file_pointer_stack.popleft())

			row = self.file.readline()
			if(not row):
				# we are leaving the loop => this context is done
				# => return to the context before __iter__ was called
				self.file.seek(self._file_pointer_stack.popleft())
				raise StopIteration()
			while(row.isspace()):
				row = self.file.readline()
			if(not row or row.isspace()):
				# we are leaving the loop => this context is done
				# => return to the context before __iter__ was called
				self.file.seek(self._file_pointer_stack.popleft())
				raise StopIteration()
			self._loop_file_pointer_stack.appendleft(self.file.tell())
			self.file.seek(seek_after)
			return self.unstringify(row)

	def __enter__(self):
		return self
	def __exit__(self, exc_type, exc_value, traceback):
		with self._lock:
			self.file.close()
		del(self.header)
		del(self)
		return False

	def _save(self, fout):
		"""
		Save this table to the file ``fout``.
		"""
		with self._lock:
			seek = self.file.tell()
			self.file.seek(0)
			for r in self.file:
				if(r.isspace()):
					continue
				fout.write(r)
			self.file.seek(seek)
	def additem(self, row):
		"""
		Add a new row.
		"""
		with self._lock:
			seek = self.file.tell()
			for k, v in row.items():
				self.header.check_data(k, v)
				if("unique" in self.header.descriptor[k]["modifiers"]):
					# check if the value is unique
					for r in self:
						if(v == r[k]):
							raise ValueError("Value {} is not unique: {}".format(k, v))
			self.file.seek(0, 2) # EOF here
			self.file.write("\n")
			self.file.write(self.stringify(row))
			self.file.flush()
			self.file.seek(seek)
	def __contains__(self, dct):
		with self._lock:
			seek = self.file.tell()
			self.file.seek(0)
			if(not self._headless):
				self.file.readline()
			for row in self.file:
				if(row.isspace()):
					continue
				if(row_matches(self.unstringify(row), dct)):
					self.file.seek(seek)
					return True
			self.file.seek(seek)
			return False
	def __iter__(self):
		with self._lock:
			self._file_pointer_stack.appendleft(self.file.tell())
			self.file.seek(0)
			if(not self._headless):
				self.file.readline()
			self._loop_file_pointer_stack.appendleft(self.file.tell())
			return self

	def __delitem__(self, dct):
		with self._lock:
			if(self._file_pointer_stack):
				raise RuntimeError("Attempt to delete item from table during looping. This leads to undefined behaviour.")
			seek_after = self.file.tell()
			max_seek = 0
			self.file.seek(0)
			os.unlink(self.file.name)
			buf = open(self.file.name, "w+")
			if(not self._headless):
				buf.write(self.file.readline())
			deleted_row = False
			for line in self.file:
				if(line.isspace()):
					continue
				r = self.unstringify(line)
				if(row_matches(r, dct)):
					deleted_row = True
				else:
					buf.write(line)
					max_seek = buf.tell()
			self.file.close()
			self.file = buf
			self.file.flush()
			if(seek_after <= max_seek):
				self.file.seek(seek_after)
			else:
				self.file.seek(0)
				raise RuntimeWarning("File is truncated. unable to restore table state.")
			if(not deleted_row):
				raise KeyError("no matching rows found: {}".format(dct))
	def close(self):
		"""
		Close the underlaying file.
		"""
		self.file.close()
		del(self)

class Selector(LjsonSelector):
	def __init__(self, header, dct, table):
		self.header = header
		self.file = table.file
		self.dct = dct
		self.table = table
		self._file_pointer_stack = deque()
		self._loop_file_pointer_stack = deque()

	def stringify(self, row):
		return json.dumps(self.header.prestringify(row))
	def unstringify(self, row):
		return self.header.preunstringify(json.loads(row))
	def getone(self, column = None):
		with self.table._lock:
			seek_after = self.file.tell()
			self.file.seek(0)
			if(not self.table._headless):
				self.file.readline()
			for line in self.file:
				if(line.isspace()):
					continue
				row = self.unstringify(line)
				if(row_matches(row, self.dct)):
					if(column):
						self.file.seek(seek_after)
						return row[column]
					else:
						self.file.seek(seek_after)
						return row
			self.file.seek(seek_after)
			return None
	def __getitem__(self, column):
		with self.table._lock:
			seek_after = self.file.tell()
			self.file.seek(0)
			if(not self.table._headless):
				self.file.readline()
			res = deque()
			for line in self.file:
				row = self.unstringify(line)
				if(row_matches(row, self.dct)):
					res.append(row[column])
			self.file.seek(seek_after)
			return QueryResult(self.table, self, column, list(res))

	def __setitem__(self, column, value):
		with self.table._lock:
			if(self._file_pointer_stack or self.table._file_pointer_stack):
				raise RuntimeError("Attempt to edit table while iterating")
			seek_after = self.file.tell()
			self.file.seek(0)
			os.unlink(self.file.name)
			buf = open(self.file.name, "w+")
			if(not self.table._headless):
				buf.write(self.file.readline())
			for line in self.file:
				if(line.isspace()):
					continue
				r = self.unstringify(line)
				if(row_matches(r, self.dct)):
					r[column] = value
					buf.write(self.stringify(r))
					buf.write("\n")
				else:
					buf.write(line)
			self.file.close()
			self.file = buf
			self.table.file = buf
			self.table.file.seek(seek_after)
			self.file.flush()

	def __next__(self):
		with self.table._lock:
			seek_after = self.file.tell()
			self.file.seek(self._loop_file_pointer_stack.popleft())

			row = self.file.readline()
			if(not row):
				# we are leaving the loop => this context is done
				# => return to the context before __iter__ was called
				self.file.seek(self._file_pointer_stack.popleft())
				raise StopIteration()
			data = {}
			if(not row.isspace()):
				data = self.unstringify(row)
			while(row.isspace() or not row_matches(data, self.dct)):
				row = self.file.readline()
				if(not row):
					# we are leaving the loop => this context is done
					# => return to the context before __iter__ was called
					self.file.seek(self._file_pointer_stack.popleft())
					raise StopIteration()
				data = self.unstringify(row) if not row.isspace() else {}
			self._loop_file_pointer_stack.appendleft(self.file.tell())
			self.table.file.seek(seek_after)
			return data
	def __iter__(self):
		with self.table._lock:
			self._file_pointer_stack.appendleft(self.file.tell())
			self.file.seek(0)
			if(not self.table._headless):
				self.file.readline()
			self._loop_file_pointer_stack.appendleft(self.file.tell())
			return self

class QueryResult(LjsonQueryResult):
	"""
	See ``ljson.base.generic.LjsonQueryResult``.
	"""
	def _perform_change(self, func, *args):
		"""
		This is used to keep the overhead of modifications at one place.
		"""
		with self.table._lock:
			if(self.selector._file_pointer_stack or self.table._file_pointer_stack):
				raise RuntimeError("Attempt to edit table while iterating")
			seek_after = self.table.file.tell()
			self.table.file.seek(0)
			os.unlink(self.table.file.name)
			buf = open(self.table.file.name, "w+")
			if(not self.table._headless):
				buf.write(self.table.file.readline())
			for line in self.table.file:
				if(line.isspace()):
					continue
				r = self.unstringify(line)
				if(row_matches(r, self.selector.dct)):
					r[self._selected] = func(r[self._selected], *args)
					buf.write(self.stringify(r))
					buf.write("\n")
				else:
					buf.write(line)
			self.table.file.close()
			self.table.file = buf
			self.table.file.flush()
			self.selector.file = buf
			self.table.file.seek(seek_after)

	def __iadd__(self, item):
		self._perform_change(lambda a,b: a + b, item)
		return self
	def __imul__(self, item):
		self._perform_change(lambda a,b: a * b, item)
		return self
	def __isub__(self, item):
		self._perform_change(lambda a,b: a - b, item)
		return self
	def __itruediv__(self, item):
		self._perform_change(lambda a,b: a / b, item)
		return self
	def __ifloordiv__(self, item):
		self._perform_change(lambda a,b: a // b, item)
		return self
	def __imod__(self, item):
		self._perform_change(lambda a,b: a % b, item)
		return self
	def __ipow__(self, item, modulo = None):
		if(modulo != None):
			self._perform_change(lambda a,b, modulo: a.__pow__(b, modulo) , item, modulo)
		else:
			self._perform_change(lambda a,b: a ** b, item)
		return self
	def __iand__(self, item):
		self._perform_change(lambda a,b: a & b, item)
		return self
	def __ixor__(self, item):
		self._perform_change(lambda a,b: a ^ b, item)
		return self
	def __ior__(self, item):
		self._perform_change(lambda a,b: a | b, item)
		return self
	def __ilshift__(self, item):
		self._perform_change(lambda a,b: a << b, item)
		return self
	def __irshift__(self, item):
		self._perform_change(lambda a,b: a >> b, item)
		return self

	def __getattr__(self, name):
		if name in ("_list", "table", "selector", "_selected", "_perform_change"):
			return object.__getattr__(self, name)
		return getattr(self._list, name)
	def __setattr__(self, name, value):
		if name in ("_list", "table", "selector", "_selected", "_perform_change"):
			return object.__setattr__(self, name, value)

		return setattr(self._list, name, value)


from ast import Lambda
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import rcParams
rcParams.update({'figure.autolayout': True})

font = {'size'   : 15}
matplotlib.rc('font', **font)

p = np.arange(1,15)
print(p)
f1 = lambda x: -np.log(100)/np.log(1-0.1**x)
f2 = lambda x: -np.log(100)/np.log(1-0.2**x)
f3 = lambda x: -np.log(100)/np.log(1-0.3**x)
f4 = lambda x: -np.log(100)/np.log(1-0.4**x)

n1 = np.array([f1(xi) for xi in p])
n2 = np.array([f2(xi) for xi in p])
n3 = np.array([f3(xi) for xi in p])
n4 = np.array([f4(xi) for xi in p])

fig, ax = plt.subplots()
ax.plot(p,n1,color='black')
ax.text(p[-1]+0.5,n1[-1],'r=0.1')
ax.plot(p,n2,color='black')
ax.text(p[-1],n2[-1],' r=0.2')
ax.plot(p,n3,color='black')
ax.text(p[-1],n3[-1],' r=0.3')
ax.plot(p,n4,color='black')
ax.text(p[-1],n4[-1],' r=0.4')
ax.set_yscale('log')
ax.set_xbound([0,17])
ax.set_xlabel('p, dimensions')
ax.set_ylabel('minimum n')
plt.savefig('knearest/curse',dpi=500)


#Deobfuscator by HuyAnh
#Zalo:0905491417
#fb.com/huyanhnong.21
luc = "\033[1;32m"

trang = "\033[1;37m"

do = "\033[1;31m"

vang = "\033[0;93m"

hong = "\033[1;35m"

xduong = "\033[1;34m"

xnhac = "\033[1;36m"

# Đánh Dấu Bản Quyền

ndp_tool = do + "[" + trang + "=.=" + do + "] " + trang + "=> "

ndp = do + "[" + trang + "=.=" + do + "] " + trang + "=> "

# Config

# List Dữ Liệu

list_id_name_page = []

# Import Lib

import requests, threading

import os, sys

from time import sleep

from datetime import datetime

import json

try:

	import requests,pystyle

except:

	print (luc + "Bạn Chưa Tải Thư Viện \n Bắt Đầu Tải ")

	os.system('pip install requests && pip install bs4 && pip install pystyle')

# ==========================[ FUNCTION ]===========================================

def echo(a):

   for i in range(len(a)):

     sys.stdout.write(a[i])

     sys.stdout.flush()

     sleep(0.001)

   print()

def banner():

    banner = f"""\033[1;34m

\033[1;32m

\033[1;32m            ███████╗██╗   ██╗████████╗██╗  ██╗

\033[1;32m            ╚══███╔╝╚██╗ ██╔╝╚══██╔══╝██║  ██║

\033[1;32m              ███╔╝  ╚████╔╝    ██║   ███████║

\033[1;32m             ███╔╝    ╚██╔╝     ██║   ██╔══██║

\033[1;32m            ███████╗   ██║      ██║   ██║  ██║

\033[1;32m            ╚══════╝   ╚═╝      ╚═╝   ╚═╝  ╚═╝ Tool Kích Hoạt Page Facebook Bị Ẩn/Huỷ Đăng

\033[1;39m              ⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦

\033[1;31m Nguyễn Ngọc Thành                  DevOps: Lê Trọng Truyền

\033[1;39m              ⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦⏦

"""

    echo(banner)

def clear():

    os.system("cls" if os.name == "nt" else "clear")

def thanh():

    print('\033[1;37m- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -')

def ndp_delay(o):

    while o > 1:

        o = o - 1

        print(f'{trang}[\033[1;31mZ\033[1;33my\033[1;36mt\033[1;35mh\033[1;34m]\033[1;37m[\033[1;36m|\033[1;37m]\033[1;37m[.....]\033[1;37m[{o}]', '     ', end='\r')

        sleep(1/6)

        print(f'{trang}[\033[1;35mZ\033[1;32my\033[1;34mt\033[1;35mh\033[1;36m]\033[1;37m[\033[1;31m/\033[1;37m]\033[1;37m[\033[1;32m>\033[1;37m....]\033[1;37m[{o}]', '     ', end='\r')

        sleep(1/6)

        print(f'{trang}[\033[1;31mZ\033[1;33my\033[1;36mt\033[1;35mh\033[1;34m]\033[1;37m[\033[1;32m-\033[1;37m]\033[1;37m[\033[1;32m>\033[1;31m>\033[1;37m...]\033[1;37m[{o}]', '     ', end='\r')

        sleep(1/6)

        print(f'{trang}[\033[1;35mZ\033[1;32my\033[1;34mt\033[1;35mh\033[1;36m]\033[1;37m[\033[1;33m+\033[1;37m]\033[1;37m[\033[1;32m>\033[1;31m>\033[1;36m>\033[1;37m..]\033[1;37m[{o}]', '     ', end='\r')

        sleep(1/6)

        print(f'{trang}[\033[1;31mZ\033[1;33my\033[1;36mt\033[1;35mh\033[1;34m]\033[1;37m[\033[1;34m\\{trang}]\033[1;37m[\033[1;32m>\033[1;31m>\033[1;36m>\033[1;33m>\033[1;37m.]\033[1;37m[{o}]', '     ', end='\r')

        sleep(1/6)

        print(f'{trang}[\033[1;35mZ\033[1;32my\033[1;34mt\033[1;35mh\033[1;36m]\033[1;37m[\033[1;35m|\033[1;37m]\033[1;37m[\033[1;32m>\033[1;31m>\033[1;36m>\033[1;33m>\033[1;35m>\033[1;37m]\033[1;37m[{o}]', '     ', end='\r')

        sleep(1/6)

def rungr(x):

    time = datetime.now().strftime("%H:%M:%S")

    uid_page = list_id_name_page[x].split('|')[0]

    name_page = list_id_name_page[x].split('|')[1]

    list1 = (f'i_user={uid_page};')

    cookie9 = (f'{cookie}{list1}')

    headers = {

        'Authority': 'www.facebook.com',

        'Method': 'POST',

        'Path': '/api/graphql/',

        'Scheme': 'https',

        'Accept': '*/*',

        'Accept-Language': 'vi,en;q=0.9,en-GB;q=0.8,en-US;q=0.7',

        'Content-Length': '1704',

        'Content-Type': 'application/x-www-form-urlencoded',

        'Cookie': cookie9,

        'Origin': 'https://www.facebook.com',

        'Referer': 'https://www.facebook.com/pages/?category=your_pages&ref=bookmarks',

        'Sec-Ch-Prefers-Color-Scheme': 'dark',

        'Sec-Ch-Ua': '"Not.A/Brand";v="8", "Chromium";v="114", "Microsoft Edge";v="114"',

        'Sec-Ch-Ua-Full-Version-List': '"Not.A/Brand";v="8.0.0.0", "Chromium";v="114.0.5735.201", "Microsoft Edge";v="114.0.1823.67"',

        'Sec-Ch-Ua-Mobile': '?0',

        'Sec-Ch-Ua-Platform': '"Windows"',

        'Sec-Ch-Ua-Platform-Version': '"15.0.0"',

        'Sec-Fetch-Dest': 'empty',

        'Sec-Fetch-Mode': 'cors',

        'Sec-Fetch-Site': 'same-origin',

        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67',

        'X-Asbd-Id': '129477',

        'X-Fb-Friendly-Name': 'usePagesCometEditPageVisibilityMutation',

        'X-Fb-Lsd': 'MsxoFWxSNp7G_6piXo7vFV',

    }

    data = {

        'av': idpro5,

        '__user': idpro5,

        '__a': '1',

        '__req': '12',

        '__hs': '19540.HYP:comet_pkg.2.1..2.1',

        'dpr': '1.5',

        '__ccg': 'EXCELLENT',

        '__rev': '1007781546',

        '__s': 'hrh3k2:l8nej4:wsrxa9',

        '__hsi': '7251274423764571025',

        '__dyn': '7AzHJ16UW5Eb8ng5K8G6EjBWobVo66u2i5U4e2C17xt3odEnz8K361twYwJyE24wJwpUe8hwaG0Z82_CxS320om78bbwto88422y11xmfz81s8hwGxu782lwv89kbxS2218wc61axe3S7Udo5qfK0zEkxe2GewyDwkUtxGm2SUbElxm3y3aexfxmu3W3y261eBx_y88E3qxWm2CVEbUGdG1FyEeo88cA0z8c86-3u364UrwFg662S269wqQ1Fw',

        '__csr': 'gZ2tjhkl6Jjl8zih15dkGOsnsl9vOTZAW9OjPYRil9QhOli9llTATrHBuyAqijH8hoxmAGKQi9t-GGiyaFDEH8HjjhFpoLWgjiKuAiijAiDXCABz9Kl1OEyZ-VHy5DAByXLzoGiaBABGcxaKayGhaiUCqbzoCu7A8xm5AUyUqyUW3C8ho9EW5axSVV8jyEe-mi2Kq-dKaxiaxqbx2fglzokGczUsx64-2a3e4o8pE4icx-3fDwVwxyocE98cU8ohwlEjwxzU4K4EtwTwj9Unwo8-K3-2e4Euw08qq0dqg07Ka03iC0rq78K0-80oZwCxq4o22wipA0pO1Mw0JBc0118w3Xtw6IwtU6G1BCw0KzwCw1GS0tSqawBwHDLQ0mZ384XDOWUC0D81AE2mCwa20L832w3R4',

        '__comet_req': '15',

        'fb_dtsg': fb_dtsg,

        'jazoest': jazoest,

        'lsd': '2bA5j70hHausxyda70P9Hc',

        '__spin_r': '1007781546',

        '__spin_b': 'trunk',

        '__spin_t': '1688318891',

        'fb_api_caller_class': 'RelayModern',

        'fb_api_req_friendly_name': 'usePagesCometEditPageVisibilityMutation',

        'variables': json.dumps({

            'input': {

                'client_mutation_id': '4',

                'actor_id': idpro5,

                'page_id': uid_page,

                'publish_mode': 'PUBLISHED'

            }

        }),

    'server_timestamps': 'true',

    'doc_id': '4920939114687785'

    }

    #print(data)

    #print(headers)

    response = requests.post('https://www.facebook.com/api/graphql/', headers=headers, data=data).text

    #print(response)

    print('\033[1;31m[\033[0;93m'+str(x+1)+'\033[1;31m] | \033[1;36m'+str(time)+' \033[1;31m| \033[0;93mSUCCESS \033[1;31m| \033[1;35m'+str(uid_page)+' \033[1;31m| \033[1;34m'+str(name_page)+' \033[1;31m| \033[1;37m'+str(idpro5)+' ')

# =================[ START TOOL ]===========================

clear()

banner()

cookie = input(ndp_tool+luc+'Vui Lòng Nhập Cookie Facebook'+trang+': '+vang)

# Get fb_dtsg + jazoest

headers = {

        'authority': 'mbasic.facebook.com',

        'cache-control': 'max-age=0',

        'sec-ch-ua': '"Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"',

        'sec-ch-ua-mobile': '?0',

        'sec-ch-ua-platform': '"Windows"',

        'upgrade-insecure-requests': '1',

        'origin': 'https://mbasic.facebook.com',

        'content-type': 'application/x-www-form-urlencoded',

        'user-agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36',

        'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',

        'sec-fetch-site': 'same-origin',

        'sec-fetch-mode': 'navigate',

        'sec-fetch-user': '?1',

        'sec-fetch-dest': 'document',

        'referer': 'https://mbasic.facebook.com/',

        'accept-language': 'en-US,en;q=0.9',

        'cookie': cookie,

}

try:

    print(ndp_tool+xnhac+"Đang Check Live Cookie...!", end="\r")

    get_token = requests.get('https://firet.io/firetx_retro/api/getthongtinck.php?cookie='+cookie).json()

    print(get_token)

    find_data = requests.get("https://mbasic.facebook.com/", headers=headers).text

    fb_dtsg = find_data.split('<input type="hidden" name="fb_dtsg" value="')[1].split('"')[0]

    jazoest = find_data.split('<input type="hidden" name="jazoest" value="')[1].split('"')[0]

    tokenpro5 = get_token['token']

    namepro5 = get_token["name"]

    idpro5 = get_token['id']

except:

    exit(ndp_tool+do+"Cookie Die Vui Lòng Kiểm Tra Lại!!")

url = "https://firet.io/firetx_retro/api/getpagean.php?cookie=" + cookie

getidpro5 = requests.get(url).json()

print(getidpro5)

list_id_name_page = []

for i in getidpro5:

    uid_page = i['id']

    name_page = i['name']

    so_luong = i['count']

    gomlist = f'{uid_page}|{name_page}'

    list_id_name_page.append(gomlist)

# NHẬP DELAY + SỐ LƯỢNG BUFF

clear()

banner()

print(ndp_tool+luc+'Get Thành Công: '+trang+str(len(list_id_name_page))+luc+' Page Pro5')

thanh()

soluongrungr = len(list_id_name_page)

thanh()

delay = int(input(ndp_tool+luc+'Nhập Delay'+trang+': '+vang))

thanh()

# RUN THAM GIA GROUP

for x in range(soluongrungr):

    threading.Thread(target=rungr,args=(x, )).start()

    ndp_delay(delay)


import numpy as np
from scipy.optimize import differential_evolution
import matplotlib.pyplot as plt

xData = [7, 7.25, 7.5, 7.75, 8, 8.25, 8.5]
yData = [8.24, 8.53, 8.87, 9.18, 9.48, 9.98, 10.32]
unc = [.05, .05, .06, .03, .01, .03, .03]

def LinearFit(x, y, u):
    """
    Fits a linear model by scipy.optimize.differential_evolution

    Parameters
    ----------
    x : (n) array_like
        1-dimensional list of x-values.
    y : (n), array_like
        1-dimensional list of y-values.
    u : (n) array_like
        1-dimensional list of uncertainties for y-values.
    Returns
    -------
    a, b : Optimal parameters for linear model a + bx
    red_chi_sq : float
        reduced chi squared as calculated by the sum of squared residuals
    """
    x = np.asarray(x)
    y = np.asarray(y)
    u = np.asarray(u)
    bounds = [[-1000, 1000]] + [[-1000, 1000]]

    def objective(s):
        a, b = np.split(s, 2)
        return np.sum(((y - b*x-a)**2.)/(u**2.))

    result = differential_evolution(objective, bounds)
    print(result)
    s = result['x']
    red_chi_sq = objective(s)/(len(x)-len(s))
    a, b = np.split(s, 2)
    return a, b, red_chi_sq

a, b, red_chi_sq = LinearFit(xData, yData, unc)
print(a)
print(b)
print(red_chi_sq)

#plot of fit vs data
fig = plt.figure()
plt.errorbar(xData, yData, yerr=unc, fmt='ro')
plt.plot(xData, a+b*xData, 'b', label = '1.41x-1.75')
plt.title('Angular Frequency vs Voltage')
plt.xlabel('Voltage (V)')
plt.ylabel('Angular Frequency (rad/sec)')
plt.legend()
plt.savefig('freq.png', dpi=300, bbox_inches='tight')
plt.close()

height = [3.1, 4.8, 4.1, 3.5, 2.4]
upper = [9.55, 9.97, 9.74, 9.64, 9.33]
lower = [8.36, 8.27, 8.30, 8.32, 8.42]
upunc = [.34, .35, .35, .34, .34]
lowunc = [.32, .32, .32, .32, .32]

aUp, bUp, red_chi_sqUp = LinearFit(height, upper, upunc)
print(aUp)
print(bUp)
print(red_chi_sqUp)

aLow, bLow, red_chi_sqLow = LinearFit(height, lower, lowunc)
print(aLow)
print(bLow)
print(red_chi_sqLow)

#plot of best fit vs data
fig = plt.figure()
plt.errorbar(height, upper, yerr=upunc, fmt='ro')
plt.errorbar(height, lower, yerr=lowunc, fmt='bo')
plt.plot(height, aUp+bUp*height, 'r', label = 'Upper Bound Fit: .255x+8.73')
plt.plot(height, aLow+bLow*height, 'b', label = 'Lower Bound Fit: -.0616x+8.55')
plt.title('Upper and Lower Bounds on Unstable Region')
plt.xlabel('Height Modulation Amplitude (cm)')
plt.ylabel('Angular Frequency (rad/sec)')
plt.legend()
plt.savefig('bounds.png', dpi=300, bbox_inches='tight')
plt.close()

xx = np.linspace(2.4, 4.8, num=50)
theoryUp = []
theoryLow = []
for i in xx:
    theoryUp.append(0.193*i+9.12)
    theoryLow.append((-0.193)*i+9.12)

#plot of theoretical fit vs data
fig = plt.figure()
plt.errorbar(height, upper, yerr=upunc, fmt='ro')
plt.errorbar(height, lower, yerr=lowunc, fmt='bo')
plt.plot(xx, theoryUp, 'r', label = 'Theoretical Upper Bound: .193x+9.12')
plt.plot(xx, theoryLow, 'b', label = 'Theoretical Lower Bound: -.193x+9.12')
plt.title('Theoretical Upper and Lower Bounds on Unstable Region')
plt.xlabel('Height Modulation Amplitude (cm)')
plt.ylabel('Angular Frequency (rad/sec)')
plt.legend()
plt.savefig('theory.png', dpi=300, bbox_inches='tight')
plt.close()

theoryUpPt = [9.72, 10.05, 9.91, 9.79, 9.58]
theoryLowPt = [8.52, 8.19, 8.33, 8.44, 8.65]
UpResid = np.subtract(upper, theoryUpPt)
LowResid = np.subtract(lower, theoryLowPt)

#Upper theoretical residual
fig = plt.figure()
plt.errorbar(height, UpResid, yerr=upunc, fmt='ro')
plt.title('Residual Plot of Theoretical Upper Bounds')
plt.xlabel('Height Modulation Amplitude (cm)')
plt.ylabel('Angular Frequency (rad/sec)')
plt.savefig('upperresiduals.png', dpi=300, bbox_inches='tight')
plt.close()

#Lower theoretical residual
fig = plt.figure()
plt.errorbar(height, LowResid, yerr=lowunc, fmt='bo')
plt.title('Residual Plot of Theoretical Lower Bounds')
plt.xlabel('Height Modulation Amplitude (cm)')
plt.ylabel('Angular Frequency (rad/sec)')
plt.savefig('lowerresiduals.png', dpi=300, bbox_inches='tight')
plt.close()

logAngle = [2.3, 2.08, 1.79, 1.39, 0.69]
time = [0, 32.16, 74.06, 133.65, 220.74]
timeunc = [0.01, 0.83, 1.12, 3.20, 6.62]

aDamp, bDamp, red_chi_sqDamp = LinearFit(logAngle, time, timeunc)
print(aDamp)
print(bDamp)
print(red_chi_sqDamp)

#plot of fit vs data
fig = plt.figure()
plt.errorbar(logAngle, time, yerr=timeunc, fmt='ro')
plt.plot(logAngle, aDamp+bDamp*logAngle, 'b', label = '-144.55x + 332.46')
plt.title('Log of Amplitude vs Time for Damped Pendulum')
plt.ylabel('Time (s)')
plt.xlabel('Log of Angle (Degrees)')
plt.legend()
plt.savefig('damping.png', dpi=300, bbox_inches='tight')
plt.close()


import sys
from pathlib import Path

import pycls
import timm
import torch
from efficientnet_pytorch import EfficientNet
from pycls.core.builders import build_model as pycls_build_model
from pycls.core.config import cfg, load_cfg

def get_backbone(backbone: str, num_classes: int = 4):
    out_channels = {
        "efficientnet-b0": 1280,
        "efficientnet-b2": 1408,
        "efficientnet-b3": 1536,
        "efficientnet-b5": 2048,
        "efficientnet-b7": 2560,
        "regnetx-1.6gf": 912,
        "pyconvhgresnet50": 2048,
        "pyconvhgresnet101": 2048,
        "pyconvhgresnet152": 2048,
        "pyconvresnet50": 2048,
        "pyconvresnet101": 2048,
        "pyconvresnet152": 2048,
    }

    if backbone.startswith("efficientnet"):
        return EfficientNet.from_pretrained(backbone), out_channels[backbone]

    if backbone.startswith("regnet"):
        pretrained_urls = {
            "regnetx-1.6gf": "https://dl.fbaipublicfiles.com/pycls/dds_baselines/160990626/RegNetX-1.6GF_dds_8gpu.pyth"
        }
        config_dir = Path(pycls.__file__).parent.parent / "configs/dds_baselines/" / backbone[:7]

        if backbone == "regnetx-1.6gf":
            load_cfg(config_dir, "RegNetX-1.6GF_dds_8gpu.yaml")
        else:
            raise ValueError
        cfg.freeze()

        model = pycls_build_model()
        model.load_state_dict(torch.utils.model_zoo.load_url(pretrained_urls[backbone], map_location="cpu"))

        return model, out_channels[backbone]

    if backbone.startswith("timm-"):
        return timm.create_model(backbone[5:], pretrained=True, num_classes=num_classes), None

    if backbone.startswith("pyconvhgresnet"):
        if "pyconv" not in sys.path:
            sys.path.append("pyconv")
        from pyconv.models import pyconvhgresnet

        model = getattr(pyconvhgresnet, backbone)(pretrained=True)
        del model.avgpool
        del model.fc
        return model, out_channels[backbone]

    if backbone.startswith("pyconvresnet"):
        if "pyconv" not in sys.path:
            sys.path.append("pyconv")
        from pyconv.models import pyconvresnet

        model = getattr(pyconvresnet, backbone)(pretrained=True)
        del model.avgpool
        del model.fc
        return model, out_channels[backbone]

    raise ValueError

def get_feature_of(name: str, model, x):
    if name.startswith("efficientnet"):
        return model.extract_features(x)
    elif name.startswith("regnet"):
        modules = list(model.children())[:-1]  # skip head
        for module in modules:
            x = module(x)
        return x
    elif name.startswith("pyconv"):
        x = model.conv1(x)
        x = model.bn1(x)
        x = model.relu(x)

        x = model.layer1(x)
        x = model.layer2(x)
        x = model.layer3(x)
        x = model.layer4(x)
        return x

    raise ValueError

# based on https://github.com/qubvel/segmentation_models.pytorch
def patch_first_conv(model, in_channels, reuse: bool = False):
    """Change first convolution layer input channels.
    In case:
        in_channels == 1 or in_channels == 2 -> reuse original weights
        in_channels > 3 -> make random kaiming normal initialization
    """

    # get first conv
    for module in model.modules():
        if isinstance(module, torch.nn.Conv2d):
            break

    # change input channels for first conv
    module.in_channels = in_channels
    old_weight = module.weight.detach()
    reset = False

    if in_channels == 1:
        weight = old_weight.sum(1, keepdim=True)
    elif in_channels == 2:
        weight = old_weight[:, :2] * (3.0 / 2.0)
    else:
        reset = True
        weight = torch.Tensor(module.out_channels, module.in_channels // module.groups, *module.kernel_size)

    module.weight = torch.nn.parameter.Parameter(weight)
    if reset:
        module.reset_parameters()

    if in_channels > 3 and reuse:
        weight = module.weight
        weight[:, :3] = old_weight
        module.weight = torch.nn.parameter.Parameter(weight)

def patch_first_conv_stride(model):
    # decrease first conv's stride
    modules_iter = iter(model.modules())
    for module in modules_iter:
        if isinstance(module, torch.nn.Conv2d) and tuple(module.stride) == (2, 2):
            break

    module.stride = (1, 1)

    for module in modules_iter:
        if isinstance(module, torch.nn.Conv2d) and tuple(module.stride) == (2, 2):
            break

    module.stride = (3, 3)

class Model(torch.nn.Module):
    def __init__(self, num_classes, backbone):
        super().__init__()
        self.backbone = backbone
        self.model, out_channels = get_backbone(backbone)

        if not self.backbone.startswith("timm-"):
            self.avg_pool = torch.nn.AdaptiveAvgPool2d(1)
            self.linear = torch.nn.Linear(out_channels, num_classes)

    def get_feature(self, x):
        if self.backbone.startswith("timm-"):
            raise NotImplementedError
        return get_feature_of(self.backbone, self.model, x)

    def forward(self, x):
        if self.backbone.startswith("timm-"):
            return self.model(x)
        else:
            x = self.get_feature(x)
            x = self.avg_pool(x).reshape(x.shape[0], -1)
            return self.linear(x)


# Sort a list of dictionaries.

continents = [
    {"continent": "Asia", "area": 31.0, "population": 3261},
    {"continent": "Africa", "area": 29.6, "population": 1341},
    {"continent": "Europe", "area": 22.1, "population": 748},
    {"continent": "North America", "area": 21.3, "population": 592},
    {"continent": "South America", "area": 17.5, "population": 431},
    {"continent": "Australia", "area": 8.5, "population": 43},
    {"continent": "Antarctica", "area": 13.7, "population": 0},
]

# There are two approaches to sorting:
#
# - sort in place using .sort() method or
# - return sorted list using sorted() function.

# Method 1: Sort in place
#
# Sort in place by (increasing) area.
#
continents.sort(key=lambda item: item.get("area"))
#
# Sort in place by (decreasing) population.
#
continents.sort(key=lambda item: item.get("population"), reverse=True)

# Method 2: Return sorted list
#
# Sort by (increasing) area.
#
sorted(continents, key=lambda item: item.get("area"))
#
# Sort by (decreasing) population.
#
sorted(continents, key=lambda item: item.get("population"), reverse=True)


from itertools import chain

from django.forms.widgets import (
    CheckboxSelectMultiple,
    CheckboxInput,
    RadioSelect,
    TextInput,
    TimeInput,
)
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape, format_html, html_safe

@html_safe
class SubWidget(object):
    """
    Some widgets are made of multiple HTML elements -- namely, RadioSelect.
    This is a class that represents the "inner" HTML element of a widget.
    """

    def __init__(self, parent_widget, name, value, attrs, choices):
        self.parent_widget = parent_widget
        self.name, self.value = name, value
        self.attrs, self.choices = attrs, choices

    def __str__(self):
        args = [self.name, self.value, self.attrs]
        if self.choices:
            args.append(self.choices)
        return self.parent_widget.render(*args)

@html_safe
class ChoiceInput(SubWidget):
    """
    An object used by ChoiceFieldRenderer that represents a single
    <input type='$input_type'>.
    """

    input_type = None  # Subclasses must define this

    def __init__(self, name, value, attrs, choice, index):
        self.name = name
        self.value = value
        self.attrs = attrs
        self.choice_value = force_text(choice[0])
        self.choice_label = force_text(choice[1])
        self.index = index
        if "id" in self.attrs:
            self.attrs["id"] += "_%d" % self.index

    def __str__(self):
        return self.render()

    def render(self, name=None, value=None, attrs=None):
        if self.id_for_label:
            label_for = format_html(' for="{}"', self.id_for_label)
        else:
            label_for = ""
        attrs = dict(self.attrs, **attrs) if attrs else self.attrs
        return format_html(
            "{} {}", label_for, self.tag(attrs), self.choice_label
        )

    def is_checked(self):
        return self.value == self.choice_value

    def tag(self, attrs=None):
        attrs = attrs or self.attrs
        final_attrs = dict(
            attrs, type=self.input_type, name=self.name, value=self.choice_value
        )
        if self.is_checked():
            final_attrs["checked"] = "checked"
        return format_html("<input{} />", flatatt(final_attrs))

    @property
    def id_for_label(self):
        return self.attrs.get("id", "")

class RadioChoiceInput(ChoiceInput):
    input_type = "radio"

    def __init__(self, *args, **kwargs):
        super(RadioChoiceInput, self).__init__(*args, **kwargs)
        self.value = force_text(self.value)

class CheckboxSelectMultipleWithIcon(CheckboxSelectMultiple):
    def render(self, name, value, attrs=None, renderer=None, choices=()):
        if value is None:
            value = []
        has_id = attrs and "id" in attrs
        final_attrs = self.build_attrs(attrs)
        output = ["
"]
        str_values = set([str(v) for v in value])
        for (i, (option_value, option_label)) in enumerate(
            chain(self.choices, choices)
        ):
            if has_id:
                final_attrs = dict(final_attrs, id="%s_%s" % (attrs["id"], i))
                label_for = ' for="%s"' % final_attrs["id"]
            else:
                label_for = ""
            cb = CheckboxInput(
                final_attrs, check_test=lambda value: str(value) in str_values
            )
            rendered_cb = cb.render(name, option_value)
            option_label = conditional_escape(option_label)
            x = option_label.split("|")
            if len(x) > 1:
                icon = x[0]
                option_label = x[1]
            else:
                icon = None
            if icon:
                image = "" % icon
            else:
                image = ""
            output.append(
                "
%s %s %s
"
                % (label_for, rendered_cb, image, option_label)
            )
        output.append("
")
        return mark_safe("\n".join(output))

class RadioInput2(RadioChoiceInput):
    def __str__(self):
        if "id" in self.attrs:
            label_for = ' for="%s_%s"' % (self.attrs["id"], self.index)
        else:
            label_for = ""
        choice_label = conditional_escape(self.choice_label)
        x = choice_label.split("|")
        if len(x) > 1:
            label = "   " % x[0] + x[1]
        else:
            label = x[0]
        self.attrs["class"] = "radioselectwithicon"
        return mark_safe("
%s %s
" % (self.tag(), label))

class RadioFieldRendererWithIcon(object):
    """An object used by RadioSelect to enable customization of radio widgets."""

    def __init__(self, name, value, attrs, choices):
        (self.name, self.value, self.attrs) = (name, value, attrs)
        self.choices = choices

    def __iter__(self):
        for (i, choice) in enumerate(self.choices):
            yield RadioInput2(self.name, self.value, self.attrs.copy(), choice, i)

    def __getitem__(self, idx):
        choice = self.choices[idx]
        return RadioInput2(self.name, self.value, self.attrs.copy(), choice, idx)

    def __str__(self):
        return self.render()

    def render(self):
        """Outputs a
 for this set of radio fields."""
        return mark_safe(
            "
%s
"
            % " ".join(['
%s
' % w for w in self])
        )

class RadioSelectWithIcon(RadioSelect):
    renderer = RadioFieldRendererWithIcon


from django.db import migrations, models
import django.utils.timezone

class Migration(migrations.Migration):

    dependencies = [
        ('django_chatterbot', '0011_blank_extra_data'),
    ]

    operations = [
        migrations.AddField(
            model_name='statement',
            name='created_at',
            field=models.DateTimeField(
                default=django.utils.timezone.now,
                help_text='The date and time that the statement was created at.'
            ),
        ),
    ]