import time
import threading
import logging
import socket
import threading
import sys
import pickle

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

try:
    import tkinter as tk # Python 3.x
    import tkinter.scrolledtext as ScrolledText
except ImportError:
    import Tkinter as tk # Python 2.x
    import ScrolledText

class TextHandler(logging.Handler):
    # This class allows you to log to a Tkinter Text or ScrolledText widget
    # Adapted from Moshe Kaplan: https://gist.github.com/moshekaplan/c425f861de7bbf28ef06

    def __init__(self, text):
        # run the regular Handler __init__
        logging.Handler.__init__(self)
        # Store a reference to the Text it will log to
        self.text = text

    def emit(self, record):
        msg = self.format(record)
        def append():
            self.text.configure(state='normal')
            self.text.insert(tk.END, msg + '\n')
            self.text.configure(state='disabled')
            # Autoscroll to the bottom
            self.text.yview(tk.END)
        # This is necessary because we can't modify the Text from other threads
        self.text.after(0, append)

class myGUI(tk.Frame):

    def __init__(self, parent, window, *args, **kwargs):
        tk.Frame.__init__(self, parent, *args, **kwargs)
        self.root = parent
        if window == 'main':
            self.build_gui()
        elif window == 'apps':
            self.build_app()
        elif window == 'file_manager':
            self.build_file_manager()

    def build_file_manager(self):
        self.root.title('FILE MANAGER')
        self.root.option_add('*tearOff', 'FALSE')
        self.grid(column=0, row=0, sticky='ew')

        entry = tk.Entry(self.root)
        entry.grid(row=1, column=0, sticky="nsew")

        button = tk.Button(self, text="Crear", command=lambda: send_message('create', 'FILE', entry.get()))
        button.configure(font='TkFixedFont')
        button.grid(row=2, column=1, sticky="nsew")

        button2 = tk.Button(self, text="Eliminar", command=lambda: send_message('delete', 'FILE', entry.get()))
        button2.configure(font='TkFixedFont')
        button2.grid(row=2, column=2, sticky="nsew")

    def build_app(self):
        self.root.title('APPS')
        self.root.option_add('*tearOff', 'FALSE')
        self.grid(column=0, row=0, sticky='ew')

        label = tk.Label(self, text="Modulo de aplicaciones")
        label.configure(font='TkFixedFont')
        label.grid(row=0, column=0, sticky="w")

        button = tk.Button(self, text="Iniciar", command=lambda: send_message('open', 'APP','APP'))
        button.configure(font='TkFixedFont')
        button.grid(row=1, column=0, sticky="nsew")

        button2 = tk.Button(self, text="Terminar", command=lambda: send_message('close', 'APP','APP'))
        button2.configure(font='TkFixedFont')
        button2.grid(row=1, column=1, sticky="nsew")

        label2 = tk.Label(self, text="App 1")
        label2.configure(font='TkFixedFont')
        label2.grid(row=2, column=0, sticky="w")

        button3 = tk.Button(self, text="Iniciar", command=lambda: send_message('open', 'APP','APP1'))
        button3.configure(font='TkFixedFont')
        button3.grid(row=3, column=0, sticky="nsew")

        button4 = tk.Button(self, text="Terminar", command=lambda: send_message('close', 'APP','APP1'))
        button4.configure(font='TkFixedFont')
        button4.grid(row=3, column=1, sticky="nsew")

        label3 = tk.Label(self, text="App  2")
        label3.configure(font='TkFixedFont')
        label3.grid(row=4, column=0, sticky="w")

        button5 = tk.Button(self, text="Iniciar", command=lambda: send_message('open', 'APP','APP2'))
        button5.configure(font='TkFixedFont')
        button5.grid(row=5, column=0, sticky="nsew")

        button6 = tk.Button(self, text="Terminar", command=lambda: send_message('close', 'APP','APP2'))
        button6.configure(font='TkFixedFont')
        button6.grid(row=5, column=1, sticky="nsew")

    def build_gui(self):
        # Build GUI
        self.root.title('GUI')
        self.root.option_add('*tearOff', 'FALSE')
        self.grid(column=0, row=0, sticky='ew')
        # self.grid_columnconfigure(0, weight=1, uniform='a')
        # self.grid_columnconfigure(1, weight=1, uniform='a')
        # self.grid_columnconfigure(2, weight=1, uniform='a')
        # self.grid_columnconfigure(3, weight=1, uniform='a')

        # Add text widget to display logging info
        label = tk.Label(self, text="Logger")
        label.configure(font='TkFixedFont')
        label.grid(row=1, column=1, sticky="w")

        st = ScrolledText.ScrolledText(self, state='disabled')
        st.configure(font='TkFixedFont')
        st.grid(column=0, row=2, sticky='w', columnspan=3)

        button = tk.Button(self, text="Aplicaciones", command=lambda: open_window('apps'))
        button.configure(font='TkFixedFont')
        button.grid(row=3, column=0, sticky="nsew")

        button2 = tk.Button(self, text="Archivos", command=lambda: open_window('file_manager'))
        button2.configure(font='TkFixedFont')
        button2.grid(row=3, column=1, sticky="nsew")

        # Create textLogger
        text_handler = TextHandler(st)

        # Logging configuration
        logging.basicConfig(filename='test.log',
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s - %(message)s')

        # Add the handler to logger
        logger = logging.getLogger()
        logger.addHandler(text_handler)

def open_window(wtype):
    window = tk.Tk()
    myGUI(window, wtype)

def connect():
    while True:
        try:
            data = sock.recv(1024)
            if data:
                data = pickle.loads(data)
                if data['codeterm'] == 3:
                    for line in data['data'].split('\n'):
                        logging.info(line)
        except:
            pass

def main():
    global sock
    sock.connect(("localhost", 4000))
    root = tk.Tk()
    myGUI(root, 'main')
    process = threading.Thread(target=connect)
    process.daemon = True
    process.start()
    # send_message('info','FILE','data')
    root.mainloop()

def send_message(process, dst, message):
    global sock
    msg = {'cmd': process, 'src': 'GUI', 'dst': dst, 'msg': message}
    sock.send(pickle.dumps(msg))

if __name__ == '__main__':
    main()


#!/usr/bin/python2.7

#######################################################################################################################
# batch_ops_plugin.py
# Description: custom operators for Nike BI batch processing
# Go to the bottom of the code to see what are the operators created in this code
# the code
#######################################################################################################################
import logging
import time
from airflow.models import BaseOperator, XCom
from airflow import settings
from airflow.utils.decorators import apply_defaults
from airflow.plugins_manager import AirflowPlugin
from batch_common import BICommon
from airflow.exceptions import AirflowException
from sqlalchemy import and_
from datetime import datetime, timedelta
import random

def pull_profile_from_xcom(context):
    profile = context['ti'].xcom_pull(key='profile', task_ids='start_batch')
    if profile is None:
        raise AirflowException("Cannot find profile, need to use BatchStartOperator to persist profile")
    return profile

def pull_env_from_xcom(context):
    env = context['ti'].xcom_pull(key='env', task_ids='start_batch')
    if env is None:
        raise AirflowException("Cannot find env, need to use BatchStartOperator to persist env")
    return env

class BatchOperator(BaseOperator):
    @apply_defaults
    def __init__(self,
                 *args, **kwargs):
        super(BatchOperator, self).__init__(*args, **kwargs)
        self.profile = None

    @staticmethod
    def get_prev_run(context):
        logging.info('getting previous run dates for dag')
        execution_date = context['execution_date']
        cls = XCom
        filters = [cls.key == 'exec_dates', cls.task_id == 'success', cls.dag_id == context['dag'].dag_id,
                   cls.execution_date < execution_date]

        session = settings.Session()
        query = (
            session.query(cls.value)
            .filter(and_(*filters))
            .order_by(cls.execution_date.desc(), cls.timestamp.desc())
            .limit(1))
        result = query.first()
        session.close()

        if result:
            return result.value
        else:
            return None

class BatchStartOperator(BatchOperator):
    ui_color = '#D8BFD8'

    def check_if_catch_up(self, context):
        try:
            time_diff = datetime.now() - context['execution_date']
            if time_diff > \
                    (context['dag'].schedule_interval + context['dag'].schedule_interval):
                logging.info(
                    "This is a catch up run, this whole dag will be marked success, only the most recent "
                    "schedule will be executed.")
                self.is_catchup = True
        except Exception:
            self.is_catchup = False

    @apply_defaults
    def __init__(self,
                 task_id='start_batch',
                 catch_up=False,
                 *args, **kwargs):
        super(BatchStartOperator, self).__init__(task_id=task_id, *args, **kwargs)
        self.env_type = None
        self.profile = None
        self.catch_up = catch_up
        self.is_catchup = False

    def execute(self, context):
        logging.info("storing batch information ")
        # check if the profile is already persisted in xcom, this only occurs if the DMStartOperator has run before this
        self.check_if_catch_up(context)
        if self.is_catchup and self.catch_up:
            # don't run the current run - force complete this run, and let the real run to run
            for t in context['dag'].tasks:
                if t != context['task']:
                    t.run(
                        start_date=context['execution_date'],
                        end_date=context['execution_date'],
                        mark_success=True,
                        ignore_dependencies=True)
        else:

            bicommon = BICommon()
            self.profile = bicommon.get_profile()

            epoch = int(time.time())

            # persist env in xcom
            self.env_type = bicommon.env

            execution_date = context['execution_date'].strftime('%Y-%m-%dT%H:%M:%S')
            curr_rundate = context['ds_nodash']

            prev_run = self.get_prev_run(context)

            if prev_run is not None:
                prev_exec_date = prev_run['execution_date']
                prev_rundate = prev_run['curr_rundate']
                prev_epoch = prev_run['curr_epoch']
            else:
                prev_exec_date = None
                prev_rundate = None
                prev_epoch = None

            xcom_keys = ['env','execution_date','curr_rundate','curr_epoch','prev_rundate','prev_epoch','prev_exec_date']

            for key in xcom_keys:

                # Waiting for a random duration
                wait_time = random.randrange(0, 30)
                time.sleep(wait_time)

                # Set Key Values
                if key == 'env':
                    value = bicommon.env
                elif key == 'curr_epoch':
                    value = epoch
                else:
                    value=eval(key)

                logging.info("Storing %s in xcom table: %s" %(key,value))

                # Start the XCOM Push
                retry_counter = 0
                while True:
                    try:
                        self.xcom_push(context=context, key=key, value=value)
                        break
                    except Exception as e:
                        retry_counter += 1
                        wait_time = retry_counter*60
                        # Random wait in between re-attempts
                        time.sleep(wait_time)
                        if retry_counter > 3:
                            break
                        else:
                            pass
                # If already tried 3 times, raise an error
                if retry_counter == 4:
                    logging.info("Encountered exception while inserting data into xcom table")
                    raise ValueError(e)

class BatchEndOperator(BatchOperator):
    ui_color = '#D8BFD8'

    @apply_defaults
    def __init__(self,
                 task_id='success',
                 *args, **kwargs):
        super(BatchEndOperator, self).__init__(task_id=task_id, *args, **kwargs)
        self.profile = None

    def execute(self, context):
        logging.info("storing end batch information ")

        execution_date = context['execution_date'].strftime('%Y-%m-%dT%H:%M:%S')

        # try getting the xcom from start_batch, if can't get it, get variables at this step instead of
        # throwing exception
        try:
            curr_rundate = context['ti'].xcom_pull(key='curr_rundate', task_ids='start_batch')
            epoch = context['ti'].xcom_pull(key='curr_epoch', task_ids='start_batch')
            prev_rundate = context['ti'].xcom_pull(key='prev_rundate', task_ids='start_batch')
            prev_epoch = context['ti'].xcom_pull(key='prev_epoch', task_ids='start_batch')
            prev_exec_date = context['ti'].xcom_pull(key='prev_exec_date', task_ids='start_batch')
        except Exception:
            logging.info("xcom not found in start_batch")
            epoch = int(time.time())
            curr_rundate = context['ds_nodash']
            item = {
                'execution_date': execution_date,
                'curr_rundate': curr_rundate,
                'curr_epoch': epoch
            }
            self.xcom_push(context=context, key='exec_dates', value=item)

        else:
            item = {
                'execution_date': execution_date,
                'curr_rundate': curr_rundate,
                'curr_epoch': epoch,
                'prev_exec_date': prev_exec_date,
                'prev_rundate': prev_rundate,
                'prev_epoch': prev_epoch,
            }
            self.xcom_push(context=context, key='exec_dates', value=item)

# Defining the plugin class
class AirflowBatchOpPlugin(AirflowPlugin):
    name = "batch_ops_plugin"
    operators = [
        BatchStartOperator,
        BatchEndOperator
    ]


from RobotArm import RobotArm

robotArm = RobotArm('exercise 10')

# Jouw python instructies zet je vanaf hier:
nummer = 9
nummer2 = 8
for x in range(5):
    robotArm.grab()
    for x in range(nummer):
        robotArm.moveRight()
    robotArm.drop()
    for x in range(nummer2):
        robotArm.moveLeft()

    nummer -= 2
    nummer2 -= 2

# Na jouw code wachten tot het sluiten van de window:
robotArm.wait()


from datetime import datetime, timedelta
from json_queue import JsonInterface

def make_duty(names: list, period: int, q: JsonInterface, k: int = 1) -> None:
	for name in names:
		q.enqueue(name, [])
		if name not in q.get_absence():
			q.enabsence(name, [])
	dates_for_next = []
	k = 1
	holidays = q.get_holidays()
	absence = q.get_absence_dict()
	for name in names:
		dates = []
		for days in dates_for_next:
			dates.append(days)
		print(dates)
		dates_for_next = []
		# for j in range(period - len(dates)):
		while len(dates) < period:
			date = (datetime.now() + timedelta(days=k)).strftime("%d.%m")
			check_week = (datetime.now() + timedelta(days=k)).strftime("%A")
			date_miss = (datetime.now() + timedelta(days=k)).strftime("%d.%m.%Y")

			date_add = (datetime.now() + timedelta(days=k)).strftime("%d.%m.%Y")
			if date not in holidays and (check_week not in ('Saturday', 'Sunday')):
				if date_miss not in absence[name]:
					k += 1
					dates.append(date_add)
				else:
					k += 1
					dates_for_next.append(date_miss)
			else:
				k += 1
		q.enqueue(name, dates)

if __name__ == "__main__":
	j = JsonInterface()
	remake_duty(0, j)


import re

def check(s):
   t = ''
   for i in range(len(s)):
      if s[i].isupper():
         t += '_'
         t += s[i]
      else:
         t += s[i]
   return t

s = input()

txt = check(s)

l = re.split(r'_',txt)

for i in l:
   print(i,end=' ')


from PIL import Image

import torch
from torch.optim.lr_scheduler import LambdaLR
import torchvision.transforms.functional as TF
import pytorch_lightning as pl

from .losses import focal_loss, water_obstacle_separation_loss, object_projection_loss, object_focal_loss
from .pairwise_affinity import pairwise_affinity_loss, object_pairwise_affinity_loss
from .metrics import PixelAccuracy, ClassIoU
from .utils import bool_arg

NUM_EPOCHS = {'warmup':25, 'finetune':50}
LEARNING_RATE = 1e-6
MOMENTUM = 0.9
WEIGHT_DECAY = 1e-6
LR_DECAY_POW = 0.9
FOCAL_LOSS_SCALE = 'labels'
SEPARATION_LOSS = {'warmup':False, 'finetune':True}
SL_LAMBDA = 0.01
PA_LOSS = {'warmup':True, 'finetune':True}
PA_LOSS_LAMBDA = 1
PA_LOSS_TAU = 0.1
OBJ_LOSS = {'warmup':True, 'finetune':False}
OBJ_LOSS_LAMBDA = 1

class LitModel(pl.LightningModule):
    """ Pytorch Lightning wrapper for a model, ready for distributed training. """

    @staticmethod
    def add_argparse_args(parser, phase):
        """Adds phase-specific model parameters to parser."""

        parser.add_argument("--learning-rate", type=float, default=LEARNING_RATE,
                            help="Base learning rate for training with polynomial decay.")
        parser.add_argument("--momentum", type=float, default=MOMENTUM,
                            help="Momentum component of the optimiser.")
        parser.add_argument("--epochs", type=int, default=NUM_EPOCHS[phase],
                            help="Number of training epochs.")
        parser.add_argument("--lr-decay-pow", type=float, default=LR_DECAY_POW,
                            help="Decay parameter to compute the learning rate decay.")
        parser.add_argument("--weight-decay", type=float, default=WEIGHT_DECAY,
                            help="Regularisation parameter for L2-loss.")
        parser.add_argument("--focal-loss-scale", type=str, default=FOCAL_LOSS_SCALE, choices=['logits', 'labels'],
                            help="Which scale to use for focal loss computation (logits or labels).")
        parser.add_argument("--separation-loss", default=SEPARATION_LOSS[phase], type=bool_arg,
                            help="Use separation loss.")
        parser.add_argument("--separation-loss-lambda", default=SL_LAMBDA, type=float,
                            help="The separation loss lambda (weight).")
        parser.add_argument("--separation-loss-sky", action='store_true',
                            help="Include sky in the separation loss computation.")
        parser.add_argument("--pairwise-affinity-loss", type=bool_arg, default=PA_LOSS[phase],
                            help="Add the pairwise affinity loss term.")
        parser.add_argument("--pairwise-affinity-loss-lambda", default=PA_LOSS_LAMBDA, type=float,
                            help="The pairwise affinity loss lambda (weight).")
        parser.add_argument("--pairwise-affinity-loss-tau", default=PA_LOSS_TAU, type=float,
                            help="The pairwise affinity loss tau (similarity threshold).")
        parser.add_argument("--object-loss", type=bool_arg, default=OBJ_LOSS[phase],
                            help="Add the object loss term.")
        parser.add_argument("--object-loss-pa", type=bool_arg, default=True,
                            help="Enable object loss PA term.")
        parser.add_argument("--object-loss-proj", type=bool_arg, default=True,
                            help="Enable object loss projection loss term.")
        parser.add_argument("--object-loss-aux", type=bool_arg, default=True,
                            help="Enable object loss auxiliary segmentation term.")
        parser.add_argument("--object-loss-lambda", default=OBJ_LOSS_LAMBDA, type=float,
                            help="The object loss lambda (weight).")

        return parser

    def __init__(self, model, num_classes, args):
        super().__init__()

        self.model = model
        self.num_classes = num_classes

        self.epochs = args.epochs
        self.learning_rate = args.learning_rate
        self.momentum = args.momentum
        self.weight_decay = args.weight_decay
        self.lr_decay_pow = args.lr_decay_pow
        self.focal_loss_scale = args.focal_loss_scale
        self.separation_loss = args.separation_loss
        self.separation_loss_lambda = args.separation_loss_lambda
        self.separation_loss_sky = args.separation_loss_sky
        self.pairwise_affinity_loss = args.pairwise_affinity_loss
        self.pairwise_affinity_loss_lambda = args.pairwise_affinity_loss_lambda
        self.pairwise_affinity_loss_tau = args.pairwise_affinity_loss_tau
        self.object_loss = args.object_loss
        self.object_loss_lambda = args.object_loss_lambda
        self.object_loss_pa = args.object_loss_pa
        self.object_loss_proj = args.object_loss_proj
        self.object_loss_aux = args.object_loss_aux

        self.val_accuracy = PixelAccuracy(num_classes)
        self.val_iou_0 = ClassIoU(0, num_classes)
        self.val_iou_1 = ClassIoU(1, num_classes)
        self.val_iou_2 = ClassIoU(2, num_classes)

    def forward(self, x):
        output = self.model(x)
        return output['out']

    def training_step(self, batch, batch_idx):
        features, labels = batch

        out = self.model(features)

        fl = focal_loss(out['out'], labels['segmentation'], target_scale=self.focal_loss_scale)

        separation_loss = torch.tensor(0.0)
        if self.separation_loss:
            separation_loss = water_obstacle_separation_loss(
                out['aux'], labels['segmentation'], include_sky=self.separation_loss_sky)

        pa_loss = torch.tensor(0.0)
        if self.pairwise_affinity_loss:
            ignore_mask = None
            if self.object_loss is not None:
                ignore_mask = labels['objects'].max(1).values
            pa_loss = pairwise_affinity_loss(out['out'], labels['segmentation'], labels['pa_similarity'],
                                             tau=self.pairwise_affinity_loss_tau, target_scale=self.focal_loss_scale, ignore_mask=ignore_mask)

        separation_loss = self.separation_loss_lambda * separation_loss
        pa_loss = self.pairwise_affinity_loss_lambda * pa_loss
        bg_loss = fl + separation_loss + pa_loss

        obj_loss_o = torch.tensor(0.0)
        obj_loss_pa = torch.tensor(0.0)
        obj_loss_aux = torch.tensor(0.0)
        obj_loss = torch.tensor(0.0)
        if self.object_loss:
            if self.object_loss_proj:
                obj_loss_o = object_projection_loss(out['out'], labels['objects'], labels['n_objects'], target_scale=self.focal_loss_scale,
                                                    normalize=True, reduce='sum')

            if self.object_loss_pa:
                obj_loss_pa = object_pairwise_affinity_loss(out['out'], labels['objects'], labels['n_objects'], labels['pa_similarity'],
                                                            tau=self.pairwise_affinity_loss_tau, normalize=True, reduce='sum')

            if self.object_loss_aux:
                obj_loss_aux = object_focal_loss(out['out'], labels['objects'], labels['n_objects'], labels['instance_seg'],
                                                normalize=True, reduce='sum')

            obj_loss = obj_loss_o + obj_loss_pa + obj_loss_aux

        loss = bg_loss + obj_loss

        # log losses
        self.log('train/loss', loss.item())
        self.log('train/bg/focal_loss', fl.item())
        self.log('train/bg/separation_loss', separation_loss.item())
        self.log('train/bg/pa_loss', pa_loss.item())
        self.log('train/bg_loss', bg_loss.item())
        self.log('train/obj/proj_loss', obj_loss_o.item())
        self.log('train/obj/pa_loss', obj_loss_pa.item())
        self.log('train/obj/aux_loss', obj_loss_aux.item())
        self.log('train/obj_loss', obj_loss.item())

        return loss

    def training_epoch_end(self, outputs):
        # Bugfix
        pass

    def validation_step(self, batch, batch_idx):
        features, labels = batch

        out = self.model(features)

        loss = focal_loss(out['out'], labels['segmentation'], target_scale=self.focal_loss_scale)

        # Log loss
        self.log('val/loss', loss.item())

        # Metrics
        labels_size = (labels['segmentation'].size(2), labels['segmentation'].size(3))
        logits = TF.resize(out['out'], labels_size, interpolation=Image.BILINEAR)
        preds = logits.argmax(1)

        # Create hard labels from soft
        labels_hard = labels['segmentation'].argmax(1)
        ignore_mask = labels['segmentation'].sum(1) < 0.9
        labels_hard = labels_hard * ~ignore_mask + 4 * ignore_mask

        self.val_accuracy(preds, labels_hard)
        self.val_iou_0(preds, labels_hard)
        self.val_iou_1(preds, labels_hard)
        self.val_iou_2(preds, labels_hard)

        self.log('val/accuracy', self.val_accuracy)
        self.log('val/iou/obstacle', self.val_iou_0)
        self.log('val/iou/water', self.val_iou_1)
        self.log('val/iou/sky', self.val_iou_2)

        return {'loss': loss, 'preds': preds}

    def configure_optimizers(self):
        # Separate parameters for different LRs
        encoder_parameters = []
        decoder_w_parameters = []
        decoder_b_parameters = []
        for name, parameter in self.model.named_parameters():
            if name.startswith('backbone'):
                encoder_parameters.append(parameter)
            elif 'weight' in name:
                decoder_w_parameters.append(parameter)
            else:
                decoder_b_parameters.append(parameter)

        optimizer = torch.optim.RMSprop([
            {'params': encoder_parameters, 'lr': self.learning_rate},
            {'params': decoder_w_parameters, 'lr': self.learning_rate * 10},
            {'params': decoder_b_parameters, 'lr': self.learning_rate * 20},
        ], momentum=self.momentum, alpha=0.9, weight_decay=self.weight_decay)

        # Decaying LR function
        lr_fn = lambda epoch: (1 - epoch/self.epochs) ** self.lr_decay_pow

        # Decaying learning rate (updated each epoch)
        scheduler = LambdaLR(optimizer, lr_fn)

        return [optimizer], [scheduler]

    def on_save_checkpoint(self, checkpoint):
        # Export the model weights
        checkpoint['model'] = self.model.state_dict()


from random import randint, shuffle, seed, choice
class Node:
    __slots__ = 'value', 'next_node'

    def __init__(self, value, next_node=None):
        """
        Initialize a node
        :param value: value of the node
        :param next_node: pointer to the next node, default is None
        """
        self.value = value  # element at the node
        self.next_node = next_node  # reference to next node

    def __eq__(self, other):
        """
        Determine if two nodes are equal (same value)
        :param other: node to compare to
        :return: True if nodes are equal, False otherwise
        """
        if other is None:
            return False
        if self.value == other.value:
            return True
        return False

    def __repr__(self):
        """
        String representation of a node
        :return: string of value
        """
        return str(self.value)

def _insertion_wrapper(insertion_sort):
    """
    :return:
    """

    def insertion_counter(self, *args, **kwargs):
        if self.size > 1:
            LinkedList._c += 1
        insertion_sort(self)
    return insertion_counter

class LinkedList:
    _c = 0

    def __init__(self, data=None):
        """
        Create/initialize an empty linked list
        """
        self.head = None  # Node
        self.tail = None  # Node
        self.size = 0  # Integer

        if data:
            [self.push_back(i) for i in data]

    def __len__(self):
        return self.length()

    def __eq__(self, other):
        """
        Defines "==" (equality) for two linked lists
        :param other: Linked list to compare to
        :return: True if equal, False otherwise
        """
        if self.size != other.size:
            return False
        if self.head != other.head or self.tail != other.tail:
            return False

        # Traverse through linked list and make sure all nodes are equal
        temp_self = self.head
        temp_other = other.head
        while temp_self is not None:
            if temp_self == temp_other:
                temp_self = temp_self.next_node
                temp_other = temp_other.next_node
            else:
                return False
        # Make sure other is not longer than self
        if temp_self is None and temp_other is None:
            return True
        return False

    def __repr__(self):
        """
        String representation of a linked list
        :return: string of list of values
        """
        temp_node = self.head
        values = []
        if temp_node is None:
            return str([])
        while temp_node is not None:
            values.append(temp_node.value)
            temp_node = temp_node.next_node
        return str(values)

    # ------------------------Accessor Functions---------------------------

    def length(self):
        """
        Gets the number of nodes of the linked list
        :return: size of list
        """
        return self.size

    def is_empty(self):
        """
        Determines if the linked list is empty
        :return: True if list is empty and False if not empty
        """
        return self.size == 0

    def front_value(self):
        """
        Gets the first value of the list
        :return: value of the list head
        """
        if self.is_empty():
            return None
        return self.head.value

    def push_front(self, val):
        """
        Adds a node to the front of the list with value 'val'
        :param val: value to add to list
        :return: no return
        """
        new_node = Node(val, self.head)
        if self.is_empty():
            self.tail = new_node
        self.head = new_node
        self.size += 1

    def push_back(self, val):
        """
        Adds a node to the back of the list with value 'val'
        :param val: value to add to list
        :return: no return
        """
        new_node = Node(val)
        # Update current head and tail, if necessary
        if self.is_empty():
            self.head = new_node
        else:
            self.tail.next_node = new_node
        # new_node is now the tail
        self.tail = new_node
        self.size += 1

    def pop_front(self):
        """
        Removes a node from the front of the list
        :return: the value of the removed node
        """
        if self.is_empty():
            return None
        val = self.head.value
        # Update head and size
        self.head = self.head.next_node
        self.size -= 1
        # If the only node was removed, also need to update tail
        if self.is_empty():
            self.tail = None
        return val

    @_insertion_wrapper
    def insertion_sort(self):
        """
        Sorts the singly linked list using a placeholder list.
        :return: nothing
        """
        leng = self.length()
        if self.is_empty():
            return None
        new = LinkedList()
        new.push_back(self.front_value())
        real_head = self.head.next_node
        count = 0
        while count < leng - 1:
            if real_head.value >= new.tail.value:
                new.push_back(real_head.value)

            elif real_head.value <= new.head.value:
                new.push_front(real_head.value)

            else:
                new_head = new.head
                while new_head.next_node is not None:
                    if real_head.value <= new_head.next_node.value and real_head.value > new_head.value:
                        temp = Node(real_head.value, new_head.next_node)
                        new_head.next_node = temp
                        new.size += 1
                        new_head = new_head.next_node
                        break
                    else:
                        new_head = new_head.next_node
                        continue
            real_head = real_head.next_node
            count += 1
        self.head = new.head
        self.tail = new.tail
        self.size = new.size


import requests
from bs4 import BeautifulSoup
import sqlite3

head = {"userAgent": "Mozilla/5.0 (X11; Linux i686 on x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2909.25 Safari/537.36"}

first_req = requests.get("https://www.myauto.ge/ka/s/0/0/25/ML-Klasse/2008/00/00/00/iyideba-mercedes-benz-ml-klasse-(%E1%83%A7%E1%83%95%E1%83%94%E1%83%9A%E1%83%90)-2008-geo?stype=0&for_rent=0&marka=25&model=ML-Klasse&year_from=2008&price_from=1000&currency_id=3&loc_id=1&det_search=0&ord=7&last_model=ML-Klasse&keyword=&category_id=m0&page=1")
req_cont = first_req.text

num_soup = BeautifulSoup(req_cont, "html.parser")

last_page = num_soup.find("li", {"class":"pagination-li last-page"})

a_number = last_page.find("a")["href"].split("=")[-1]

BASE_URL = "https://www.myauto.ge/ka/s/0/0/25/ML-Klasse/2008/00/00/00/iyideba-mercedes-benz-ml-klasse-(%E1%83%A7%E1%83%95%E1%83%94%E1%83%9A%E1%83%90)-2008-geo?stype=0&for_rent=0&marka=25&model=ML-Klasse&year_from=2008&price_from=1000&currency_id=3&loc_id=1&det_search=0&ord=7&last_model=ML-Klasse&keyword=&category_id=m0&page="

for page in range(1, int(a_number)):

	request = requests.get(BASE_URL+str(page), headers=head)
	content = request.text

	soup = BeautifulSoup(content, "html.parser")

	main_container = soup.find("div", {"class":"container-main"})

	cars_list = main_container.find_all("div", {"class":"car-short-info"})

	for item in cars_list:
		car_name = item.find("a").text.strip()

		car_id = item.find("div", {"class":"cr-vp-lbl"}).text

		year = item.find("p", {"class":"car-year"}).text.strip()

		try:
			levy = item.find("p", {"class":"car-levy passed"}).text.strip()
		except:
			levy = "განუბაჟებელი"

		engine = item.find("div", {"data-info":"ძრავი"}).text.strip()

		kilometrage = item.find("div", {"class":"cr-road"}).text.strip()

		transmission = item.find("div", {"class":"cr-wheel"}).text.strip()

		wheel = item.find("div", {"class":"cr-gas"}).text.strip()

		place = item.find("p", {"class":"car-list-row"}).text.strip().split()[0]

		prices = item.find("div", {"price-title-container"})
		price_gel = prices.find_all("label")[0].text.strip()
		price_usd = prices.find_all("label")[1].text.strip()

		print(f"{car_name}; {car_id}; \nმდებარეობა:->> {place}; წელი: {year};\
				\nძრავი:->> {engine}; განვლილი მანძილი(km):->> {kilometrage}\
				\nგადაცემათა კოლოფი:->> {transmission}; \nსაჭე:->> {wheel}; \nგანბაჟება: {levy};")

		print(f"USD: {price_usd}; GEL: {price_gel}\n")

	print("-------------------------------------------------------------------")


#
# @lc app=leetcode.cn id=2423 lang=python3
#
# [2423] 删除字符使频率相同
#
# https://leetcode.cn/problems/remove-letter-to-equalize-frequency/description/
#
# algorithms
# Easy (18.99%)
# Likes:    15
# Dislikes: 0
# Total Accepted:    5.4K
# Total Submissions: 28.2K
# Testcase Example:  '"abcc"'
#
# 给你一个下标从 0 开始的字符串 word ，字符串只包含小写英文字母。你需要选择 一个 下标并 删除 下标处的字符，使得 word 中剩余每个字母出现
# 频率 相同。
#
# 如果删除一个字母后，word 中剩余所有字母的出现频率都相同，那么返回 true ，否则返回 false 。
#
# 注意：
#
#
# 字母 x 的 频率 是这个字母在字符串中出现的次数。
# 你 必须 恰好删除一个字母，不能一个字母都不删除。
#
#
#
#
# 示例 1：
#
# 输入：word = "abcc"
# 输出：true
# 解释：选择下标 3 并删除该字母，word 变成 "abc" 且每个字母出现频率都为 1 。
#
#
# 示例 2：
#
# 输入：word = "aazz"
# 输出：false
# 解释：我们必须删除一个字母，所以要么 "a" 的频率变为 1 且 "z" 的频率为 2
# ，要么两个字母频率反过来。所以不可能让剩余所有字母出现频率相同。
#
#
#
#
# 提示：
#
#
# 2 <= word.length <= 100
# word 只包含小写英文字母。
#
#
#

# @lc code=start
class Solution:

    def equalFrequency(self, word: str) -> bool:

        def judge(li: list[int]) -> bool:
            lit = [x for x in li if x != 0]
            for v in lit:
                if v != lit[0]: return False
            return True

        li = [0 for _ in range(26)]
        se = set(word)
        for c in word:
            i = ord(c) - ord('a')
            li[i] += 1

        for c in se:
            i = ord(c) - ord('a')
            li[i] -= 1
            if judge(li): return True
            li[i] += 1
        return False

# @lc code=end

2423.删除字符使频率相同.py


import argparse
import asyncio
import os.path

from tornado.platform.asyncio import AsyncIOMainLoop
from tornado.web import Application
from tornado.web import StaticFileHandler
from tornado.httpserver import HTTPServer
from tornado.options import define

from libs import setup

from handlers import (
    IndividualView,
    TwilioView,
    WebSocketHandler
)
from handlers.websocket.view import infinite_update_loop

# CONSTANTS
parser = argparse.ArgumentParser(description='commodus')
parser.add_argument('dbuser', help='database username string')
parser.add_argument('dbpass', help='database password string')
parser.add_argument('dbhost', help='database host string (ex: 120.0.0.1)')
parser.add_argument('dbname', help='database name string')
parser.add_argument('--dbport', help='database port integer (ex: 5432)', type=int, default=5432)
parser.add_argument('--port', help='API server port integer (ex: 8080)', type=int, default=8080)
config = parser.parse_args()
define('username', default=config.dbuser, type=str, group='db')
define('password', default=config.dbpass, type=str, group='db')
define('host', default=config.dbhost, type=str, group='db')
define('name', default=config.dbname, type=str, group='db')
define('port', default=config.dbport, type=int, group='db')

logger = setup.log(name='commodus', version='v1')

def main():
    AsyncIOMainLoop().install()
    server = HTTPServer(
        Application(
            [
                (r'/v1/twilio/', TwilioView),
                (r"/v1/individual/([0-9A-F]{32})", IndividualView),
                (r'/static/(.*)', StaticFileHandler, {'path': 'static'}),
                (r'/ws', WebSocketHandler),
                (r'/(.*)', StaticFileHandler, {'path': 'static', 'default_filename': 'index.html'}),
            ],
            # default_handler_class=NotFoundView,
            template_path=os.path.join(os.path.dirname(__file__), "static")
        )
    )
    server.bind(8080)
    server.start()  # Forks multiple sub-processes
    logger.info("installing background services")
    asyncio.ensure_future(infinite_update_loop())
    logger.info("server is waiting for a connection")
    asyncio.get_event_loop().run_forever().start()

if __name__ == "__main__":
    main()


from pynput import keyboard
import time

script_on = False

#Listener
def on_press(key):
    try: k = key.char
    except: k = key.name

    if key == keyboard.Key.esc:
        return False

    if key == 'F10':
        print("Script toggled")
        script_on = not script_on

#Main body
def main():
    #Setting listener
    listener = keyboard.Listener(on_press=on_press)
    listener.start()

    while True:
        time.sleep(10)


import torch
import random
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence

if torch.cuda.is_available():
    device = torch.device('cuda')
else:
    device = torch.device('cpu')
class DecoderNet(nn.Module):
    def __init__(
        self, word_vectors, output_size, embed_size, hidden_size=1024,
        dropout_keep_prob=1, max_length=110, num_layers=4
    ):
        super(DecoderNet, self).__init__()
        self.embed = nn.Embedding(output_size, embed_size)
        self.gru = nn.GRU(
            (embed_size + 3*32*32), hidden_size, num_layers, batch_first=True,
        )
        self.linear = nn.Linear(hidden_size, output_size)
        self.max_length = max_length
        self.word_vectors = word_vectors
        self.output_size = output_size
        # self._init()

    def _init(self):
        self.embed.weight.data = self.word_vectors

    # Foward and sample stolen from https://github.com/yunjey/pytorch-tutorial
    def forward(self, features, captions, lengths, teacher_forcing_ratio=0.75):
        """Decode image feature vectors and generate captions."""
        # use_teacher_forcing = True if random.random() < teacher_forcing_ratio else False
        loss = 0.0;
        embeddings = self.embed(captions); features = features.unsqueeze(1)
        # print(embeddings.shape, features.shape)
        features = features.expand(embeddings.shape[0], embeddings.shape[1], features.shape[-1])
        embeddings = torch.cat((features, embeddings), -1)

        states = None; weights = torch.ones(self.output_size).to(device); weights[622] = 0
        for t in range(embeddings.shape[1]):
            use_teacher_forcing = True
            if t == 0: inputs = embeddings[:, t, :].unsqueeze(1)
            hiddens, states = self.gru(inputs, states)
            cur_output = self.linear(hiddens.squeeze(1))
            _, predicted = cur_output.max(1)

            loss_function = nn.CrossEntropyLoss(weight=weights, reduce=False)
            if not use_teacher_forcing:
                predicted = predicted.detach()
                inputs = self.embed(predicted).unsqueeze(1)
                inputs = torch.cat((features[:, t, :].unsqueeze(1), inputs), -1)
                loss += loss_function(cur_output, captions[:, t])
            else:
                inputs = embeddings[:, t, :].unsqueeze(1)
                loss += loss_function(cur_output, captions[:, t])
        return loss

    def sample(self, features, states=None):
        """Generate captions for given image features using greedy search."""
        sampled_ids = []
        START = self.word_vectors[621].expand((features.shape[0], 1, 100))
        embeddings = START.to(device); features = features.unsqueeze(1)
        features = features.expand(embeddings.shape[0], embeddings.shape[1], features.shape[-1])
        embeddings = torch.cat((features, embeddings), -1)

        for i in range(self.max_length):
            hiddens, states = self.gru(embeddings, states)       # hiddens: (batch_size, 1, hidden_size)
            outputs = self.linear(hiddens.squeeze(1))            # outputs:  (batch_size, vocab_size)
            _, predicted = outputs.max(1)                        # predicted: (batch_size)
            sampled_ids.append(predicted)
            embeddings = self.embed(predicted).unsqueeze(1)      # inputs: (batch_size, embed_size)
            embeddings = torch.cat((features, embeddings), -1)   # inputs: (batch_size, 1, embed_size)
        sampled_ids = torch.stack(sampled_ids, 1)                # sampled_ids: (batch_size, max_length)
        return sampled_ids


# JEGYED50-BBC-MICROBIT-STUDY365-BLOCKS-03-03-C
# Fish animation with create big image and scroll image

twohalffish = images.create_big_image("""
    . . # . . . . . . .
        . # # . . # . . . .
        # # # # # # . . . .
        . # # . . # . . . .
        . . # . . . . . . .
""")

def on_forever():
    twohalffish.scroll_image(1, 200)
basic.forever(on_forever)


from .Handlers import send
import ba, _ba
from stats import mystats

Commands = ['me', 'list', 'uniqeid']
CommandAliases = ['stats', 'score', 'rank', 'myself', 'l', 'id', 'pb-id', 'pb', 'accountid']

def ExcelCommand(command, arguments, clientid, accountid):
	"""
	Checks The Command And Run Function

	Parameters:
		command : str
		arguments : str
		clientid : int
		accountid : int

	Returns:
		None
	"""
	if command in ['me', 'stats', 'score', 'rank', 'myself']:
		stats(accountid,clientid)

	elif command in ['list', 'l']:
		list(clientid)

	elif command in ['uniqeid', 'id', 'pb-id', 'pb' , 'accountid']:
		accountid_request(arguments, clientid, accountid)

def stats(ac_id,clientid):
	stats=mystats.get_stats_by_id(ac_id)
	reply="Score:"+str(stats["scores"])+"\nGames:"+str(stats["games"])+"\nKills:"+str(stats["kills"])+"\nDeaths:"+str(stats["deaths"])+"\nAvg.:"+str(stats["avg_score"])
	send(reply,clientid)

def list(clientid):
	"""Returns The List Of Players Clientid and index"""

	p = u'{0:^16}{1:^15}{2:^10}'
	seprator = '\n______________________________\n'

	list = p.format('Name', 'Client ID' , 'Player ID')+seprator
	session = _ba.get_foreground_host_session()

	for i in session.sessionplayers:
		list += p.format(i.getname(icon = False),
		i.inputdevice.client_id, i.id)+"\n"

	send(list, clientid)

def accountid_request(arguments, clientid, accountid):
	"""Returns The Account Id Of Players"""

	if arguments == [] or arguments == ['']:
		send(f"Your account id is {accountid} ", clientid)

	else:
		try:
			session = _ba.get_foreground_host_session()
			player = session.sessionplayers[int(arguments[0])]

			name = player.getname(full=True, icon=True)
			accountid = player.get_account_id()

			send(f" {name}'s account id is '{accountid}' ", clientid)
		except:
			return


# apis/serializers.py
from rest_framework import serializers
from todos import models

class TodoSerializer(serializers.ModelSerializer):
    title123 = serializers.CharField(source='title')
    class Meta:
        model = models.Todo
        fields = (
            'id',
            'title123',
            'description',
        )


import copy
from collections import Sequence
from math import floor

import matplotlib.pyplot as plt
import mmcv
import numpy as np
import torch
from mmcv.runner import obj_from_dict

from .. import datasets

def to_tensor(data):
    """Convert objects of various python types to :obj:`torch.Tensor`.

    Supported types are: :class:`numpy.ndarray`, :class:`torch.Tensor`,
    :class:`Sequence`, :class:`int` and :class:`float`.
    """
    if isinstance(data, torch.Tensor):
        return data
    elif isinstance(data, np.ndarray):
        return torch.from_numpy(data)
    elif isinstance(data, Sequence) and not mmcv.is_str(data):
        return torch.tensor(data)
    elif isinstance(data, int):
        return torch.LongTensor([data])
    elif isinstance(data, float):
        return torch.FloatTensor([data])
    else:
        raise TypeError('type {} cannot be converted to tensor.'.format(
            type(data)))

def random_scale(img_scales, mode='range'):
    """Randomly select a scale from a list of scales or scale ranges.

    Args:
        img_scales (list[tuple]): Image scale or scale range.
        mode (str): "range" or "value".

    Returns:
        tuple: Sampled image scale.
    """
    num_scales = len(img_scales)
    if num_scales == 1:  # fixed scale is specified
        img_scale = img_scales[0]
    elif num_scales == 2:  # randomly sample a scale
        if mode == 'range':
            img_scale_long = [max(s) for s in img_scales]
            img_scale_short = [min(s) for s in img_scales]
            long_edge = np.random.randint(
                min(img_scale_long),
                max(img_scale_long) + 1)
            short_edge = np.random.randint(
                min(img_scale_short),
                max(img_scale_short) + 1)
            img_scale = (long_edge, short_edge)
        elif mode == 'value':
            img_scale = img_scales[np.random.randint(num_scales)]
    else:
        if mode != 'value':
            raise ValueError(
                'Only "value" mode supports more than 2 image scales')
        img_scale = img_scales[np.random.randint(num_scales)]
    return img_scale

def show_ann(coco, img, ann_info):
    plt.imshow(mmcv.bgr2rgb(img))
    plt.axis('off')
    coco.showAnns(ann_info)
    plt.show()

def get_dataset(data_cfg):

    data_info = copy.deepcopy(data_cfg)
    data_info['ann_file'] = data_cfg['ann_file']
    data_info['proposal_file'] = None
    data_info['img_prefix'] = data_cfg['img_prefix']
    dset = obj_from_dict(data_info, datasets)
    return dset

def make_gaussian(size, sigma=10, center=None, d_type=np.float64):
    """ Make a square gaussian kernel.
    size: is the dimensions of the output gaussian
    sigma: is full-width-half-maximum, which
    can be thought of as an effective radius.
    """

    x = np.arange(0, size[1], 1, float)
    y = np.arange(0, size[0], 1, float)
    y = y[:, np.newaxis]

    if center is None:
        x0 = y0 = size[0] // 2
    else:
        x0 = center[0]
        y0 = center[1]

    return np.exp(-4 * np.log(2) * ((x - x0) ** 2 + (y - y0) ** 2) / sigma ** 2).astype(
        d_type
    )

def generate_heatmap(
    bbox_shape, kx_bbox, ky_bbox, heatmap_size=(64, 48), gaussian_size=5, gaussian_std=2
):
    """
    Args:
        bbox_shape (list): h, w of bbox
        kx_bbox, ky_bbox (int): keypoint coordination in bbox
        heatmap_size (tuple): default value is (64, 48)
        gaussian_size (int): gaussian size
        gaussian_std (int): gaussian std

    Returns:
        heatmap (np.darray): heatmap w/wo gaussian
        target_weight (np.darray): if heatmap has gaussian, 1 else 0
    """
    assert gaussian_size % 2 != 0

    h, w = bbox_shape
    assert 0 <= kx_bbox < w and 0 <= ky_bbox < h

    heatmap = np.zeros(heatmap_size)
    ratio_w = heatmap_size[1] / w
    ratio_h = heatmap_size[0] / h

    resized_kx_bbox = floor(kx_bbox * ratio_w)
    resized_ky_bbox = floor(ky_bbox * ratio_h)

    # Add temp pad for gaussian addition
    pad_size = gaussian_size // 2
    heatmap_pad = np.pad(heatmap, (pad_size, pad_size), mode="constant")

    gaussian = make_gaussian([gaussian_size, gaussian_size], gaussian_std)

    # heatmap coords adjusting gaussian
    gx1 = resized_kx_bbox
    gy1 = resized_ky_bbox

    gx2 = resized_kx_bbox + gaussian_size
    gy2 = resized_ky_bbox + gaussian_size

    heatmap_pad[gy1:gy2, gx1:gx2] = gaussian
    heatmap = heatmap_pad[pad_size:-pad_size, pad_size:-pad_size]
    target_weight = np.ones([1, 1])
    return heatmap, target_weight

def add_boundary_noise(img_shape, x1, y1, x2, y2, kx_bbox=None, ky_bbox=None):
    """Add noise when cropping bbox

    Args:
        img_shape (list): [h, w]
        x1, y1, x2, y2 (int): bbox coordination
        kx_bbox, ky_bbox (int): keypoint coordination, default is None

    Returns:
        new_x1, new_x2, new_y1, new_y2 (int): new bbox coordination
    """
    img_h, img_w = img_shape

    randint_w = sorted((0, (x2 - x1) // 3 + 1))
    randint_h = sorted((0, (y2 - y1) // 3 + 1))

    dx1 = min(x1, np.random.randint(*randint_w))
    dx2 = min(img_w - x2, np.random.randint(*randint_w))
    dy1 = min(y1, np.random.randint(*randint_h))
    dy2 = min(img_h - y2, np.random.randint(*randint_h))

    new_x1 = x1 - dx1
    new_x2 = x2 + dx2
    new_y1 = y1 - dy1
    new_y2 = y2 + dy2

    if kx_bbox is not None and ky_bbox is not None:
        new_kx_bbox = kx_bbox + dx1
        new_ky_bbox = ky_bbox + dy1
        return new_x1, new_x2, new_y1, new_y2, new_kx_bbox, new_ky_bbox
    return new_x1, new_x2, new_y1, new_y2

def bb_intersection_over_union(boxA, boxB):
    # determine the (x, y)-coordinates of the intersection rectangle
    xA = max(boxA[0], boxB[0])
    yA = max(boxA[1], boxB[1])
    xB = min(boxA[2], boxB[2])
    yB = min(boxA[3], boxB[3])

    # compute the area of intersection rectangle
    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    # compute the area of both the prediction and ground-truth
    # rectangles
    boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
    boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)

    # compute the intersection over union by taking the intersection
    # area and dividing it by the sum of prediction + ground-truth
    # areas - the interesection area
    iou = interArea / float(boxAArea + boxBArea - interArea)

    # return the intersection over union value
    return iou


import numpy

def do_tarspose_flattern(arr):
    print(arr.transpose(), arr.flatten(), sep='\n')

if __name__ == "__main__":
    """
    You are given a NXM integer array matrix with space separated elements ( N= rows and  M= columns).
    Your task is to print the transpose and flatten results.
    """
    N, M = list(map(int, input().strip().split()))
    do_tarspose_flattern(numpy.array([list(map(int, input().strip().split())) for _ in range(N)]))


## QUESTION
"""
Given an array Arr of size N, swap the Kth element from beginning with Kth element from end.

Example 1:

Input:
N = 8, K = 3
Arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output: 1 2 6 4 5 3 7 8
Explanation: Kth element from beginning is
3 and from end is 6.
Example 2:

Input:
N = 5, K = 2
Arr[] = {5, 3, 6, 1, 2}
Output: 5 1 6 3 2
Explanation: Kth element from beginning is
3 and from end is 1.
Your Task:
You don't need to read input or print anything. Your task is to complete the function swapKth() which takes the array of integers arr, n and k as parameters and returns void. You have to modify the array itself.

Expected Time Complexity: O(1)
Expected Auxiliary Space: O(1)
"""

## SOLUTION:

#User function Template for python3
class Solution:

	def swapKth(self,arr, n, k):
		# code here

		start1=k+1
		end1=n-k

		temp=arr[k-1]
		arr[k-1]=arr[n-k]
		arr[n-k]=temp

		return arr

#{
#  Driver Code Starts
#Initial Template for Python 3

if __name__ == '__main__':
    tc = int(input())
    while tc > 0:
        n, k = list(map(int, input().strip().split()))
        arr = list(map(int, input().strip().split()))
        ob = Solution()
        ob.swapKth(arr, n, k)
        for x in arr:
            print(x, end=" ")
        print()
        tc -= 1

# } Driver Code Ends


from staphan_bolzmann_base import *

def n_ary_search(depth_left, left, right, n_arity, ns) -> float:
	if depth_left == 0:
		return (left + right) / 2

	step = (right - left) / n_arity
	offset = step * ns

	best_pow, mse_from_pow = research_graphs_pow(left, right, n_arity, False)

	return n_ary_search(depth_left - 1, best_pow - offset, best_pow + offset, n_arity, ns)

values = []
for recursion_limit in range(1, 16):
	value = n_ary_search(recursion_limit, 2, 10, 100, 30)

	values.append((recursion_limit, value))

	print(value)

print(values)

if __name__ == '__main__':
	matplotlib.rcParams.update({'font.size': 16})

	plt.title("N-ary search Dynamic")

	plt.plot(*zip(*values))

	plt.xlabel("Iteration's Index")
	plt.ylabel("MSE")

	plt.show()


"""
应用模块
"""

from fet import _Flask as Flask
from celery import Celery

# pylint: disable=all

celery = Celery(
    __name__,
    broker='redis://localhost:6379/0',
    backend='redis://localhost:6379/0',
)

def create_app(default='default'):
    """ 创建应用"""
    app = Flask(
        __name__,
    )

    configure_app(app, config_file=default)
    configure_celery_app(app)
    configure_request_hook(app)
    configure_extensions(app)
    configure_blueprints(app)
    return app

def configure_app(app, config_dir="fresh.config", config_file=None):
    """ 基础配置"""
    config_files = ['default']
    if config_file and config_file not in config_files:
        config_files.append(config_file)

    for config_file in config_files:
        if config_file.endswith('.py'):
            config_file = config_file[:-3]

        config_path = config_dir + '.' + config_file
        app.config.from_object(config_path)

def configure_celery_app(app):
    """ 配置celery"""
    celery.conf.update(app.config)

def configure_blueprints(app):
    """ 配置蓝图"""
    from fresh.api import bp as api_bp
    from fresh.views.home import bp as home_bp
    app.register_blueprint(api_bp)
    app.register_blueprint(home_bp)

def configure_extensions(app):
    """ 配置扩展"""
    from fresh.extends import (
        api, db, login_manager, mail, redis_store, cryptor
    )
    api.init_app(app)
    db.init_app(app)
    login_manager.init_app(app)
    mail.init_app(app)
    redis_store.init_app(app)
    cryptor.init_app(app)

def configure_request_hook(app):
    """ 请求钩子"""

    @app.before_request
    def before_request():
        """ 请求前钩子"""
        pass

    @app.after_request
    def after_request(response):
        """ 请求后钩子"""
        response.headers['Access-Control-Allow-Origin'] = '*'
        response.headers['Access-Control-Allow-Methods'] = 'GET,POST,PUT,OPTIONS'
        response.headers['Access-Control-Allow-Headers'] = 'x-requested-with,content-type,token'
        return response


from dsa import *

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        subsets = []

        def rec(nums, i, subset, subsets):
            if i == len(nums):
                subsets.append(subset[:])
                return

            rec(nums, i + 1, subset + [nums[i]], subsets)
            rec(nums, i + 1, subset, subsets)

        rec(nums, 0, [], subsets)
        return subsets


N, K = map(int, input().split())
arr = [0 for _ in range(1000001)]
left, right = 10000, 0
for _ in range(N):
    g, x = map(int, input().split())
    arr[x] = g
    left = min(left, x)
    right = max(right, x)

end = left
now, ans = 0, 0
for i in range(left, right+1):
    while end < right + 1 and end - i <= K * 2:
        if not arr[end]:
            end += 1
            continue
        now += arr[end]
        end += 1
    ans = max(ans, now)
    now -= arr[i]
    if end >= right: break
print(ans)


from typing import Optional

from Token import Token
from TokenType import TokenType

class Scanner():
    KEYWORDS = {
        "and": TokenType.AND,
        "class": TokenType.CLASS,
        "else": TokenType.ELSE,
        "false": TokenType.FALSE,
        "fun": TokenType.FUN,
        "for": TokenType.FOR,
        "if": TokenType.IF,
        "nil": TokenType.NIL,
        "or": TokenType.OR,
        "print": TokenType.PRINT,
        "return": TokenType.RETURN,
        "super": TokenType.SUPER,
        "this": TokenType.THIS,
        "true": TokenType.TRUE,
        "var": TokenType.VAR,
        "while": TokenType.WHILE,
    }

    def __init__(self, source: str, lox):
        self.lox = lox
        self.source = source
        self.tokens = []
        self.start = 0
        self.current = 0
        self.line = 1

    def scanTokens(self) -> list[Token]:
        while not self.isAtEnd():
            # We are at the beginning of the next lexeme
            self.start = self.current
            self.scanToken()

        self.tokens.append(Token(TokenType.EOF, "", None, self.line))
        return self.tokens

    def scanToken(self) -> None:
        c = self.advance()
        if c == "(":
            self.addToken(TokenType.LEFT_PAREN)
        elif c == ")":
            self.addToken(TokenType.RIGHT_PAREN)
        elif c == "{":
            self.addToken(TokenType.LEFT_BRACE)
        elif c == "}":
            self.addToken(TokenType.RIGHT_BRACE)
        elif c == ",":
            self.addToken(TokenType.COMMA)
        elif c == ".":
            self.addToken(TokenType.DOT)
        elif c == "-":
            self.addToken(TokenType.MINUS)
        elif c == "+":
            self.addToken(TokenType.PLUS)
        elif c == ";":
            self.addToken(TokenType.SEMICOLON)
        elif c == "*":
            self.addToken(TokenType.STAR)

        # operators
        elif c == "!":
            self.addToken(TokenType.BANG_EQUAL if self.match("=") else TokenType.BANG)
        elif c == "=":
            self.addToken(TokenType.EQUAL_EQUAL if self.match("=") else TokenType.EQUAL)
        elif c == "<":
            self.addToken(TokenType.LESS_EQUAL if self.match("=") else TokenType.LESS)
        elif c == ">":
            self.addToken(TokenType.GREATER_EQUAL if self.match("=") else TokenType.GREATER)

        # comments
        elif c == "/":
            if self.match("/"):
                # A comment goes until the end of the line.
                while self.peek() != "/n" and not self.isAtEnd():
                    self.advance()
            else:
                self.addToken(TokenType.SLASH)

        # whitespaces
        elif c == " ":
            pass
        elif c == "\r":
            pass
        elif c == "\t":
            # Ignore whitespace
            pass
        elif c == "\n":
            self.line += 1

        # string literals
        elif c == '"':
            self.string()

        else:
            # number literals
            if self.isDigit(c):
                self.number()
            # reserved number and identifier
            elif self.isAlpha(c):
                self.identifier()
            else:
                self.lox.error(self.line, "Unexpected character.")

    def identifier(self) -> None:
        while self.isAlphaNumeric(self.peek()):
            self.advance()

        text = self.source[self.start:self.current]
        type = self.KEYWORDS.get(text)
        if type is None:
            type = TokenType.IDENTIFIER

        self.addToken(type)

    def string(self) -> None:
        while self.peek() != '"' and not self.isAtEnd():
            if self.peek() == "\n":
                self.line += 1
            self.advance()

        if self.isAtEnd():
            self.lox.error(self.line, "Unterminated string.")

        # The closing ".
        self.advance()

        # Trim the surrounding quotes.
        value = self.source[self.start + 1: self.current - 1]
        self.addTokenLiteral(TokenType.STRING, value)

    def number(self) -> None:
        while self.isDigit(self.peek()):
            self.advance()

        # Look for fractional part
        if self.peek() == "." and self.isDigit(self.peekNext()):
            # Consume the "."
            self.advance()

            while self.isDigit(self.peek()):
                self.advance()

        value = float(self.source[self.start:self.current])
        self.addTokenLiteral(TokenType.NUMBER, value)

    def match(self, expected: str) -> bool:
        if self.isAtEnd():
            return False
        if self.source[self.current] != expected:
            return False

        self.current += 1
        return True

    def peek(self) -> str:
        if self.isAtEnd():
            return ""
        current_char = self.source[self.current]
        return current_char

    def peekNext(self) -> str:
        if self.current + 1 >= len(self.source):
            return ""
        return self.source[self.current + 1]

    def isAlpha(self, c:str) -> bool:
        return (c >= "a" and c <= "z") or (c >= "A" and c <= "Z") or c == "_"

    def isAlphaNumeric(self, c: str) -> bool:
        return self.isAlpha(c) or self.isDigit(c)

    def isDigit(self, c: str) -> bool:
        return c >= "0" and c <= "9"

    def isAtEnd(self) -> bool:
        return self.current >= len(self.source)

    def advance(self) -> str:
        current_char = self.source[self.current]
        self.current += 1
        return current_char

    def addToken(self, type: str) -> None:
        self.addTokenLiteral(type, None)

    def addTokenLiteral(self, type: str, literal: Optional[str]) -> None:
        text = self.source[self.start:self.current]
        self.tokens.append(Token(type, text, literal, self.line))


import os
import pandas as pd
import matplotlib.pyplot as plt

from transformers import GPT2TokenizerFast

from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import RecursiveCharacterTextSplitter

from langchain.vectorstores import FAISS
from langchain.chains.question_answering import load_qa_chain
from langchain.llms import HuggingFaceHub
from langchain.chains import ConversationalRetrievalChain
from langchain.chains import RetrievalQA

from langchain.embeddings.huggingface import HuggingFaceEmbeddings
from llama_index import LangchainEmbedding

import textract

from dotenv import load_dotenv
import gradio as gr

class PDFQA():

    def __init__(self) -> None:
        super().__init__()

        os.environ['HUGGINGFACEHUB_API_TOKEN'] = os.getenv('HUGGINGFACEHUB_API_TOKEN')

        self.source_folder = './data/'
        self.output_folder = './output/'

    def loading_pdf():
        return 'Loading...'

    def pdf_changes(self, pdf_doc, repo_id):
        # # Simple method - Split by pages
        # loader = PyPDFLoader(pdf_doc.name)
        # pages = loader.load_and_split()

        # # SKIP TO STEP 2 IF YOU'RE USING THIS METHOD
        # chunks = pages

        if pdf_doc is None:
            return

        doc = textract.process(pdf_doc.name)

        # Step 2: Save to .txt and reopen (helps prevent issues)
        with open(self.output_folder+'test.txt', 'w') as f:
            f.write(doc.decode('utf-8'))

        with open(self.output_folder+'test.txt', 'r') as f:
            text = f.read()

        # Step 3: Create function to count tokens
        tokenizer = GPT2TokenizerFast.from_pretrained('gpt2')

        def count_tokens(text: str) -> int:
            return len(tokenizer.encode(text))

        # Step 4: Split text into chunks
        text_splitter = RecursiveCharacterTextSplitter(
            # Set a really small chunk size, just to show.
            chunk_size = 512,
            chunk_overlap  = 24,
            length_function = count_tokens,
        )

        chunks = text_splitter.create_documents([text])

        embeddings = HuggingFaceEmbeddings()
        # embed_model = LangchainEmbedding(embeddings)

        # Create vector database
        db = FAISS.from_documents(chunks, embeddings)
        retriever = db.as_retriever()

        flan_ul2 = HuggingFaceHub(repo_id=repo_id, model_kwargs={'temperature': 0.1})
        # chain = load_qa_chain(flan_ul2, chain_type='stuff')
        self.chain = RetrievalQA.from_chain_type(llm=flan_ul2, chain_type='stuff', retriever=retriever, return_source_documents=True)
        return 'Ready'

    def add_text(self, history, text):
        history = history + [(text, None)]
        return history, ''

    def bot(self, history):
        response = self.infer(history[-1][0])
        history[-1][1] = response['result']
        return history

    def infer(self, question):

        query = question
        result = self.chain({'query': query})

        return result

if __name__ == '__main__':
    load_dotenv()

    pdf_qa = PDFQA()

    # query = 'What is the copay for Diagnostic test?'
    # query = 'what is my out of pocket limit?'
    # query = 'what is the radiology cost for having a baby'
    # query = how much will be my radiology cost for new born baby?

    css='''
    #col-container {max-width: 700px; margin-left: auto; margin-right: auto;}
    '''

    title = '''

Upload a PDF document and start asking questions from the document

Upload a pdf document from your computer, click the 'Process PDF' button,

        once ready (check for the Ready status), you can start asking questions about the uploaded pdf document

    '''

    with gr.Blocks(css=css) as demo:
        with gr.Column(elem_id='col-container'):
            gr.HTML(title)

            with gr.Column():
                pdf_doc = gr.File(label='Load a pdf', file_types=['.pdf'], type='file')
                repo_id = gr.Dropdown(label='LLM', choices=['google/flan-t5-large', 'bigscience/mt0-large', 'microsoft/prophetnet-large-uncased', 'bigscience/T0_3B'], value='google/flan-t5-large')
                with gr.Row():
                    langchain_status = gr.Textbox(label='Status', placeholder='', interactive=False)
                    load_pdf = gr.Button('Process PDF')

            chatbot = gr.Chatbot([], elem_id='chatbot').style(height=350)
            question = gr.Textbox(label='Question', placeholder='Ask your question and hit enter')
            submit_btn = gr.Button('Send message')

        repo_id.change(pdf_qa.pdf_changes, inputs=[pdf_doc, repo_id], outputs=[langchain_status], queue=False)
        load_pdf.click(pdf_qa.pdf_changes, inputs=[pdf_doc, repo_id], outputs=[langchain_status], queue=False)
        question.submit(pdf_qa.add_text, [chatbot, question], [chatbot, question]).then(
            pdf_qa.bot, chatbot, chatbot
        )
        submit_btn.click(pdf_qa.add_text, [chatbot, question], [chatbot, question]).then(
            pdf_qa.bot, chatbot, chatbot
        )

    demo.launch()


import os
import logging
import numpy as np
import random
import paddle
from tqdm import tqdm
from models.simple_cnn import SimpleCNN
from models.mini_xception import MiniXception
from data.dataset import load_imdb, split_imdb_data
from data.dataset import FaceDataset
from visualdl import LogWriter
from argparse import ArgumentParser
from paddle.io import DataLoader
from paddle import distributed as dist
from config.confg import parse_args

logging.basicConfig(format="%(asctime)s - %(levelname)s - %(message)s", level=logging.INFO)

def train():
    # Load the dataset
    logging.info(f"Loading the dataset ...")
    data = load_imdb(os.path.join(data_args.imdb_dir, 'imdb.mat'))
    train_set, val_set = split_imdb_data(data, args.validation_split)
    train_set = FaceDataset(train_set, img_path_prefix=data_args.imdb_dir, grayscale=data_args.grayscale,
                            do_transform=True,
                            do_random_crop=data_args.do_rand_crop,
                            translation_factor=data_args.translation_factor,
                            vertical_flip_probability=data_args.vertical_flip_probability,
                            read_img_at_once=data_args.read_img_at_once,
                            img_size=data_args.img_size,
                            )
    val_set = FaceDataset(val_set, img_path_prefix=data_args.imdb_dir, grayscale=data_args.grayscale,
                          read_img_at_once=data_args.read_img_at_once,
                          img_size=data_args.img_size,
                          )
    logging.info(
        f"The numbers of samples of training and validation sets are {train_set.__len__()} and {val_set.__len__()}.")
    train_loader = DataLoader(train_set, batch_size=args.batch_size, num_workers=args.num_workers, shuffle=True)
    val_loader = DataLoader(val_set, batch_size=args.batch_size, num_workers=args.num_workers)

    # For multi-GPUs training
    dist.init_parallel_env()

    # Build the model, optimizer and loss function
    if args.model_name == "MiniXception":
        model = MiniXception(args.n_classes, args.in_channels)
    else:
        model = SimpleCNN(args.n_classes, args.in_channels)
    scheduler = paddle.optimizer.lr.ReduceOnPlateau(learning_rate=0.001, factor=0.5, patience=50, verbose=True,
                                                    epsilon=1e-6)
    optimizer = paddle.optimizer.Adam(learning_rate=scheduler, parameters=model.parameters())
    loss_fn = paddle.nn.CrossEntropyLoss()

    # Restore parameters
    if args.restore:
        model = restore_params(model, args.model_state_dict)
        optimizer = restore_params(optimizer, args.opt_state_dict)
        epoch = int(args.model_state_dict.split('-')[1]) + 1
    else:
        epoch = 1

    # For multi-GPUs training
    model = paddle.DataParallel(model)

    # For visualDL
    train_logger = LogWriter(logdir=os.path.join(args.logdir, 'train'))
    val_logger = LogWriter(logdir=os.path.join(args.logdir, 'val'))

    # Start training
    saved_params = []
    max_val_acc = 0.95
    for epoch in range(epoch, args.epochs + 1):
        logging.info("=" * 50 + f"Epoch {epoch}" + "=" * 50)

        # Training
        n_samples, sum_acc, sum_loss = 0, 0., 0.
        model.train()
        with tqdm(train_loader) as t:
            for step, batch in enumerate(t, 1):
                inputs, labels = batch[0], batch[1]
                pred = model(inputs)
                loss = loss_fn(pred, labels)
                acc = paddle.metric.accuracy(pred, labels.unsqueeze(1))
                n = len(inputs)
                sum_loss += loss.item() * n
                sum_acc += acc.item() * n
                n_samples += n
                loss.backward()
                optimizer.step()
                optimizer.clear_grad()
                t.set_postfix(train_loss=loss.item(), train_acc=acc.item())

        loss, acc = sum_loss / n_samples, sum_acc / n_samples
        train_logger.add_scalar('loss', loss, epoch)
        train_logger.add_scalar('acc', acc, epoch)
        train_logger.add_scalar('lr', optimizer.get_lr(), epoch)
        logging.info(f"Epoch {epoch}, train loss {loss}, train acc {acc}, lr {optimizer.get_lr()}.")

        # Validation
        n_samples, sum_acc, sum_loss = 0, 0., 0.
        model.eval()
        for batch in tqdm(val_loader()):
            inputs, labels = batch[0], batch[1]
            pred = model(inputs)
            loss = loss_fn(pred, labels)
            acc = paddle.metric.accuracy(pred, labels.unsqueeze(1))
            n = len(inputs)
            sum_loss += loss.item() * n
            sum_acc += acc.item() * n
            n_samples += n
        loss, acc = sum_loss / n_samples, sum_acc / n_samples
        val_logger.add_scalar('loss', loss, epoch)
        val_logger.add_scalar('acc', acc, epoch)
        logging.info(f"Epoch {epoch}, val loss {loss}, val acc {acc}")
        scheduler.step(loss, epoch)

        # Save the model state dict
        if acc > max_val_acc or epoch >= args.epochs:
            logging.info(f"Epoch {epoch}, Output model with val acc {acc} to {args.model_dir}")
            model_path = os.path.join(args.model_dir, f"{args.model_name}-{epoch}-{acc}.params")
            opt_path = os.path.join(args.model_dir, f"{args.model_name}-{epoch}-{acc}.opt")
            paddle.save(model.state_dict(), model_path)
            paddle.save(optimizer.state_dict(), opt_path)
            if args.just_keep_the_best:     # Just keep the best model, remove the others
                for p in saved_params:
                    os.remove(p)
            saved_params = [model_path, opt_path]
            max_val_acc = acc
            if acc >= 0.96:     # Stop training when the acc reach 0.96
                logging.info("Finished training.")
                break
    logging.info("Finished training.")

def restore_params(model, model_path):
    """Restore parameters of the model.
    Args:
        model: paddle.nn.Layer, the model to be restored.
        model_path: The file path of the parameters.
    """
    logging.info(f"Restoring parameters from {model_path}")
    model_state_dict = paddle.load(model_path)
    model.set_state_dict(model_state_dict)
    return model

def set_seed(seed: int):
    """Set the random seed.
    """
    random.seed(seed)
    np.random.seed(seed)
    paddle.seed(seed)

if __name__ == '__main__':
    parser = ArgumentParser("Training parameters")
    parser.add_argument('--conf_path', '-c', type=str, default='config/conf.yaml', help='Path to the config.')
    parser.add_argument('--model_name', '-m', type=str, choices=['MiniXception', 'SimpleCNN'],
                        help='Choose a model to train.')

    args = parse_args(parser)   # parse arguments

    data_args = args.dataset    # arguments of the dataset

    set_seed(args.seed)     # set the random seed

    train()     # begin training


import sys

sys.stdin.reconfigure(errors='ignore')

instances_qty = int(input())
for instance in range(1, instances_qty + 1):
    original_message = input()
    team_1_message = input()
    team_2_message = input()

    length_max = max([len(original_message), len(team_1_message), len(team_2_message)])
    reformat_string = '{:<' + str(length_max) + '}'
    original_message = reformat_string.format(original_message)
    team_1_message = reformat_string.format(team_1_message)
    team_2_message = reformat_string.format(team_2_message)

    team_1_score = team_2_score = 0
    first_right = 0
    for index, character in enumerate(original_message):
        team_1_right = team_1_message[index] == character
        team_2_right = team_2_message[index] == character
        team_1_score += int(team_1_right)
        team_2_score += int(team_2_right)
        if not first_right:
            if team_1_right and not team_2_right:
                first_right = 1
            if team_2_right and not team_1_right:
                first_right = 2
    print('Instancia {}'.format(instance))
    if team_1_score > team_2_score:
        print('time 1')
    elif team_2_score > team_1_score:
        print('time 2')
    else:
        if first_right == 1:
            print('time 1')
        elif first_right == 2:
            print('time 2')
        else:
            print('empate')
    print()


from yapsy.IPlugin import IPlugin
import wolframalpha
import yaml

keys_file = open("friday/plugins/KEYS")
keys = yaml.load(keys_file)
keys_file.close()

class Wolfram(IPlugin):
    def can_perform(self, friday, request):
        return 'result' in request and 'resolvedQuery' in request['result']\
                and 'action' in request['result'] and request['result']['action'] == 'wisdom.unknown'
        # result = request['result']  # Assumes we're using gTTS
        # # Get the text that is supposed to be spoken aloud
        # reply = result['fulfillment']['speech']
        # # Get what the service thought you said
        # question = result['resolvedQuery']

    def perform(self, friday, request):
        question = request['result']['resolvedQuery']
        client = wolframalpha.Client(keys['WOLFRAM'])
        res = client.query(question)
        answer = str(list(res))
        """if len(res):
            results = list(res.results)
            if len(results):
                answer = results[0].text[0]
            else:
                answer = ' '.join([each_answer.subpods[0].text for each_answer in res.pods
                                   if each_answer.subpods[0].text])
        else:
            # answer = "Sorry, Wolfram doesn't know the answer."
            answer = ""
        """
        """# Replace some of its notation so it's more easily read.
        answer = answer.replace('\n', '. ').replace('~~', ' or about ')
        # Get the result to a computation and don't bother reading the original question.
        if '=' in answer:
            answer = answer[answer.index('=') + 1:].strip()
        """
        return answer

#
# def wolfram_query(question):
#     # Every service should have a general set of requirements under which
#     # it is activated, this would be one of the ones that Wolfram Alpha
#     # uses, it does have others as well. Consider having a single method
#     # in the plugin system that returns a boolean determining whether
#     # a plugin should be activated.
#     if question:
#
#
# def wolfram_query_old(question):
#     import wolframalpha
#     # Every service should have a general set of requirements under which
#     # it is activated, this would be one of the ones that Wolfram Alpha
#     # uses, it does have others as well. Consider having a single method
#     # in the plugin system that returns a boolean determining whether
#     # a plugin should be activated.
#     if question.lower().startswith('wolfram'):
#         question = question[8:]
#     client = wolframalpha.Client(user_info.WOLFRAM_KEY)
#     res = client.query(question)
#     try:
#         return next(res.results).text  # This really needs to be changed.
#         # I shouldn't have to rely upon error catching for my flow control.
#     except StopIteration:
#         pass
#     try:
#         answer = '   '.join([each_answer.text for each_answer in res.pods if each_answer])
#     except TypeError:
#         answer = None
#     if not answer:
#         answer = "Sorry, Wolfram doesn't know the answer."
#
#     # Replace some of its notation so it's more easily read.
#     answer = answer.replace('\n', '; ').replace('~~', ' or about ')
#     # Get the result to a computation and don't bother reading the original question.
#     if '=' in answer:
#         answer = answer[answer.index('=')+1:]
#     return [answer, None]  # Follows answer format of [text, action]
#


"""This file ensures that there is only one instance of the program running,
   and shows the currently running instance if there is"""

from socket import socket
from thread import start_new_thread
import atexit
from excepthandler import exception_managed

class PortInUse(Exception):
	pass

def set_callback(new_callback):
	global callback
	callback = new_callback

callback = None

def atexit():
	global port
	sock = socket()
	sock.connect(('127.0.0.1', port))
	if sock.recv(9) == 'harmonize':
		sock.send('q')
	sock.close()

port = 26505
def running():
	global port

	sock = socket()
	if sock.connect_ex(('127.0.0.1', port)) == 0:
		if sock.recv(9) == 'harmonize':
			sock.send('c')
			sock.close()
			return True
		else:
			raise PortInUse()
	else:
		@exception_managed
		def start_server(port):
			global callback
			server_sock = socket()
			server_sock.bind(('127.0.0.1', port))
			server_sock.listen(2)
			while True:
				request, addr = server_sock.accept()
				request.send('harmonize')
				res = request.recv(1)
				request.close()
				if res == 'c' and callback:
					callback()
				elif res == 'q':
					break
			server_sock.close()

		start_new_thread(start_server, (port,))
		return False


import gi
import parquet
import string

gi.require_version("Gtk", "3.0")
from gi.repository import Gtk

class AlertDialog(Gtk.Dialog):
  def __init__(self, parent, title="", description=""):
    super().__init__(title=title, transient_for=parent, flags=0)
    self.add_buttons(
      Gtk.STOCK_OK, Gtk.ResponseType.OK
    )
    label = Gtk.Label(label=description)
    box = self.get_content_area()
    box.add(label)
    self.show_all()

class PriceCatcher(Gtk.Window):

  locations                 = None
  group                     = None
  category                  = None
  state                     = None
  district                  = None
  premise_type              = None
  items                     = None
  premises                  = None
  hbox_search_combobox      = None
  hbox_menu                 = None # wrap hbox_search_combobox and search_button
  vbox_premise_list         = None

  def __init__(self):
    super().__init__(title="OpendDOSM - PriceCatcher")

    self.set_border_width(10)

    item_groups_store = Gtk.ListStore(int, str)
    item_groups = ["SEMUA KUMPULAN", *parquet.get_item_groups()]
    for i, v in enumerate(item_groups):
      item_groups_store.append([i, v])
    item_groups_combo = Gtk.ComboBox.new_with_model_and_entry(item_groups_store)
    item_groups_combo.connect("changed", self.on_group_combo_changed)
    item_groups_combo.set_entry_text_column(1)
    item_groups_combo.set_active(0)

    item_categories_store = Gtk.ListStore(int, str)
    item_categories = ["SEMUA KATEGORI", *parquet.get_item_categories()]
    for i, v in enumerate(item_categories):
      item_categories_store.append([i, v])
    item_categories_combo = Gtk.ComboBox.new_with_model_and_entry(item_categories_store)
    item_categories_combo.connect("changed", self.on_category_combo_changed)
    item_categories_combo.set_entry_text_column(1)
    item_categories_combo.set_active(0)

    self.locations = parquet.get_premise_location()

    states_store = Gtk.ListStore(int, str)
    states = ["SEMUA NEGERI", *self.locations.keys()]
    for i, v in enumerate(states):
      states_store.append([i, v])
    states_combo = Gtk.ComboBox.new_with_model_and_entry(states_store)
    states_combo.connect("changed", self.on_state_combo_changed)
    states_combo.set_entry_text_column(1)
    states_combo.set_active(0)

    wrapper = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)  # wrap menu_grid and vbox_premise_list

    self.hbox_menu = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)

    # all combobox
    self.hbox_search_combobox = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
    self.hbox_search_combobox.pack_start(item_groups_combo, False, False, 0)
    self.hbox_search_combobox.pack_start(item_categories_combo, False, False, 0)
    self.hbox_search_combobox.pack_start(states_combo, False, False, 0)
    self.hbox_menu.pack_start(self.hbox_search_combobox, False, False, 0)

    # search button
    search_button = Gtk.Button.new_with_label("Papar Data")
    search_button.connect("clicked", self.show_price_list)
    self.hbox_menu.pack_end(search_button, False, False, 0)  # wrap hbox_search_combobox and search_button

    menu_grid = Gtk.Grid()
    menu_grid.add(self.hbox_menu)

    wrapper.add(menu_grid)

    self.vbox_premise_list = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)

    listbox = Gtk.ListBox()
    listbox.set_selection_mode(Gtk.SelectionMode.NONE)
    label = Gtk.Label(label="NO DATA HERE", xalign=0)
    label.set_halign(Gtk.Align.CENTER)
    listbox.add(label)
    self.vbox_premise_list.add(listbox)

    scrolled_window = Gtk.ScrolledWindow()
    scrolled_window.add(self.vbox_premise_list)

    wrapper.pack_start(scrolled_window, True, True, 0)

    self.add(wrapper)
    self.maximize()

  def hbox_search_combobox_append_district_combobox(self, state = None):
    if (state in self.locations):
      self.state = state
      self.district = None
      self.premise_type = None
      districts = ["SEMUA DAERAH", *self.locations[self.state].keys()]
      districts_store = Gtk.ListStore(int, str)
      for i, v in enumerate(districts):
        districts_store.append([i, v])
      districts_combo = Gtk.ComboBox.new_with_model_and_entry(districts_store)
      districts_combo.connect("changed", self.on_district_combo_changed)
      districts_combo.set_entry_text_column(1)
      districts_combo.set_active(0)
      self.hbox_search_combobox.pack_start(districts_combo, False, False, 0)
      districts_combo.show()
    else:
      self.state = None
      self.district = None
      self.premise_type = None

  def hbox_search_combobox_append_premise_type_combobox(self, district = None):
    if (district in self.locations[self.state]):
      self.district = district
      self.premise_type = None
      premises_types = ["SEMUA PREMIS", *self.locations[self.state][self.district]]
      premises_types_store = Gtk.ListStore(int, str)
      for i, v in enumerate(premises_types):
        premises_types_store.append([i, v])
      premises_types_combo = Gtk.ComboBox.new_with_model_and_entry(premises_types_store)
      premises_types_combo.connect("changed", self.on_premise_type_combo_changed)
      premises_types_combo.set_entry_text_column(1)
      premises_types_combo.set_active(0)
      self.hbox_search_combobox.pack_start(premises_types_combo, False, False, 0)
      premises_types_combo.show()
    else:
      self.district = None
      self.premise_type = None

  def show_price_list(self, button):
    if (self.group == None and self.category == None):
      dialog = AlertDialog(self, title="Peringatan!", description="Sila pilih kategori atau kumpulan barangan")
      response = dialog.run()
      # if response == Gtk.ResponseType.OK:
        # print("The OK button was clicked")
      # elif response == Gtk.ResponseType.CANCEL:
        # print("The Cancel button was clicked")
      dialog.destroy()
      return

    self.items = dict()
    item_codes = list()
    for item in parquet.search_items(item_category=self.category, item_group=self.group).itertuples():
      self.items[item[1]] = item
      item_codes.append(item[1])
    item_codes = tuple(item_codes)

    self.premises = dict()
    premises_codes = list()
    for premise in parquet.search_premises(state=self.state, district=self.district, premise_type=self.premise_type).itertuples():
      self.premises[premise[1]] = premise
      premises_codes.append(premise[1])
    premises_codes = tuple(premises_codes)

    search_result = parquet.search_pricecatcher(premise_codes = premises_codes, item_codes = item_codes)
    price_list = parquet.group_price_list_by_premise_item(search_result)
    self.vbox_premise_list_fill(price_list)

  def vbox_premise_list_fill(self, price_list):
    while (len(self.vbox_premise_list.get_children()) > 0):
      self.vbox_premise_list.remove(self.vbox_premise_list.get_children()[len(self.vbox_premise_list.get_children()) - 1])
    if len(price_list) == 0:
      listbox = Gtk.ListBox()
      listbox.show()
      listbox.set_selection_mode(Gtk.SelectionMode.NONE)
      label = Gtk.Label(label="NO DATA HERE", xalign=0)
      label.show()
      label.set_halign(Gtk.Align.CENTER)
      listbox.add(label)
      self.vbox_premise_list.add(listbox)
      return

    for premise in price_list:
      listbox = Gtk.ListBox()
      listbox.show()
      listbox.set_selection_mode(Gtk.SelectionMode.NONE)

      vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=6)
      vbox.show()

      premise_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=6)
      premise_box.show()

      label_premise = Gtk.Label(xalign=0)
      label_premise.set_markup(f'{str(self.premises[premise][2]).strip()}')
      label_premise.show()
      premise_box.add(label_premise)

      label_address = Gtk.Label(xalign=0)
      label_address.set_markup(f'{" ".join(str(self.premises[premise][3]).split())}')
      label_address.show()
      premise_box.add(label_address)

      label_state = Gtk.Label(label=str(self.premises[premise][5]).strip(), xalign=0)
      label_state.show()
      premise_box.pack_end(label_state, False, False, 0)

      label_district = Gtk.Label(label=str(self.premises[premise][6]).strip(), xalign=0)
      label_district.show()
      premise_box.pack_end(label_district, False, False, 0)

      label_premise_type = Gtk.Label(label=str(self.premises[premise][4]).strip(), xalign=0)
      label_premise_type.show()
      premise_box.pack_end(label_premise_type, False, False, 0)

      vbox.add(premise_box)

      listbox.add(vbox)
      for item in price_list[premise]:
        text_lines = list()
        for i in price_list[premise][item]:
          text_lines.append("\t" + str(i[1]).replace(" 00:00:00", "") + "\t\tRM" + str(format(float(i[4]), '.2f')))
        item_expander = Gtk.Expander(
          label=" ".join([str(self.items[item][2]), str(self.items[item][3]), str(self.items[item][4]), str(self.items[item][5])])
        )
        item_expander.show()
        item_expander.set_expanded(False)
        item_expander.show()

        details = Gtk.Label(label="\n".join(text_lines), xalign=0)
        details.set_halign(Gtk.Align.START)
        details.show()

        item_expander.add(details)
        vbox.add(item_expander)
      self.vbox_premise_list.add(listbox)

  def on_group_combo_changed(self, combo):
    tree_iter = combo.get_active_iter()
    if tree_iter is not None:
      model = combo.get_model()
      row_id, name = model[tree_iter][:2]
      # print("Selected: ID=%d, name=%s" % (row_id, name))
      self.group = name if row_id != 0 else None
    else:
      self.group = None
      entry = combo.get_child()
      # print("Entered: %s" % entry.get_text())

  def on_category_combo_changed(self, combo):
    tree_iter = combo.get_active_iter()
    if tree_iter is not None:
      model = combo.get_model()
      row_id, name = model[tree_iter][:2]
      # print("Selected: ID=%d, name=%s" % (row_id, name))
      self.category = name if row_id != 0 else None
    else:
      self.category = None
      entry = combo.get_child()
      # print("Entered: %s" % entry.get_text())

  def on_state_combo_changed(self, combo):
    if (self.hbox_search_combobox != None):
      while (len(self.hbox_search_combobox.get_children()) > 3):
        self.hbox_search_combobox.remove(self.hbox_search_combobox.get_children()[len(self.hbox_search_combobox.get_children()) - 1])
      self.hbox_search_combobox.show()
    tree_iter = combo.get_active_iter()
    if tree_iter is not None:
      model = combo.get_model()
      row_id, name = model[tree_iter][:2]
      # print("State Selected: ID=%d, name=%s" % (row_id, name))
      self.hbox_search_combobox_append_district_combobox(name)
    else:
      entry = combo.get_child()
      # print("State Entered: %s" % entry.get_text())

  def on_district_combo_changed(self, combo):
    if (self.hbox_search_combobox != None):
      while (len(self.hbox_search_combobox.get_children()) > 4):
        self.hbox_search_combobox.remove(self.hbox_search_combobox.get_children()[len(self.hbox_search_combobox.get_children()) - 1])
      self.hbox_search_combobox.show()
    tree_iter = combo.get_active_iter()
    if tree_iter is not None:
      model = combo.get_model()
      row_id, name = model[tree_iter][:2]
      # print("District Selected: ID=%d, name=%s" % (row_id, name))
      self.hbox_search_combobox_append_premise_type_combobox(name)
    else:
      entry = combo.get_child()
      # print("District Entered: %s" % entry.get_text())

  def on_premise_type_combo_changed(self, combo):
    tree_iter = combo.get_active_iter()
    if tree_iter is not None:
      model = combo.get_model()
      row_id, name = model[tree_iter][:2]
      # print("Premise Type Selected: ID=%d, name=%s" % (row_id, name))
      self.premise_type = name if row_id != 0 else None
    else:
      self.premise_type = None
      entry = combo.get_child()
      # print("Premise Type Entered: %s" % entry.get_text())

win = PriceCatcher()
win.connect("destroy", Gtk.main_quit)
win.show_all()
Gtk.main()


from telebot import TeleBot

api = '1722995619:AAFD3SqWOCp2ZCjlUhkkYCYp6MvZfJeVPu8'
bot = TeleBot(api, parse_mode='html')

@bot.message_handler(commands=['start'])
def send_welcome(message):
    bot.send_message(message.chat.id, 'Привет, ты попал в бота для получения данных'
                                      ' с сервера в виде exele файлов\n\n'
                                      'Напиши боту команду /info он пришлет тебе все файлы с статистикой')

@bot.message_handler(commands=['info'])
def send_exele(message):
    chat_id = message.chat.id

    rekshop = open('rekshop.xls', 'rb')
    bot.send_document(chat_id, rekshop)

    voltiq = open('voltiq.xls', 'rb')
    bot.send_document(chat_id, voltiq)

    roboshop = open('roboshop.xls', 'rb')
    bot.send_document(chat_id, roboshop)

    arduinopro = open('arduinopro.xls', 'rb')
    bot.send_document(chat_id, arduinopro)

    bot.send_message(chat_id, text='Для завершения анализа обратитесь к программисту')

bot.polling(none_stop=True)