import os
import subprocess
import sys
from pathlib import Path
from time import sleep
from typing import Any, Callable, TypeVar

import numpy as np
from hydra.core.hydra_config import HydraConfig
from hydra_zen import load_from_yaml
from omegaconf.errors import ConfigAttributeError
from pytorch_lightning import Trainer
from pytorch_lightning.trainer.states import TrainerFn
from torch import distributed

from .._compatibility import PL_VERSION, Version

R = TypeVar("R")

def _setup_environment() -> None:
    if distributed.is_initialized():
        distributed.destroy_process_group()

def _teardown() -> None:
    # Remove PL environments so next multirun starts fresh
    envs = (
        "LOCAL_RANK",
        "NODE_RANK",
        "WORLD_SIZE",
        "MASTER_ADDR",
        "MASTER_PORT",
        "PL_GLOBAL_SEED",
    )

    for name in envs:
        os.environ.pop(name, None)

def _subprocess_call(local_rank: int, testing: bool, predicting: bool) -> None:
    env_copy = os.environ.copy()
    env_copy["LOCAL_RANK"] = f"{local_rank}"
    # CWD is the Hydra working directory
    cwd = os.getcwd()
    os_cwd = (
        f'"{cwd}"'  # this is needed to handle characters like `=` in the directory name
    )

    command = [
        sys.executable,
        "-m",
        "rai_toolbox.mushin.lightning._pl_main",
    ]
    hydra_cfg = HydraConfig.get()

    hydra_output = (
        os.path.join(cwd, hydra_cfg.output_subdir)
        if hydra_cfg.output_subdir is not None
        else cwd
    )

    # Validate that minimal configuration requirements
    config = Path(hydra_output) / "config.yaml"
    assert config.exists()
    cfg = load_from_yaml(config)
    if "trainer" not in cfg or "module" not in cfg:
        raise ConfigAttributeError(
            "Missing configurations `trainer` and `module` are required for use with HydraDDP.  See documentation for further details."
        )

    # create the command for CLI
    command += ["-cp", hydra_output, "-cn", "config.yaml"]

    # Set flag to run Trainer.fit or Trainer.test in `_pl_main.py`
    command += ["++pl_testing=" + ("false" if not testing else "true")]

    # Set flag to run Trainer.fit or Trainer.test in `_pl_main.py`
    command += ["++pl_predicting=" + ("false" if not predicting else "true")]

    # Set flag for local rank
    command += [f"++pl_local_rank={local_rank}"]

    command += [
        f"hydra.run.dir={os_cwd}",
        f"hydra.output_subdir=.pl_hydra_rank_{local_rank}",
        f"hydra.job.name={hydra_cfg.job.name}",
    ]
    subprocess.Popen(command, env=env_copy, cwd=cwd)

if PL_VERSION >= Version(1, 6, 0):
    from pytorch_lightning.strategies.ddp import DDPStrategy
    from pytorch_lightning.strategies.launchers.subprocess_script import (
        _SubprocessScriptLauncher,
    )

    class HydraDDP(DDPStrategy):  # type: ignore
        """DDP Strategy that supports Hydra run and multirun jobs.

        This strategy assumes a PyTorch Lightning `Trainer.fit` or `Trainer.test` has been configured
        to execute via Hydra.  It requires that Hydra saves a `config.yaml` in the current working directory with the following keys/properties set::

           ├── Config
           │    ├── trainer: A `pytorch_lightning.Trainer` configuration
           │    ├── module: A `pytorch_lightning.LightningModule` configuration
           │    ├── datamodule: [OPTIONAL] A `pytorch_lightning.LightningDataModule` configuration

        This strategy will launch a child subprocesses for additional GPU beyond the first using the following base command::

           python -m rai_toolbox.mushin.lightning._pl_main -cp <path to config.yaml> -cn config.yaml

        Examples
        --------

        First define a Hydra configuration using hydra-zen:

        >>> import pytorch_lightning as pl
        ... from hydra_zen import builds, make_config,
        ... from rai_toolbox.mushin import HydraDDP
        ... from rai_toolbox.mushin.testing.lightning import SimpleLightningModule
        ...
        ... TrainerConfig = builds(
        ...     pl.Trainer,
        ...     accelerator="auto",
        ...     gpus=2,
        ...     max_epochs=1,
        ...     fast_dev_run=True,
        ...     strategy=builds(HydraDDP),
        ...     populate_full_signature=True
        ... )
        ...
        ... ModuleConfig = builds(SimpleLightningModule)
        ...
        ... Config = make_config(
        ...     trainer=TrainerConfig,
        ...     module=ModuleConfig
        ... )

        Next, define a task function to execute the Hydra job:

        >>> from hydra_zen import instantiate
        >>> def task_function(cfg):
        ...     obj = instantiate(cfg)
        ...     obj.trainer.fit(obj.module)

        Launch the Hydra+Lightning DDP job

        >>> from hydra_zen import launch
        >>> job = launch(Config, task_function)

        ``HydraDDP`` also supports ``LightningDataModule`` configuration.

        >>> DataModuleConfig = ... # A LightningDataModule config
        >>> Config = make_config(
        ...     trainer=TrainerConfig,
        ...     module=ModuleConfig
        ...     datamodule=DataModuleconfig
        ... )

        Next define a task function to execute the Hydra job:

        >>> from hydra_zen import instantiate
        >>> def task_function(cfg):
        ...     obj = instantiate(cfg)
        ...     obj.trainer.fit(obj.module, datamodule=obj.datamodule)

        Launch the Hydra+Lightning DDP job:

        >>> from hydra_zen import launch
        >>> job = launch(Config, task_function)
        """

        def setup_environment(self) -> None:
            _setup_environment()
            super().setup_environment()

        def _configure_launcher(self) -> None:
            if self.cluster_environment is None:  # pragma: no cover
                raise TypeError("HydraDDP.cluster_environment is None")

            if not self.cluster_environment.creates_processes_externally:
                self._launcher = _HydraDDPLauncher(
                    self.cluster_environment, self.num_processes, self.num_nodes
                )
                self._rank_0_will_call_children_scripts = True

        def teardown(self) -> None:
            """Performs additional teardown steps for PL to allow for Hydra multirun jobs."""
            super().teardown()
            _teardown()

    class _HydraDDPLauncher(_SubprocessScriptLauncher):
        @property
        def is_interactive_compatible(self) -> bool:  # pragma: no cover
            return True

        def launch(
            self,
            function: Callable[..., R],
            *args: Any,
            trainer: Trainer,
            **kwargs: Any,
        ) -> R:
            """Creates new processes, then calls the given function.

            Parameters
            ----------
            function : Callable[[...], ReturnType]
                A callback function to execute after all processes have been created.
                It is up to the implementation of this function to synchronize the processes, e.g., with barriers.

            *args : Any
                Optional positional arguments to be passed to the given function.

            trainer : pytorch_lightning.Trainer
                Optional reference to the pytorch_lightning.Trainer`.

            **kwargs : Any
                Optional keyword arguments to be passed to the given function.

            Returns
            -------
            ReturnType
            """
            del trainer  # unused
            if (
                not self.cluster_environment.creates_processes_externally
            ):  # pragma: no cover
                testing = function.__name__ == "_test_impl"
                predicting = function.__name__ == "_predict_impl"
                self._call_children_scripts(testing=testing, predicting=predicting)

            return function(*args, **kwargs)

        def _call_children_scripts(self, testing: bool, predicting: bool):
            # bookkeeping of spawned processes
            self._check_can_spawn_children()

            # DDP Environment variables
            os.environ["MASTER_ADDR"] = self.cluster_environment.main_address
            os.environ["MASTER_PORT"] = str(self.cluster_environment.main_port)

            # allow the user to pass the node rank
            os.environ["NODE_RANK"] = str(self.cluster_environment.node_rank())
            os.environ["LOCAL_RANK"] = str(self.cluster_environment.local_rank())
            os.environ["WORLD_SIZE"] = f"{self.num_processes * self.num_nodes}"

            for local_rank in range(1, self.num_processes):
                _subprocess_call(local_rank, testing, predicting)

                # starting all processes at once can cause issues
                # with dataloaders delay between 1-10 seconds
                delay = np.random.uniform(1, 5, 1)[0]
                sleep(delay)

else:  # pragma: no cover
    from pytorch_lightning.plugins.training_type.ddp import DDPPlugin  # type: ignore

    class HydraDDP(DDPPlugin):
        """DDP Strategy that supports Hydra run and multirun jobs.

        This strategy assumes a PyTorch Lightning `Trainer.fit` or `Trainer.test` has been configured
        to execute via Hydra.  It requires that Hydra saves a `config.yaml` in the current working directory with the following keys/properties set::

           ├── Config
           │    ├── trainer: A `pytorch_lightning.Trainer` configuration
           │    ├── module: A `pytorch_lightning.LightningModule` configuration
           │    ├── datamodule: [OPTIONAL] A `pytorch_lightning.LightningDataModule` configuration

        This strategy will launch a child subprocesses for additional GPU beyond the first using the following base command::

           python -m rai_toolbox.mushin.lightning._pl_main -cp <path to config.yaml> -cn config.yaml

        Examples
        --------

        First define a Hydra configuration using hydra-zen:

        >>> import pytorch_lightning as pl
        ... from hydra_zen import builds, make_config,
        ... from rai_toolbox.mushin import HydraDDP
        ... from rai_toolbox.mushin.testing.lightning import SimpleLightningModule
        ...
        ... TrainerConfig = builds(
        ...     pl.Trainer,
        ...     accelerator="auto",
        ...     gpus=2,
        ...     max_epochs=1,
        ...     fast_dev_run=True,
        ...     strategy=builds(HydraDDP),
        ...     populate_full_signature=True
        ... )
        ...
        ... ModuleConfig = builds(SimpleLightningModule)
        ...
        ... Config = make_config(
        ...     trainer=TrainerConfig,
        ...     module=ModuleConfig
        ... )

        Next define a task function to execute the Hydra job:

        >>> from hydra_zen import instantiate
        >>> def task_function(cfg):
        ...     obj = instantiate(cfg)
        ...     obj.trainer.fit(obj.module)

        Launch the Hydra+Lightning DDP job:

        >>> from hydra_zen import launch
        >>> job = launch(Config, task_function)

        ``HydraDDP`` also supports ``LightningDataModule`` configuration.

        >>> DataModuleConfig = ... # A LightningDataModule config
        >>> Config = make_config(
        ...     trainer=TrainerConfig,
        ...     module=ModuleConfig
        ...     datamodule=DataModuleconfig
        ... )

        Next, define a task function to execute the Hydra job:

        >>> from hydra_zen import instantiate
        >>> def task_function(cfg):
        ...     obj = instantiate(cfg)
        ...     obj.trainer.fit(obj.module, datamodule=obj.datamodule)

        Launch the Hydra+Lightning DDP job:

        >>> from hydra_zen import launch
        >>> job = launch(Config, task_function)
        """

        def setup_environment(self) -> None:
            _setup_environment()
            super().setup_environment()

        def _call_children_scripts(self):
            if self.lightning_module is None:  # pragma: no cover
                raise TypeError("HydraDDP.lightning_module is None")

            if self.lightning_module.trainer is None:  # pragma: no cover
                raise TypeError("HydraDDP.lightning_module.trainer is None")

            if self.cluster_environment is None:  # pragma: no cover
                raise TypeError("HydraDDP.cluster_environment is None")

            # bookkeeping of spawned processes
            self._check_can_spawn_children()

            # DDP Environment variables
            os.environ["MASTER_ADDR"] = self.cluster_environment.master_address()
            os.environ["MASTER_PORT"] = str(self.cluster_environment.master_port())

            # allow the user to pass the node rank
            os.environ["NODE_RANK"] = str(self.cluster_environment.node_rank())
            os.environ["LOCAL_RANK"] = str(self.cluster_environment.local_rank())
            os.environ["WORLD_SIZE"] = f"{self.num_processes * self.num_nodes}"

            self.interactive_ddp_procs = []
            for local_rank in range(1, self.num_processes):
                testing = self.lightning_module.trainer.state.fn == TrainerFn.TESTING
                predicting = (
                    self.lightning_module.trainer.state.fn == TrainerFn.PREDICTING
                )
                _subprocess_call(local_rank, testing=testing, predicting=predicting)

                # starting all processes at once can cause issues
                # with dataloaders delay between 1-10 seconds
                delay = np.random.uniform(1, 5, 1)[0]
                sleep(delay)

            self._rank_0_has_called_call_children_scripts = True

        def teardown(self) -> None:
            """Performs additional teardown steps for PL to allow for Hydra multirun jobs."""
            super().teardown()
            _teardown()


#!/usr/bin/env python

import sys
import argparse
import rospy
from std_msgs.msg import Empty
from jsk_recognition_msgs.msg import Rect, RectArray

class CheckIntersection:
    # claimed topic must have 0 or 1 elements
    #
    def __init__(self, topic1, topic2, output_topic, tolerance=-1, size_threshold=2.5):
        self.sub1 = rospy.Subscriber(topic1, RectArray, self.callback_update, queue_size=1)
        self.sub2 = rospy.Subscriber(topic2, RectArray, self.callback_check, queue_size=2)
        self.pub  = rospy.Publisher(output_topic, Empty, queue_size=10)

        self.rect = None
        self.empty_counter = 0
        self.tolerance = tolerance
        self.thre = size_threshold

    def callback_update(self, msg):
        if msg.rects:
            self.empty_counter = 0
            self.rect = msg.rects[0]
            return
        # empty
        self.empty_counter += 1
        if self.tolerance >= 0 and self.empty_counter > self.tolerance:
            self.rect = None

    def callback_check(self, msg):
        if self.rect is None:
            return
        for rect in msg.rects:
            if self.check(rect):
                self.pub.publish(Empty())
                return

    def check_overlap(self, r):
        if self.rect is None:
            return False
        if (r.x + r.width) < self.rect.x:
            return False
        if r.x > (self.rect.x + self.rect.width):
            return False
        if (r.y + r.height) < self.rect.y:
            return False
        if r.y > (self.rect.y + self.rect.height):
            return False
        return True

    def check_dimensions(self, r):
        if self.rect is None:
            return False
        if r.width > self.rect.width * self.thre:
            return False
        if r.height > self.rect.height * self.thre:
            return False
        return True

    def check(self, r):
        return self.check_dimensions(r) and self.check_overlap(r)

def filter_roslaunch_args(arg_list):
    return [x for x in arg_list if not x.startswith('__name') and not x.startswith('__log')]

if __name__ == '__main__':
    parser = argparse.ArgumentParser()

    parser.add_argument("topic1", help="Claimed resource rectangle")
    parser.add_argument("topic2", help="Claiming resource rectangle")
    parser.add_argument("output_topic", help="Publishing result")
    parser.add_argument("--tolerance", type=int, default=-1,
                        help="Number of empty messages before reseting")

    args = parser.parse_args(filter_roslaunch_args(sys.argv)[1:])

    rospy.init_node('rectangle_intersection', anonymous=True)
    worker = CheckIntersection(args.topic1, args.topic2, args.output_topic,
                               tolerance=args.tolerance)
    rospy.spin()


import random

import telebot
from telebot import types
token=''
bot=telebot.TeleBot(token)
sms=['Для возвращения на главное меню введите любое слово!']
kon1=['Записаться на маникюр или педикюр можно по телефону: '
     '+3753362686** ,или INSTAGRAM https://instagram.com/daria.y_nails?igshid=Ym*yMTA2M2Y=   ']
kon2=['Записаться на брови или ресницы можно по телефону:'
     '+375 ,либо написать в INSTAGRAM: https://instagram.com/browi_yanina?igshid=Ym*yMTA2M2Y=']

def create_keyboard():
    keyboard=types.InlineKeyboardMarkup()
    services_1_btn=types.InlineKeyboardButton(text='Прайс по маникюру и педикюру', callback_data='1')
    services_btn = types.InlineKeyboardButton(text='Прайс по бровям и ресницам', callback_data='2')
    masters_btn = types.InlineKeyboardButton(text='Мастера', callback_data='3')
    sign_up_btn=types.InlineKeyboardButton(text='Записаться на маникюр или педикюр',callback_data='4')
    sign_up_1_btn=types.InlineKeyboardButton(text='Записаться на брови или ресницы',callback_data='5')

    keyboard.add(services_1_btn)
    keyboard.add(services_btn)
    keyboard.add(sign_up_btn)
    keyboard.add(sign_up_1_btn)
    keyboard.add(masters_btn)
    return keyboard
@bot.message_handler(content_types=['text'])
def start_bot(message):
    keyboard=create_keyboard()
    bot.send_message(
        message.chat.id,'Здравствуйте! Вас приветствует студия красоты TIME! ',
        reply_markup=keyboard
        )

@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
    keyboard=create_keyboard()
    if call.message:
        if call.data=='1':
            img = open('пра.jpg', 'rb')
            bot.send_photo(
                chat_id=call.message.chat.id,
                photo=img,
                caption='Прайс по маникюру и педикюру')
            msg = random.choice(sms)
            bot.send_message(call.message.chat.id, msg)

        if call.message:
            if call.data == '2':
                img = open('прайс брови.jpg', 'rb')
                bot.send_photo(
                    chat_id=call.message.chat.id,
                    photo=img,
                    caption='Прайс по бровям и ресницам')
                msg = random.choice(sms)
                bot.send_message(call.message.chat.id, msg)
        if call.data == '3':
          img = open('Даша.jpg', 'rb')
          bot.send_photo(
             chat_id=call.message.chat.id,
             photo=img,
             caption='Мастер по маникюру Даша')
          img = open('Янина.jpg','rb')
          bot.send_photo(
              chat_id=call.message.chat.id,
              photo=img,
              caption='Мастер по бровям Янина')
          msg = random.choice(sms)
          bot.send_message(call.message.chat.id, msg)
        if call.data == '4':
           msg = random.choice(kon1)
           bot.send_message(call.message.chat.id, msg)
           msg = random.choice(sms)
           bot.send_message(call.message.chat.id, msg)

        if call.data == '5':
           msg = random.choice(kon2)
           bot.send_message(call.message.chat.id, msg)
           msg = random.choice(sms)
           bot.send_message(call.message.chat.id, msg)

if __name__=='__main__':
  bot.polling(none_stop=True)


import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

SCOPES = ['https://www.googleapis.com/auth/drive']

def get_service(credential, pickle_token, target_folder):
    creds = None

    if pickle_token is not None and os.path.exists(pickle_token):
        with open(pickle_token, 'rb') as token:
            creds = pickle.load(token)

    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            if credential is None:
                raise Exception('No pickle file found. Please enable google drive api. Go to \'https://developers.google.com/drive/api/v3/quickstart/python\' and follow Step 1 and download your credential.json and input with the command line option --credential')
            flow = InstalledAppFlow.from_client_secrets_file(
                    credential, SCOPES)
            creds = flow.run_local_server()
            with open(os.path.join(target_folder, 'token.pickle'), 'wb') as token:
                pickle.dump(creds, token)
            print('Pickle is saved in target folder {}. Use the option --pickle next time you run the application.'.format(target_folder))
    service = build('drive', 'v3', credentials=creds)
    return service


from asanitize.services.discord import session, build_url
from asanitize.services.discord.data.http_middleware import HTTPMiddleware
from asanitize.services.discord.data.channel_list import DirectMessageChannelList, GuildList, User
from asanitize.services.discord.exceptions import AuthenticationTokenMissingError, ConnectionError

class Client(HTTPMiddleware):
    token = None
    current_user_info = None

    def __init__(self, token: str) -> None:
        self.token = token
        if not token:
            raise AuthenticationTokenMissingError('Missing discord authentication token')

        session.headers.update({'Authorization': token })

        response = self.get(build_url('users', '@me'))
        if response.status_code != 200:
            raise ConnectionError('Connection error')

        response = response.json()
        self.current_user_info = User(
            id=response.get('id'),
            username=response.get('username'),
            avatar=response.get('avatar'),
            discriminator=response.get('discriminator'),
            public_flags=response.get('public_flags'),
            flags=response.get('flags'),
            banner=response.get('banner'),
            banner_color=response.get('banner_color'),
            accent_color=response.get('accent_color'),
            bio=response.get('bio'),
            locale=response.get('locale'),
            nsfw_enabled=response.get('nsfw_enabled'),
            mfa_enabled=response.get('mfa_enabled'),
            email=response.get('email'),
            verified=response.get('verified'),
            phone=response.get('phone'),
        )

    def get_direct_message_channels(self) -> DirectMessageChannelList:
        direct_messages_url = build_url('users', '@me', 'channels')
        response = self.get(direct_messages_url).json()
        return DirectMessageChannelList(response)

    def get_guilds(self) -> GuildList:
        guilds_url = build_url('users', '@me', 'guilds')
        response = self.get(guilds_url).json()
        return GuildList(guild_list=response)


from __main__ import vtk, qt, ctk, slicer
import vtkSegmentationCorePython as vtkSegmentationCore
import os
#
# CSISegCor
# Cubic Spline Image Segmentation Correction
class CSISegCor:

    def __init__(self, parent):

        parent.title = "Cubic Spline Image Segmentation Correction"
        parent.categories = ["Exemple"]
        parent.dependencies = []
        parent.contributors = [" Abdelkhalek Bakkari ", "Dhifli Mohamed "]

class CSISegCorWidget:

    def __init__(self, parent=None):

        if not parent:
            self.parent = slicer.qMRMLWidget()
            self.parent.setLayout(qt.QVBoxLayout())
            self.parent.setMRMLScene(slicer.mrmlScene)
        else:
            self.parent = parent
        self.layout = self.parent.layout()
        if not parent:
            self.setup()
            self.parent.show()

    def setup(self):

        self.__clippingModelNode = None
        self.__clippingMarkupNode = None
        self.__clippingMarkupNodeObserver = None

        self.toFids = slicer.vtkMRMLMarkupsFiducialNode()
        self.fromFids = slicer.vtkMRMLMarkupsFiducialNode()
        self.toFids.SetName('toFids')
        self.fromFids.SetName('fromFids')
        slicer.mrmlScene.AddNode(self.toFids)
        slicer.mrmlScene.AddNode(self.fromFids)
        self.__markupList = []
        # create a callapsible button
        collapsibleButton = ctk.ctkCollapsibleButton()
        collapsibleButton.text = "Cubic Spline Image Segmentation Correction"

        # bind collapsibleButton to root Layout
        self.layout.addWidget(collapsibleButton)

        # new layout for collapsible button
        self.formLayout = qt.QFormLayout(collapsibleButton)

        # volume selector
        self.formFrame = qt.QFrame(collapsibleButton)
        self.formFrame1 = qt.QFrame(collapsibleButton)
        self.formFrame4 = qt.QFrame(collapsibleButton)
        self.formFrame2 = qt.QFrame(collapsibleButton)
        self.formFrame5 = qt.QFrame(collapsibleButton)
        self.formFrame3 = qt.QFrame(collapsibleButton)

        # set a layout to horizontal
        self.formFrame.setLayout(qt.QHBoxLayout())
        self.formFrame1.setLayout(qt.QHBoxLayout())
        self.formFrame4.setLayout(qt.QHBoxLayout())
        self.formFrame2.setLayout(qt.QHBoxLayout())
        self.formFrame5.setLayout(qt.QHBoxLayout())
        self.formFrame3.setLayout(qt.QHBoxLayout())

        # bind a new frame to existing layout in collapsible menu
        self.formLayout.addWidget(self.formFrame)
        self.formLayout.addWidget(self.formFrame1)
        self.formLayout.addWidget(self.formFrame4)
        self.formLayout.addWidget(self.formFrame2)
        self.formLayout.addWidget(self.formFrame5)
        self.formLayout.addWidget(self.formFrame3)

        # creating new volume selector
        self.inputSelector = qt.QLabel("Input Volume: ", self.formFrame)
        self.formFrame.layout().addWidget(self.inputSelector)
        self.inputSelector = slicer.qMRMLNodeComboBox(self.formFrame)
        self.inputSelector.nodeTypes = (("vtkMRMLScalarVolumeNode"), "")
        self.inputSelector.addEnabled = False
        self.inputSelector.removeEnabled = False

        self.inputSelector1 = qt.QLabel("Input segmentation: ", self.formFrame1)
        self.formFrame1.layout().addWidget(self.inputSelector1)
        self.inputSelector1 = slicer.qMRMLNodeComboBox(self.formFrame1)
        self.inputSelector1.nodeTypes = (("vtkMRMLSegmentationNode"), "")
        self.inputSelector1.addEnabled = False
        self.inputSelector1.removeEnabled = False

        self.inputSelector4 = qt.QLabel("Input transformation: ", self.formFrame4)
        self.formFrame4.layout().addWidget(self.inputSelector4)
        self.inputSelector4 = slicer.qMRMLNodeComboBox(self.formFrame4)
        self.inputSelector4.nodeTypes = (("vtkMRMLTransformNode"), "")
        self.inputSelector4.addEnabled = False
        self.inputSelector4.removeEnabled = False

        self.inputSelector2 = qt.QLabel("Set default Segmentation display : ", self.formFrame2)
        self.formFrame2.layout().addWidget(self.inputSelector2)

        self.inputSelector5 = qt.QLabel("Add markups : ", self.formFrame3)
        self.formFrame5.layout().addWidget(self.inputSelector5)

        self.inputSelector3 = qt.QLabel("Segmentation Correction: ", self.formFrame3)
        self.formFrame3.layout().addWidget(self.inputSelector3)

        # bind the current volume selector to the current scene of slicer
        self.inputSelector.setMRMLScene(slicer.mrmlScene)
        self.inputSelector1.setMRMLScene(slicer.mrmlScene)
        self.inputSelector4.setMRMLScene(slicer.mrmlScene)

        # bind the input selector to the frame
        self.formFrame.layout().addWidget(self.inputSelector)
        self.formFrame1.layout().addWidget(self.inputSelector1)
        self.formFrame4.layout().addWidget(self.inputSelector4)

        # testing
        button = qt.QPushButton("Load Volume")
        self.formFrame.layout().addWidget(button)
        button.connect("clicked()", slicer.util.openAddVolumeDialog)
        button.show()

        # button for importing mesh files
        button1 = qt.QPushButton("Load Segemntation")
        self.formFrame1.layout().addWidget(button1)
        button1.connect("clicked()", slicer.util.openAddSegmentationDialog)
        button1.show()

        # button for importing mesh files
        button4 = qt.QPushButton("Load Transform")
        self.formFrame4.layout().addWidget(button4)
        button4.connect("clicked()", slicer.util.openAddTransformDialog)
        button4.show()

        # button for setting default segmentation display
        button2 = qt.QPushButton("Set default")
        self.formFrame2.layout().addWidget(button2)
        button2.connect("clicked(bool)", self.SetDefaultValuesClicked)
        button2.show()

        # button for Final work
        self.button5 = qt.QToolButton()
        self.button5.icon = qt.QIcon(os.path.join(os.path.dirname(__file__), 'MarkupsMouseModePlace.png'))
        self.button5.setCheckable(1)
        self.formFrame5.layout().addWidget(self.button5)
        self.button5.connect("clicked(bool)", self.enableaddmarkuponclick)
        self.button5.show()

        # button for Final work
        button3 = qt.QPushButton("Do corrections")
        self.formFrame3.layout().addWidget(button3)
        button3.connect("clicked(bool)", self.do_correctionsClicked)
        button3.show()

    def enableaddmarkuponclick(self):
        applicationLogic = slicer.app.applicationLogic()
        selectionNode = applicationLogic.GetSelectionNode()

        selectionNode.SetReferenceActivePlaceNodeClassName("vtkMRMLMarkupsFiducialNode")
        interactionNode = applicationLogic.GetInteractionNode()

        if self.button5.checked:
            interactionNode.SwitchToPersistentPlaceMode()
        else:
            interactionNode.SwitchToViewTransformMode()

        #self.onClippingMarkupSelect(self.toFids)

    def onClippingMarkupSelect(self, node):

        if node != None and node != '':
            if node.GetID() not in self.__markupList:
                new_clippingModelNode = slicer.vtkMRMLModelNode()
                new_clippingModelNode.SetScene(slicer.mrmlScene)
                slicer.mrmlScene.AddNode(new_clippingModelNode)
                self.toFids.append(node.GetID())

            self.toFids = node
            self.setAndObserveClippingMarkupNode(node)

    def setAndObserveClippingMarkupNode(self, clippingMarkupNode):

        # Remove observer to old parameter node
        if self.__clippingMarkupNode and self.__clippingMarkupNodeObserver:
            self.__clippingMarkupNode.RemoveObserver(self.__clippingMarkupNodeObserver)
            self.__clippingMarkupNodeObserver = None

        # Set and observe new parameter node
        self.__clippingMarkupNode = clippingMarkupNode
        if self.__clippingMarkupNode:
            self.__clippingMarkupNodeObserver = self.__clippingMarkupNode.AddObserver(vtk.vtkCommand.ModifiedEvent, self.onClippingMarkupNodeModified)

        applicationLogic = slicer.app.applicationLogic()
        selectionNode = applicationLogic.GetSelectionNode()

        # Update GUI
        self.updateModelFromClippingMarkupNode()

    def updateModelFromClippingMarkupNode(self):

        self.updateModelFromMarkup(self.__clippingMarkupNode, self.__clippingModelNode)

    def SetDefaultValuesClicked(self):
        if(not self.toFids):
            self.toFids = slicer.vtkMRMLMarkupsFiducialNode()
            self.toFids.SetName('toFids')
        if(not self.fromFids):
            self.fromFids = slicer.vtkMRMLMarkupsFiducialNode()
            self.fromFids.SetName('fromFids')
        if self.inputSelector1.currentNode():
            segmentationNode = self.inputSelector1.currentNode()
            TransformNode = self.inputSelector4.currentNode()
            segmentation = segmentationNode.GetSegmentation()
            segment = segmentation.GetSegment(segmentation.GetNthSegmentID(0))
            segment.SetColor(0, 0, 1)
            segmentationNode.GetDisplayNode().Visibility2DFillOff()

            if TransformNode:
                segmentationNode.SetAndObserveTransformNodeID(TransformNode.GetID())
                print ("transform successful")
            print ("color change successful")
        else:
            slicer.util.errorDisplay("No Segementation selected !")

    def do_correctionsClicked(self):
        # Copy and paste into Slicer Python interactor
        # Drag visible fiducials to deform transform

        # Scale defines how large cube will be created
        # numPerEdge defines how many fiducials to put on each edge of the cube
        size=0
        scalex = 10.0
        scaley = 10.0
        scalez = 10.0
        numPerEdge = size/10

        # Create the FROM fiducial list, and hide it so it doesn't change with mouse interactions

        slicer.mrmlScene.AddNode(self.toFids)
        self.toFids.Copy(self.fromFids)
        self.toFids.SetName('toFids')
        self.toFids.GetDisplayNode().SetVisibility(True)

        # Create the transform node to hold the deformable transformation later
        try:
            slicer.mrmlScene.RemoveNode(slicer.util.getNode("TpsTransform"))
            tNode = slicer.vtkMRMLTransformNode()
            tNode.SetName('TpsTransform')
            slicer.mrmlScene.AddNode(tNode)
        except:
            print("creating new TpsTransform")

        tNode = slicer.vtkMRMLTransformNode()
        tNode.SetName('TpsTransform')
        slicer.mrmlScene.AddNode(tNode)

        # Function that will be called whenever a TO fiducial moves and the transform needs an update

        def updateTpsTransform(caller, eventid):
            numPerEdge = self.fromFids.GetNumberOfFiducials()
            if numPerEdge != self.toFids.GetNumberOfFiducials():
                print
                'Error: Fiducial numbers are not equal!'
                return

            fp = vtk.vtkPoints()
            tp = vtk.vtkPoints()
            f = [0, 0, 0]
            t = [0, 0, 0]

            for i in range(numPerEdge):
                self.fromFids.GetNthFiducialPosition(i, f)
                self.toFids.GetNthFiducialPosition(i, t)
                fp.InsertNextPoint(f)
                tp.InsertNextPoint(t)

            tps = vtk.vtkThinPlateSplineTransform()
            tps.SetSourceLandmarks(fp)
            tps.SetTargetLandmarks(tp)
            tps.SetBasisToR()
            tNode.SetAndObserveTransformToParent(tps)

        self.toFids.AddObserver(vtk.vtkCommand.ModifiedEvent, updateTpsTransform)

        # A ROI annotation defines the region where the transform will be visualized

        roi = self.inputSelector1.currentNode()
        slicer.mrmlScene.AddNode(roi)
        roi.SetDisplayVisibility(True)
        # Set up transform visualization as gridlines

        tNode.CreateDefaultDisplayNodes()
        d = tNode.GetDisplayNode()
        d.SetAndObserveRegionNode(roi)
        d.SetVisualizationMode(slicer.vtkMRMLTransformDisplayNode.VIS_MODE_GRID)
        d.SetVisibility(False)
        roi.SetAndObserveTransformNodeID(tNode.GetID())
        TransformNode = self.inputSelector4.currentNode()
        tNode.SetAndObserveTransformNodeID(TransformNode.GetID())

    def updateModelFromMarkup(self, inputMarkup, outputModel):
        """
        Update model to enclose all points in the input markup list
        """

        # Delaunay triangulation is robust and creates nice smooth surfaces from a small number of points,
        # however it can only generate convex surfaces robustly.
        useDelaunay = True

        # Create polydata point set from markup points

        points = vtk.vtkPoints()
        cellArray = vtk.vtkCellArray()

        numberOfPoints = inputMarkup.GetNumberOfFiducials()

        # Surface generation algorithms behave unpredictably when there are not enough points
        # return if there are very few points
        if useDelaunay:
            if numberOfPoints < 3:
                return
        else:
            if numberOfPoints < 10:
                return

        points.SetNumberOfPoints(numberOfPoints)
        new_coord = [0.0, 0.0, 0.0]

        """for i in range(numberOfPoints):
            inputMarkup.GetNthFiducialPosition(i, new_coord)
            points.SetPoint(i, new_coord)"""

        cellArray.InsertNextCell(numberOfPoints)
        for i in range(numberOfPoints):
            cellArray.InsertCellPoint(i)

        pointPolyData = vtk.vtkPolyData()
        pointPolyData.SetLines(cellArray)
        pointPolyData.SetPoints(points)

        # Create surface from point set

        if useDelaunay:

            delaunay = vtk.vtkDelaunay3D()
            delaunay.SetInputData(pointPolyData)

            surfaceFilter = vtk.vtkDataSetSurfaceFilter()
            surfaceFilter.SetInputConnection(delaunay.GetOutputPort())

            smoother = vtk.vtkButterflySubdivisionFilter()
            smoother.SetInputConnection(surfaceFilter.GetOutputPort())
            smoother.SetNumberOfSubdivisions(3)
            smoother.Update()

            outputModel.SetPolyDataConnection(smoother.GetOutputPort())

        else:

            surf = vtk.vtkSurfaceReconstructionFilter()
            surf.SetInputData(pointPolyData)
            surf.SetNeighborhoodSize(20)
            surf.SetSampleSpacing(
                80)  # lower value follows the small details more closely but more dense pointset is needed as input

            cf = vtk.vtkContourFilter()
            cf.SetInputConnection(surf.GetOutputPort())
            cf.SetValue(0, 0.0)

            # Sometimes the contouring algorithm can create a volume whose gradient
            # vector and ordering of polygon (using the right hand rule) are
            # inconsistent. vtkReverseSense cures this problem.
            reverse = vtk.vtkReverseSense()
            reverse.SetInputConnection(cf.GetOutputPort())
            reverse.ReverseCellsOff()
            reverse.ReverseNormalsOff()

            outputModel.SetPolyDataConnection(reverse.GetOutputPort())

        # Create default model display node if does not exist yet
        if not outputModel.GetDisplayNode():
            modelDisplayNode = slicer.mrmlScene.CreateNodeByClass("vtkMRMLModelDisplayNode")
            modelDisplayNode.SetColor(0, 0, 1)  # Blue
            modelDisplayNode.BackfaceCullingOff()
            modelDisplayNode.SliceIntersectionVisibilityOn()
            modelDisplayNode.SetOpacity(0.3)  # Between 0-1, 1 being opaque
            slicer.mrmlScene.AddNode(modelDisplayNode)
            outputModel.SetAndObserveDisplayNodeID(modelDisplayNode.GetID())

        outputModel.GetDisplayNode().SliceIntersectionVisibilityOn()

        outputModel.Modified()

    def onClippingMarkupNodeModified(self, observer, eventid):

        self.updateModelFromClippingMarkupNode()

    def updateModelFromClippingMarkupNode(self):

        self.updateModelFromMarkup(self.__clippingMarkupNode, self.__clippingModelNode)


import json
from urllib.parse import urlparse, parse_qs
from http.server import BaseHTTPRequestHandler, HTTPServer
from views import get_all_entries, get_single_entry, delete_entry, get_all_moods, get_searched_entries, create_entry, update_entry

class HandleRequests(BaseHTTPRequestHandler):
    """Controls the functionality of any GET, PUT, POST, DELETE requests to the server
    """

    def parse_url(self, path):
        '''parses the url'''

        parsed_url = urlparse(path)
        path_params = parsed_url.path.split("/")
        resource = path_params[1]

        if parsed_url.query:
            query = parse_qs(parsed_url.query)
            return (resource, query)

        pk = None
        try:
            pk = int(path_params[2])
        except (IndexError, ValueError):
            pass
        return (resource, pk)

    def do_GET(self):
        '''handles GET requests to the server'''
        self._set_headers(200)
        response = {}

        parsed = self.parse_url(self.path)
        # use query params to get the search term
        if '?' not in self.path:
            (resource, id) = parsed

            if resource == "entries":
                if id is not None:
                    response = get_single_entry(id)
                else:
                    response = get_all_entries()

            elif resource == "moods":
                response = get_all_moods()
        else:
            (resource, query) = parsed

            if query.get('q') and resource == "entries":
                response = get_searched_entries(query['q'][0])
                print("response", response)

        self.wfile.write(json.dumps(response).encode())

    def do_POST(self):
        '''handles POST requests'''
        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)

        post_body = json.loads(post_body)

        (resource, id) = self.parse_url(self.path)

        created_entry = None

        if resource == "entries":
            self._set_headers(201)
            created_entry = create_entry(post_body)

        self.wfile.write(json.dumps(created_entry).encode())

    def do_PUT(self):
        '''updates an entry'''

        content_len = int(self.headers.get('content-length', 0))
        post_body = self.rfile.read(content_len)
        post_body = json.loads(post_body)

        (resource, id) = self.parse_url(self.path)

        success = False

        if resource == "entries":
            success = update_entry(id, post_body)

            if success:
                self._set_headers(204)
            else:
                self._set_headers(404)

        self.wfile.write(json.dumps(post_body).encode())

    def do_DELETE(self):
        '''delete handler'''
        self._set_headers(204)

        (resource, id) = self.parse_url(self.path)

        if resource == "entries":
            delete_entry(id)

        self.wfile.write("".encode())

    def _set_headers(self, status):
        '''sets status code, content-type and access-control-allow-origin headers on response

        Args:
            status (number): the status code to return to the front end'''
        self.send_response(status)
        self.send_header('Content-type', 'application/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()

    def do_OPTIONS(self):
        """Sets the options headers
        """
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods',
                         'GET, POST, PUT, DELETE')
        self.send_header('Access-Control-Allow-Headers',
                         'X-Requested-With, Content-Type, Accept')
        self.end_headers()

def main():
    """Starts the server on port 8088 using the HandleRequests class
    """
    host = ''
    port = 8088
    HTTPServer((host, port), HandleRequests).serve_forever()

if __name__ == "__main__":
    main()


from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit
from crispy_forms.bootstrap import InlineRadios

from website.models import Inscricao
from functools import reduce

"""
    Formulário contendo os seguintes campos
    Nome (Req|Str|Max:100)
    CPF (Req|Str|Formato:000.000.000-00)
    Nascimento (Req|Data)
    Email (Req|Str|Formato:<EMAIL>)
    Endereço (Req|Str|Max:120)
    Sexo (Req|Radio|Itens:Masculino;Feminino)
    Curso (Req|Dropbox|Itens:Curso técnico;Curso superior; Curso extra-curricular)
    Minicursos (Checkbox List|Itens:Introdução a Computação Gráfica;Introduição a construção de jogos;Realidade Virtual;Computação nas Nuvens)
"""

class CursoForm(forms.ModelForm):
    nome = forms.CharField(label='Nome', max_length=100,
                           widget=forms.TextInput(attrs={'form_style': 'inline'}),  required=True)
    # Adiciona uma mascará para o campo CPF
    cpf = forms.CharField(label='CPF', max_length=14,
                          min_length=14, required=True, widget=forms.TextInput(attrs={'form_style': 'inline', 'data-mask': '000.000.000-00'}))
    nascimento = forms.DateField(label='Nascimento', required=True)
    email = forms.EmailField(label='Email', required=True)
    endereco = forms.CharField(label='Endereço', max_length=120, required=True)
    sexo = forms.ChoiceField(
        label='Sexo', choices=Inscricao.SEXO_CHOICES, widget=forms.RadioSelect, required=True)
    curso = forms.ChoiceField(
        label='Curso', choices=Inscricao.CURSO_CHOICES, required=True)
    minicursos = forms.MultipleChoiceField(
        label='Minicursos', choices=Inscricao.MINICURSOS_CHOICES, widget=forms.CheckboxSelectMultiple, required=False)

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.helper = FormHelper()
        self.helper.form_class = 'form-horizontal'
        self.helper.label_class = 'col-lg-2'
        self.helper.field_class = 'col-lg-8'

        self.helper.layout = Layout(
            'nome',
            'cpf',
            'email',
            'nascimento',
            'endereco',
            InlineRadios('sexo'),
            'curso',
            'minicursos',
            Submit('submit', 'Enviar', css_class='btn btn-primary align-self-end')
        )

        # Inicia o minicursos, transformando de Integer Bitwise para MultipleChioiceFIeld
        self.fields['minicursos'].initial = self._minicursos_to_choices(
            self.initial.get('minicursos', 0))

    def _minicursos_to_choices(self, minicursos):
        return [c for c in Inscricao.MINICURSOS_CHOICES if c[0] & minicursos]

    def _choices_to_minicursos(self, choices):
        return reduce(lambda x, y: x | y, [int(c[0]) for c in choices], 0)

    def save(self, *args, **kwargs):
        # Salva o minicursos, transformando de MultipleChioiceFIeld para Integer Bitwise
        self.cleaned_data['minicursos'] = self._choices_to_minicursos(
            self.cleaned_data['minicursos'])
        self.instance.minicursos = self.cleaned_data['minicursos']
        return super().save(*args, **kwargs)

    class Meta:
        fields = ['nome', 'cpf', 'nascimento', 'email',
                  'endereco', 'sexo', 'curso']
        model = Inscricao


from django import template
from django.conf import settings

register = template.Library()

@register.filter(name='media_folder_products')
def media_folder_products(path):
    if not path:
        path = 'products_images/default.jpg'

    return f'{settings.MEDIA_URL}{path}'

def media_folder_users(path):
    if not path:
        path = 'user_avatars/default.png'

    return f'{settings.MEDIA_URL}{path}'

register.filter('media_folder_users', media_folder_users)


def solution(s):
    min_len = len(s)
    for n in range(1,(len(s)//2)+1):
        length = 0
        i = 0
        while i < len(s):
            token = s[i:n+i]
            iter = -1
            while token == s[i:n+i]:
                i += n
                iter += 1

            if iter > 0:
                length += n+len(str(iter+1))
            else:
                length += len(token)
        min_len = min(min_len, length)
    return min_len

# second try fail


import math

class Fraction:
    """A fraction with a numerator and denominator and arithmetic operations.
    Fractions are always stored in proper form, without common factors in
    numerator and denominator, and denominator >= 0.
    Since Fractions are stored in proper form, each value has a
    unique representation, e.g. 4/5, 24/30, and -20/-25 have the same
    internal representation.
    """

    def __init__(self, numerator, denominator=1):
        """Initialize a new fraction with the given numerator
           and denominator (default 1).
        """
        self.check_inf = False
        self.check_nan = False

        # check that numerator and denominator is int or not
        if not isinstance(numerator, int) or not isinstance(denominator, int):
            raise TypeError("type object cannot be interpreted as an integer")

        else:
            if (numerator == 0 and denominator  == 0):  # 0/0 represent NaN
                self.numerator = 0
                self.denominator = 0
                self.check_nan = True
            elif (numerator == 1 and denominator == 0):  # 1/0 is infinity
                self.check_inf = True
                self.numerator = 1
                self.denominator = 0

            elif (numerator == -1 and denominator == 0):  # -1/0 is infinity
                self.check_inf = True
                self.numerator = -1
                self.denominator = 0

            elif denominator == 0:
                self.numerator = 1
                self.denominator = 0

            if math.gcd(numerator, denominator) == 1 and (self.check_nan == False) and (self.check_inf == False):
                if ('-' in str(denominator)):
                    self.numerator = numerator * -1
                    self.denominator = denominator * -1
                else:
                    self.numerator = numerator
                    self.denominator = denominator

            elif (self.check_nan == False) and (self.check_inf == False):
                if ('-' in str(denominator)):
                    self.numerator = (numerator * -1) / math.gcd(numerator,denominator)
                    self.numerator = int(self.numerator)
                    self.denominator = (denominator * -1) / math.gcd(numerator,denominator)
                    self.denominator = int(self.denominator)
                else:
                    self.numerator = numerator / math.gcd(numerator, denominator)
                    self.numerator = int(self.numerator)
                    self.denominator = denominator / math.gcd(numerator, denominator)
                    self.denominator = int(self.denominator)

    def __add__(self, frac):
        """Return the sum of two fractions as a new fraction.
        Use the standard formula  a/b + c/d = (ad+bc)/(b*d)
        """
        if (self.numerator == 0 and self.denominator == 0) or (frac.numerator == 0 and frac.denominator == 0):
            numerator = 0
            denominator = 0

        else:
            if (self.numerator == 1 and self.denominator == 0) or (frac.numerator == 1 and frac.denominator == 0):
                if self.numerator == -1 or frac.numerator == -1:
                    numerator = 0
                    denominator = 0
                else:
                    numerator = 1
                    denominator = 0
            else:
                numerator = (self.numerator * frac.denominator) + (frac.numerator * self.denominator)
                denominator = self.denominator * frac.denominator
        return Fraction(numerator, denominator)

    def __mul__(self, frac):
        numerator = self.numerator * frac.numerator
        denominator = self.denominator * frac.denominator
        return Fraction(numerator, denominator)

    def __str__(self):
        if self.denominator == 1 or self.denominator == -1:
            if '-' in str(self.denominator):
                return "-{:.0f}".format(self.numerator)
            return "{:.0f}".format(self.numerator)
        if '-' in str(self.denominator):
            return "-{:.0f}/{:.0f}".format(self.numerator, self.denominator * -1)
        return "{:.0f}/{:.0f}".format(self.numerator, self.denominator)

    def __eq__(self, frac):
        """Two fractions are equal if they have the same value.
        Fractions are stored in proper form so the internal representation
        is unique (3/6 is same as 1/2).
        """
        """Two persons are qual if they have the same name"""

        if not isinstance(frac, Fraction):
            return False
        if (self.denominator == 0 and self.numerator == 0) and (frac.numerator == 0 and frac.denominator == 0):
            return True
        elif (self.denominator == 0 and self.numerator == 0) or (frac.numerator == 0 and frac.denominator == 0):
            return False
        if self.denominator == 0 or frac.denominator == 0:
            if self.numerator == frac.numerator:
                return True
            else:
                return False
        return (self.numerator / self.denominator) == (frac.numerator / frac.denominator)


import sys
from flask import *
import json
sys.path.append('./')
from DB_ADMIN import db
from bson.json_util import dumps

databaseObj1 = db.database()
databaseClient1 = databaseObj1.getClient2()
clientdetail_db = databaseClient1.empdb
clintdb_collection =clientdetail_db.empdetail

def hello():

    return jsonify({"message": "welcome to employee section"})

def view():
    data = dumps(clintdb_collection.find({},{"_id": 0}))
    if (clintdb_collection.find({},{"_id": 0}).count()!= 0):
        return jsonify({"employe": data ,"id": userid})
    print(clintdb_collection.find({},{"_id": 0}).count())

def add_employee(data):
    employee = json.loads(data)
    name = employee["name"]
    mail = employee["mail"]
    address = employee["address"]
    mydict = {"name": name, "mail": mail, "address": address }
    clintdb_collection.insert_one(mydict)
    return {'status': "sucess"}

def update_employee(primary_key,data):
    employee = json.loads(data)
    name = employee["name"]
    address = employee["address"]
    olddata=  {'mail': primary_key}
    newdata = { "$set": { "name": name,"mail": primary_key, "address": address} }
    clintdb_collection.update_one(olddata, newdata)
    return jsonify({"emplyoee" : "emplyoee updated"})

def delete_employee(primary_key):
    clintdb_collection.delete_one({"mail": primary_key})
    return jsonify({"emplyoee": "employee deleted"})


import os
import re
import operator
import functools

def recurse_dir(dir_path, func_to_call_on_files, ignore = []):
	"""Recurses through all subdirectories and calls func_to_call_on_files on
	each found file except files and directories in ignore."""

	for path in os.listdir(dir_path):
		if not path in ignore:
			full_path = dir_path + os.sep + path
			if os.path.isdir(path):
				recurse_dir(full_path, func_to_call_on_files)
			else:
				func_to_call_on_files(full_path)

class ClassIdGenerator:
	"""Generates unique ids for classes."""

	class Class:
		"""Represents a c++ class."""

		def __init__(self, generator, name):
			self.generator = generator
			self.id = generator.get_unique_id()
			self.name = name.strip()

		def __eq__(self, other):
			if not isinstance(other, ClassIdGenerator.Class):
				return False
			return self.name == other.name

		def __ne__(self, other):
			return not self.__eq__(other)

		def __cmp__(self, other):
			if not isinstance(other, ClassIdGenerator.Class):
				return -1
			return cmp(self.name, other.name)

		def __hash__(self):
			return hash(self.name)

	def __init__(self):
		self.next_id = 0
		self.classes = set([])
		self.regex = re.compile( r"""
				(?P<classId>static\s+const\s+int\s+classId\s*;)|		#static const int classId;
				(?P<entire_class_str>class\s+(?P<class_name>\w+)		#class className
				(
					([^;>]*{) |											#case with no colon
					(\s*:[^;]*{)) 										#case with colon for inheritance
				)
				""", re.VERBOSE)

#		self.regex = re.compile(r"""
#				(static\s+const\s+int\s+classId\s*;)| 	#static const int classId
#				(class\s+(?P<class_name>\w+)			#class className
#					[^;]*{)""")

	def get_unique_id(self):
		new_id = self.next_id
		self.next_id += 1
		return new_id

	def add_class(self, name):
		self.classes.add(ClassIdGenerator.Class(self, name))

	def remove_classes(self, names):
		print(repr(names))
		self.classes = set([c for c in self.classes if not c.name in names])

	def strip_comments(text):
		class State:
			pass

		def strip_between_markers(text, start_marker, end_marker):
			State.NOT_IN_COMMENT = State()
			State.IN_COMMENT = State()
			State.BAD = State()

			pos = 0
			start = re.compile(start_marker)
			end = re.compile(end_marker)
			state = State.NOT_IN_COMMENT
			last_comment_end = 0
			start_end_pairs = []

			while state != State.BAD:

				if state == State.NOT_IN_COMMENT:
					result = start.search(text, pos)
					if result:
						state = State.IN_COMMENT
						start_end_pairs.append((last_comment_end, result.start()))
						pos = result.end()
					else:
						state = State.BAD

				elif state == State.IN_COMMENT:
					result = end.search(text, pos)
					if result:
						state = State.NOT_IN_COMMENT
						pos = result.end()
						last_comment_end = result.end()
					else:
						state = State.BAD

			start_end_pairs.append((last_comment_end, len(text)))
			return functools.reduce(operator.add, [text[start:end] for (start, end) in start_end_pairs], "")
		return strip_between_markers(strip_between_markers(text, r'/\*', r'\*/'), r'//', r'\n')

	def parse_file(self, source_file):
		file = open(source_file)
		file_text = functools.reduce(operator.add, file.readlines(), "")
		file.close()

		file_text = ClassIdGenerator.strip_comments(file_text)

		for match in self.regex.finditer(file_text):
			match_dict = match.groupdict()
			next_class_name = match_dict['class_name']
			next_class_id = match_dict['classId']
			if next_class_name:
				self.add_class(next_class_name)

#			for i in range(len(match.groups())):
#				print(str(i) + " " + str(match.group(i)))

#			if match.groups(

	def write_includes(self, out_stream):
		write = out_stream.write
		write('//Including all headers\n')
		for _class in self.classes:
			write(''.join(['#include "', _class.name, '.hpp"\n']))
		write('\n')

	def write_class_declarations(self, out_stream):
		write = out_stream.write
		write('//declaring classes\n')
		for _class in self.classes:
			write(''.join(['class ', _class.name, ';\n']))
		write('\n')

	def write_class_to_id_map(self, out_stream):
		write = out_stream.write
		write('//Specialized templates for classes -> ids\n')
		for _class in self.classes:
			write(''.join(['template <> class ClassToId<', _class.name, '> { public: enum { id = ', str(_class.id), '}; };\n']))
		write('\n')

	def write_id_to_class_map(self, out_stream):
		write = out_stream.write
		write('//Specialized templates for ids -> classes\n')
		for _class in self.classes:
			write(''.join(['template <> class IdToClass<', str(_class.id), '> { public: typedef ', _class.name, ' type; };\n']))
		write('\n')

	def write_id_to_class_macro(self, out_stream):
		write = out_stream.write
		write('//macro that makes a switch statement for each template\n')
		write('#define ID_TO_CLASS_DECODE(id,pre_command,post_command) \\\n\tswitch(id)\\\n\t{\\\n')
		for _class in self.classes:
			write(''.join(['\tcase ClassToId<', _class.name, '>::id:\\\n\t\tpre_command<', _class.name, '>post_command\\\n']))
		write('}\n')

if __name__ == "__main__":
	generator = ClassIdGenerator()

	try:
		with open('ClassId.include') as fp:
			for line in fp:
				generator.add_class(line)

			fp.close()
	except IOError as error:
		print("Could not open ClassId.include...")
		raise error

	out_stream = open('ClassId.cc', 'w')
	out_stream.write('//This is an auto-generated file. Any changes in this file will be lost!\n\n')
	out_stream.write('//This file contains a mapping from Classes to ids using template specialization\n//ClassToId<ClassName>::id\n\n')
	out_stream.write('\n')

	def generate(filename):
		return generator.parse_file(filename)

#	recurse_dir(".", generate, ['.svn'])
#
#	try:
#		with open('ClassId.ignore') as fp:
#			generator.remove_classes(list(map(lambda s: s.strip(), fp.readlines())))
#
#			fp.close()
#	except IOError as error:
#		print("Could not open ClassId.ignore...ignoring user hard coded classes to ignore.")

	out_stream.write('//ClassId.cpp generation begins\n')
	generator.write_includes(out_stream)
	generator.write_class_to_id_map(out_stream)
	generator.write_id_to_class_map(out_stream)
	generator.write_id_to_class_macro(out_stream)
	out_stream.write('//ClassId.cpp generation ends\n')
	out_stream.close()


# -*- coding: UTF-8 -*-
"""
:Script:   Field_Calculator_defs.py
:Author:   Dan.Patterson@carleton.ca
:Created:  2013-??-??
:Modified: 2016-09-17
:Purpose: demonstration functions that can be used in the field calculator
:Useage:
:  copy the function into the code block and put in the suggested format
:  into the expression box...modify that to reflect your field names and/or
:  required input values
:Tips:
:  some people use the __esri_field_calculator_splitter__ within their scripts
:  to separate the def from the expression box.
:
"""
import sys
import arcpy

# Simple no code block examples
"""
- simple comparison and reclass
  " True condition " if !some_field! == "some_value" else " False condition "
  "Agricultural 10 Acres" if !Zone! == "A-10" else "False"

- compound comparisons and reclass
  "True" if !some_field! < "some_value"
         else ("other value" if !some_field! == "final_value" else "False")
  "True" if !Random! < 5 else ("sort of" if !Random! == 5 else "False")

- geometry related
  5000m along polygons and polylines
  x = !Shape!.boundary().positionAlongLine(5000,False).centroid.X  # polygons
  y = !Shape!.boundary().positionAlongLine(5000,False).centroid.Y  # polygons

  x = !Shape!.positionAlongLine(5000,False).centroid.X  #for polylines
  y = !Shape!.positionAlongLine(5000,False).centroid.Y  #for polylines

  x = !Shape!.positionAlongLine(0.25,True).centroid.X  # polylines
  y = !Shape!.positionAlongLine(0.25,True).centroid.Y  # polylines
  pnt_num = !Shape!.pointCount - !Shape!.partCount
          # number of vertices in a polygon

"""
# Imports  normally they are handled within the def to remind people

print("\nScript location...since I always forget... {}".format(sys.argv[0]))

# ----- Code block section -----

# (1) no_nulls_allowed([!a!, !b!, !c!...])

def no_nulls_allowed(fld_list):
    """provide a list of fields"""
    good_stuff = []
    for i in fld_list:
        if i:
            good_stuff.append(str(i))
        out_str = " ".join(good_stuff)
    return out_str

def no_nulls_mini(fld_list):
    ok_flds = [str(i) for i in fld_list if i]
    return ("{} "*len(ok_flds)).format(*ok_flds)

# (2) Conversions

"""field name, extracts numbers from the beginning of a string until
a non-numeric entry is reached, otherwise None
extract_int(field_name)   extract the integer from the front of a string
"""

import itertools
def extract_int(field_name):
    try:
        return int("".join(itertools.takewhile(str.isdigit, str(field_name))))
    except:
        pass

"""-----------------------------------------
field name, extracts integers from a string
extract_nums(field_name)   extracts all numbers from a string
"""
def extract_nums(field_name):
    numbers = []
    for i in field_name:
        try:
            val = int(i)
            numbers.append(str(val))
        except ValueError:
            break
    return int("".join(numbers))

"""-----------------------------------------
field name, strips numbers from a string
strip_num(field_name)   strips all numbers from a string
"""
####add string data digits, letters, printable punctuation etc
import string
def strip_num(field_name):
    for i in string.digits:
        field_name = field_name.replace(i,"")
    return field_name

# (3) Comparisons

"""-----------------------------------------
field name, threshold value in the code block, modify expression to suite,
if_elif_else(!test_fld!,5)    modify the code within the return section
"""
def if_elif_else(field_name, value):
    if field_name <= value:
        return value     # ie (1.0 + (field_name/2.0))
    elif field_name <= 10:
        return value     # ie (1.5 + 2*((field-1)/24.0))
    else:
        return value     # ie (max(5.0, 3.5+((field-25)/15.0)))

"""-----------------------------------------
field name, threshold value in the code block, modify expression to suite,
returns 0, 1
greaterThan( !Y_UTM!, 5000000)  copy to the expression box and modify to suit
"""
def greaterThan(field_name,value):
    if field_name >= value:
        return True
    else:
        return False

"""-----------------------------------------
field name, threshold value in the code block, modify expression to suite,
returns 0, 1
lessThan( !Y_UTM!, 500000)  copy to the expression box and modify to suit
"""
def lessThan(field_name,value):
    if field_name <= value:
        return True
    else:  return False

#Others
"""return a text value for nulls in a text field
replaceNull(!some_field!,"'TextValue')   """
def replaceNull(field_name,value):
    if field_name is None:
        return value
    else:
        return field_name

"""-----------------------------------------
return a text value with a word removed by index number
remove_part(!textFld!,0," ")
"""
def remove_part(field_name,index=-1,sep=" "):
    a_list = field_name.split(sep)
    out_str = ""
    if abs(index) <= len(a_list):
        a_list.pop(index)
        for i in a_list:
            out_str += (i + " ")
    return out_str.rstrip()

"""------------------------------------------
Label grid cells like excel
"""
import string
c = -1
r = 0

def code_grid(rows=1, cols=1):
    global c, r
    c += 1
    UC = list(string.ascii_uppercase)
    if c >= cols:
        c = 0
        r += 1
    label = UC[c] + str(r)
    return label

# (4) Date-time

# arcpy.time.ParseDateTimeString(!FIELD1!) + datetime.timedelta(hours=1)
# arcpy.time.ParseDateTimeString(!FIELD1!) + datetime.timedelta(days=1)

import datetime

#datetime.datetime.now() + datetime.timedelta(days=1)

#Math related

""" -----------------------------------------
Return a random number in the range 0-1
randomNum()  #enter into the expression box
"""
import numpy
def randomNum():
    return numpy.random.random()

"""-----------------------------------------
Return a random number integer in the range start, end
randomInt(0,10)   #enter into the expression box
"""
import numpy
def randomInt(start, end):
    return numpy.random.randint(start, end)

"""-----------------------------------------
Return the cumulative sum of a field
cumulative(field_name)  # enter into the expression box
"""
old = 0   # include this line
def cumulative(new):
    '''accumulate values'''
    global old
    if old >= 0:
        old = old + new
    else:
        old = new
    return old

#  or

total = 0
def cumsum(in_field):
    global total
    total += in_field
    return total

"""-----------------------------------------
geometric mean   not done yet
"""
import operator
def geometric_mean(iterable):
    return (reduce(operator.mul, iterable)) ** (1.0/len(iterable))

#Geometry related

#--Counts
"""-----------------------------------------
Input shape field, return number of parts
count_parts(!Shape!)    #enter into the expression box
"""
def count_parts(shape):
    return shape.partCount

"""-----------------------------------------
Input shape field, return number of points in a feature
count_pnts(!Shape!)     #enter into the expression box
"""
def count_pnts(shape):
    counter = 0
    num_parts = shape.partCount
    num_pnts = 0
    while counter < num_parts:
        part = shape.getPart(counter)
        pnt = part.next()
        while pnt:
            num_pnts += 1
            pnt = part.next()
            if not pnt:
                pnt = part.next()
        counter += 1
    return num_pnts

# -- Point features ----------------------------------------
#  References
#     https://geonet.esri.com/message/557195#557195
#     https://geonet.esri.com/message/557196#557196

"""-----------------------------------------
dist_to(shape, from_x, from_y)
input:      shape field, origin x,y
returns:    distance to the specified point
expression: dist_to(!Shape!, x, y)
"""

def dist_to(shape, from_x, from_y):
    x = shape.centroid.X
    y = shape.centroid.Y
    distance = math.sqrt((x - from_x)**2 + (y - from_y)**2)
    return distance

""" -----------------------------------------
dist_between(shape)
input:      shape field
returns:    distance between successive points
expression: dist_between(!Shape!)
"""

x0 = 0.0
y0 = 0.0

def dist_between(shape):
    global x0
    global y0
    x = shape.centroid.X
    y = shape.centroid.Y
    if x0 == 0.0 and y0 == 0.0:
        x0 = x
        y0 = y
    distance = math.sqrt((x - x0)**2 + (y - y0)**2)
    x0 = x
    y0 = y
    return distance

"""-----------------------------------------
dist_cumu(shape)
input:      shape field
returns:    cumulative distance between points
expression: dist_cumu(!Shape!)
"""

x0 = 0.0
y0 = 0.0
distance = 0.0
def dist_cumu(shape):
    global x0
    global y0
    global distance
    x = shape.firstpoint.X
    y = shape.firstpoint.Y
    if x0 == 0.0 and y0 == 0.0:
        x0 = x
        y0 = y
    distance += math.sqrt((x - x0)**2 + (y - y0)**2)
    x0 = x
    y0 = y
    return distance

"""-----------------------------------------
azimuth_to(shape, from_x, from_y)
input:      shape field, from_x, from_y
returns:    angle between 0 and <360 between a specified point and others
expression: azimuth_to(!Shape!, from_x, from_y)
"""
def azimuth_to(shape, from_x, from_y):
    x = shape.centroid.X
    y = shape.centroid.Y
    radian = math.atan((x - from_x)/(y - from_y))
    degrees = math.degrees(radian)
    if degrees < 0:
        return degrees + 360.0
    else:
        return degrees

"""-----------------------------------------
angle_between(shape)
input:      shape field
returns:    angle between successive points,
            NE +ve 0 to 90, NW +ve 90 to 180,
            SE -ve <0 to -90, SW -ve <-90 to -180
expression: angle_between(!Shape!)
"""
x0 = 0.0;  y0 = 0.0;  angle = 0.0
def angle_between(shape):
    global x0
    global y0
    x = shape.centroid.X
    y = shape.centroid.Y
    if x0 == 0.0 and y0 == 0.0:
        x0 = x
        y0 = y
        return 0.0
    radian = math.atan2((y - y0),(x - x0))
    angle = math.degrees(radian)
    x0 = x
    y0 = y
    return angle

#--Polyline features

"""-----------------------------------------
Input shape field: simple shape length
poly_length(!Shape!)    #enter into the expression box
"""
def poly_length(shape):
    return shape.length

"""-----------------------------------------
Input shape field: returns cumulative length of polylines connected or not
poly_cumu_len(!Shape!)    #enter into the expression box
"""
length = 0.0
def poly_cumu_len(shape):
    global length
    length += shape.length
    return length

"""-----------------------------------------
Input shape field: returns angle between 0 and <360 based upon the first and last point
azimuth_to(!Shape!,from_x, from_y)  # ie azimuth_to(!Shape!,339200, 5025200)
"""
import math
def azimuth_to(shape, from_x, from_y):
    x = shape.centroid.X
    y = shape.centroid.Y
    radian = math.atan2((y - from_y), (x - from_x))
    degrees = math.degrees(radian)
    if degrees < 0:
        return  degrees + 360
    return degrees

"""-----------------------------------------
Input shape field, value (distance or decimal fraction, 0-1),
    use_fraction (True/False), XorY (X or Y):
Returns a point x meters or x  decimal fraction along a line,
   user specifies whether X or Y coordinates
pnt_along(!Shape!, 100, False, 'X')  # eg. X coordinate 100 m from start point
"""
def pnt_along(shape, value, use_fraction, XorY):
    XorY = XorY.upper()
    if use_fraction and (value > 1.0):
        value = value/100.0
    if shape.type == "polygon":
        shape = shape.boundary()
    pnt = shape.positionAlongLine(value, use_fraction)
    if XorY == 'X':
        return pnt.centroid.X
    else:
        return pnt.centroid.Y

# --Polygon

# --Shapes in general
##def shape_shift(shape,dX=0,dY=0):
##    """ shape_shift(!Shape!,0,0)
##    __esri_field_calculator_splitter__
##    shift/move/translate a shape by dX,dY
##    """
##    pnt = shape.firstPoint.X #.centroid
##    #pnt.X += pnt.X + dX
##    #pnt.Y = pnt.Y + dY
##    return pnt
import arcpy

def shift_features(in_features, x_shift=None, y_shift=None):
    """
    Shifts features by an x and/or y value. The shift values are in
    the units of the in_features coordinate system.

    Parameters:
    in_features: string
        An existing feature class or feature layer.  If using a
        feature layer with a selection, only the selected features
        will be modified.

    x_shift: float
        The distance the x coordinates will be shifted.

    y_shift: float
        The distance the y coordinates will be shifted.
    """

    with arcpy.da.UpdateCursor(in_features, ['SHAPE@XY']) as cursor:
        for row in cursor:
            cursor.updateRow([[row[0][0] + (x_shift or 0),
                               row[0][1] + (y_shift or 0)]])

    return

# shape_shift(!SHAPE@!,0,0)

# formatting
"""partition a string or number into parts in a text field
!field_name!   in the expression box"""
def partition(field_name):
    a = str(field_name)
    return "{0[0]}+{0[1]}".format(a.partition(a[3:]))

#field_name=602300
#print frmt(field_name)


"""non nullable fields

Revision ID: e0688a829fc9
Revises: 31d8f37a2e74
Create Date: 2021-01-13 19:00:18.594311

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision = 'e0688a829fc9'
down_revision = '31d8f37a2e74'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('item', 'name',
               existing_type=sa.VARCHAR(length=256),
               nullable=False)
    op.alter_column('item', 'price',
               existing_type=postgresql.DOUBLE_PRECISION(precision=53),
               nullable=False)
    op.alter_column('item', 'store_id',
               existing_type=sa.INTEGER(),
               nullable=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.alter_column('item', 'store_id',
               existing_type=sa.INTEGER(),
               nullable=True)
    op.alter_column('item', 'price',
               existing_type=postgresql.DOUBLE_PRECISION(precision=53),
               nullable=True)
    op.alter_column('item', 'name',
               existing_type=sa.VARCHAR(length=256),
               nullable=True)
    # ### end Alembic commands ###


# Script to collect Z80 execution data using a BusRaider
import time, datetime, json, logging, os
from SimpleHDLC import HDLC
from SimpleTCP import SimpleTCP
import argparse

class Tracer:

    # Start trace
    def start(self):
        # Setup
        self.setup(args.busRaiderIPAddr, "", args.logFileName)

        # Stop any previous tracer
        self.sendFrame("tracerStop", b"{\"cmdName\":\"tracerStop\"}\0")

        # Set machine
        self.sendFrame("SetMachine", b"{\"cmdName\":\"setMcJson\"}\0"+b"{\"name\":\"" + bytes(machineName, 'utf-8') + b"\",\"hw\":[],\"emulate6850\":{}}\0")
        time.sleep(2)

        # Bus reset
        self.sendFrame("busInit", b"{\"cmdName\":\"busInit\"}\0")
        time.sleep(1)

        # Start tracer with recording (dense binary records) turned on (logging should be off as this creates verbose text log)
        self.sendFrame("tracerStart", b"{\"cmdName\":\"tracerStart\",\"logging\":0,\"record\":1}\0")

        # Start message
        timeStart = datetime.datetime.now()
        self.logger.info(f"Execution trace started at {str(timeStart)}")

        # Run the trace
        self.awaitingTraceResponse = False
        for i in range(10):
            j = 0
            while self.awaitingTraceResponse and j < 2000:
                time.sleep(0.001)
                j += 1
            if j >= 2000:
                break
            self.sendFrame("tracerGetLong", b"{\"cmdName\":\"tracerGetBin\"}\0")
            self.awaitingTraceResponse = True
            time.sleep(0.01)

        # Calculate rate
        timeEnd = datetime.datetime.now()
        elapsed = (timeEnd - timeStart).total_seconds()
        if elapsed > 0 and not self.instrCountAtStart is None:
            instrCount = self.curInstructionCount - self.instrCountAtStart
            self.logger.info(f"{instrCount} instructions in {elapsed:.2f} secs => {instrCount/elapsed:.1f} per second {self.instructionsSkipped} lost")

        # Stop tracing
        self.cleardown()

    def cleardown(self):
        # Clear down
        try:
            self.rdpTCP.stopReader()
        except Exception as excp:
            self.logger.error(f"{excp}")
        if self.dumpTraceFile:
            self.dumpTraceFile.close()

    # Handle received messages
    def frameCallback(self, msgContent, binContent, logger):
        if (msgContent['cmdName'] == "tracerGetBinData") and (not self.dumpTraceFile is None):
            # Traced bus access contents
            dataCount = msgContent['dataLen'] // self.sizeOfTraceBinElem
            traceCount = msgContent['traceCount']
            # Check if any bus accesses lost in communication
            if self.curInstructionCount != traceCount:
                self.instructionsSkipped += traceCount - self.curInstructionCount
            # For calculating rate
            if self.instrCountAtStart is None:
                self.instrCountAtStart = traceCount
            self.curInstructionCount = traceCount + dataCount
            elemPos = 0
            # Extract the data, format and write to file
            for i in range(dataCount):
                dataStr = self.formatTraceBinElem(binContent, elemPos, traceCount)
                elemPos += self.sizeOfTraceBinElem
                traceCount += 1
                self.dumpTraceFile.write(dataStr + "\n")
            self.awaitingTraceResponse = False

    # Format for trace dumping
    def formatTraceBinElem(self, binContent, contentPos, traceCount):
        addr = binContent[contentPos] + (binContent[contentPos+1]*256)
        busData = binContent[contentPos+2]
        retData = binContent[contentPos+3]
        flags = binContent[contentPos+4]
        outData = f"{traceCount:08d} {addr:04x} {busData:02x} {self.formatFlags1(flags)}{self.formatFlags2(flags)}"
        if (flags & 0x80) != 0:
              outData += f"{retData:02x}"
        return outData

    def formatFlags1(self, busFlags):
        return self.flags1[(busFlags >> 3) & 0x03]

    def formatFlags2(self, busFlags):
        return self.flags2[busFlags & 0x07]

    # Send frame to BusRaider
    def sendFrame(self, comment, content):
        frame = bytearray(content)
        self.hdlcHandler.sendFrame(frame)

    # HDLC Frame handler
    def onHDLCBinFrame(self, fr):
        msgContent = {'cmdName':''}
        try:
            # Split string - the format is a JSON string terminated with NULL then
            # a binary section to the end of the buffer
            nullPos = fr.find(b"\0")
            binContent = b""
            if nullPos >= 0:
                jsonStr = fr[:nullPos].decode('utf-8').rstrip('\0')
                msgContent = json.loads(jsonStr)
                binContent = fr[nullPos+1:]
            else:
                jsonStr = fr.decode('utf-8').rstrip('\0')
                msgContent = json.loads(jsonStr)
        except Exception as excp:
            self.logger.error(f"Failed to parse Json from {fr}, {excp}")
        try:
            # All messages should contain cmdName to identify message type
            if 'cmdName' in msgContent:
                if msgContent['cmdName'] == "log":
                    # Check for a log message from Pi
                    try:
                        self.logger.info(f"{msgContent['lev']} : {msgContent['src']} {msgContent['msg']}")
                    except Exception as excp:
                        self.logger.error(f"LOG CONTENT NOT FOUND IN FRAME {fr}, {excp}")
                else:
                    self.frameCallback(msgContent, binContent, self.logger)
        except Exception as excp:
            self.logger.error(f"Failed to extract cmdName from {msgContent} frame {fr}, {excp}")

    # Check for using IP address
    def setup(self, ipAddrOrHostName, fileBase, dumpTraceFileName):

        # Format of trace binary element
        self.sizeOfTraceBinElem = 5
        self.flags1 = ("..",".I","1.","1I")
        self.flags2 = ("...","..R",".W.",".WR","M..","M.R","MW.","MWR")

        # Instruction timing
        self.instrCountAtStart = None
        self.curInstructionCount = 0
        self.instructionsSkipped = 0

        # Logging
        self.logger = logging.getLogger(__name__)
        self.logger.setLevel(logging.DEBUG)
        consoleLogger = logging.StreamHandler()
        consoleLogger.setLevel(logging.DEBUG)
        consoleLogger.setFormatter(logging.Formatter('%(asctime)s: %(message)s'))
        self.logger.addHandler(consoleLogger)

        # Open trace file
        self.dumpTraceFile = None
        try:
            if dumpTraceFileName is not None and len(dumpTraceFileName) > 0:
                self.dumpTraceFile = open(os.path.join(fileBase, dumpTraceFileName), "w")
        except Exception as excp:
            self.logger.warning("Can't open dump trace file " + os.path.join(fileBase, dumpTraceFileName))

        # HDLC port
        self.tcpHdlcPort = 10001

        # Callback to send to TCP
        def sendDataToTCP(dataToSend):
            self.rdpTCP.sendFrame(dataToSend)

        # Frame handler
        def onTCPFrame(fr):
            # Send to HDLC
            self.hdlcHandler.processBytes(fr)

        # TCP Reader
        self.rdpTCP = SimpleTCP(ipAddrOrHostName, self.tcpHdlcPort)
        self.rdpTCP.startReader(onTCPFrame)

        # Setup HDLC
        self.hdlcHandler = HDLC(None, sendDataToTCP, None)
        self.hdlcHandler.setCallbacks(None, self.onHDLCBinFrame)

        # Welcome
        self.logger.info(f"UnitTest BusRaider IP {ipAddrOrHostName} port {self.tcpHdlcPort}")

if __name__ == "__main__":

    # Handle arguments
    argparser = argparse.ArgumentParser(description='Trace Execution')
    argparser.add_argument('busRaiderIPAddr', action='store')
    argparser.add_argument('machine', choices=['ANSI', 'H19', 'TRS80', 'Spectrum', 'Robs'], action='store')
    argparser.add_argument('preloadProgram', action='store')
    argparser.add_argument('testProgram', action='store')
    argparser.add_argument('logFileName', action='store')
    args = argparser.parse_args()

    # Full machine name
    if args.machine == 'ANSI':
        machineName = "Serial Terminal ANSI"
    elif args.machine == 'H19':
        machineName = "Serial Terminal H19"
    elif args.machine == 'TRS80':
        machineName = "TRS80"
    elif args.machine == 'Spectrum':
        machineName = "ZX Spectrum"
    elif args.machine == 'Robs':
        machineName = "Rob's Z80"

    # Create and start the tracer
    tracer = Tracer()
    tracer.start()


import torch
import torchvision
import torchvision.transforms as transforms
import os
from datetime import datetime
from local_dataset.face2comic import Face2ComicDataset

def mkdir(dir):
    if os.path.exists(dir):
        return
    else:
        os.makedirs(dir)

def make_dirs(args, prefix, now=None):
    if now is None:
        now = datetime.now().strftime("%Y-%m-%dT%H-%M-%S")

    if args.load_model:
        # 如果加载已有的模型，则继续保存在指定的文件夹下
        root_path = os.path.join(args.load_path)
    else:
        root_path = os.path.join(args.output_path, prefix, now)

    log_path = os.path.join(root_path, "log")
    mkdir(log_path)
    model_path = os.path.join(root_path, "model")
    mkdir(model_path)
    image_path = os.path.join(root_path, "images")
    mkdir(image_path)
    sample_path = os.path.join(root_path, "samples")
    mkdir(sample_path)
    return image_path, model_path, log_path, sample_path, now

def get_optimizer(optim_config, parameters):
    if optim_config.optimizer == 'Adam':
        return torch.optim.Adam(parameters, lr=optim_config.lr, weight_decay=optim_config.weight_decay,
                                betas=(optim_config.beta1, 0.999))
    elif optim_config.optimizer == 'RMSProp':
        return torch.optim.RMSprop(parameters, lr=optim_config.lr, weight_decay=optim_config.weight_decay)
    elif optim_config.optimizer == 'SGD':
        return torch.optim.SGD(parameters, lr=optim_config.lr, momentum=0.9)
    else:
        return NotImplementedError('Optimizer {} not understood.'.format(optim_config.optimizer))

def get_dataset(dataset_config):
    trans = transforms.Compose([
        transforms.Resize(dataset_config.image_size),
        transforms.ToTensor()
    ])

    train_dataset, test_dataset = None, None
    if dataset_config.dataset == 'face2comic':
        train_dataset = Face2ComicDataset('train', (dataset_config.image_size, dataset_config.image_size))
        test_dataset = Face2ComicDataset('test', (dataset_config.image_size, dataset_config.image_size))
    elif dataset_config.dataset == 'MNIST':
        train_dataset = torchvision.datasets.MNIST(root="./data", train=True, transform=trans, download=True)
        test_dataset = torchvision.datasets.MNIST(root="./data", train=False, transform=trans, download=True)
    elif dataset_config.dataset == 'FashionMNIST':
        train_dataset = torchvision.datasets.FashionMNIST(root="./data", train=True, transform=trans, download=True)
        test_dataset = torchvision.datasets.FashionMNIST(root="./data", train=False, transform=trans, download=True)

    return train_dataset, test_dataset


import random
n=[]
c=0
def makeno():
    while len(n)<4:
        x = random.randrange(0,9)
        if x not in n:
            n.append(x)
    #for i in range(4):
     #   x=random.randrange(0,9)
     #   n.append(x)
    print(n)

if len(n)>len(set(n)):
    n.clear()
    makeno()
def playgame():
    global c
    c+=1
    cows=0
    bulls=0
    #print(n)
    choice=input("enter no a 4 digit no")
    guess=[]
    for i in range(4):
        guess.append(int(choice[i]))
    for i in range(4):
        for j in range(4):
            if guess[i]==n[j]:
               cows+=1
    for x in range (4):
        if guess[x]==n[x]:
           bulls+=1
    print("bulls:",bulls)
    print("cows:",cows)
    if bulls==4:
       print("you won win ",c,"c")
    #if bulls!=4:
    else:
        print("you looser")
        playgame()
makeno()
playgame()


# -*- coding: utf-8 -*-
"""
Created on Sun Apr  6 17:14:22 2014

@author: Mike
"""

from pandas import *
import numpy as np
from matplotlib import pyplot as plt

def plot_weather_data(filepath):
    data = read_csv(filepath)
    x = data['Hour']
    y = data['ENTRIESn_hourly']

    fig = plt.figure()
    ind = np.arange(len(y))
    plt.bar(x, y)
    return plt


import os
import shlex
import subprocess
import sys
import threading
import traceback
from queue import Queue

import pandas as pd

from logger import logger
from config import config
from engine import GtpEngine

engine_config = config["LOCAL"]
USER_FOLDER = engine_config.get("katago_folder")

class LocalEngine(GtpEngine):
    """Starts and communicates with the KataGo gtp engine"""

    def __init__(self) -> None:
        self.engine_id = str(0)
        self.katago_process = None

        self.command_queue = Queue()
        self.read_katago_thread = None
        self.command_loop_thread = None
        self._lock = threading.Lock()
        self.shell = False

        self.logger = logger
        self.analysis = None

        self.set_command()

    def set_command(self):
        exe_file = engine_config.get("exe", "katago.exe")
        exe = os.path.expanduser(os.path.join(USER_FOLDER, exe_file))

        gtp_cfg_file_name = engine_config.get("gtp_config_file")
        gtp_cfg_file = os.path.expanduser(os.path.join(USER_FOLDER, gtp_cfg_file_name))

        model_name = engine_config.get("model", "b40.bin.gz")
        model_file = os.path.expanduser(os.path.join(USER_FOLDER, model_name))

        self.command = shlex.split(
            f'"{exe}" gtp -model "{model_file}" -config "{gtp_cfg_file}"'
        )

    def start(self):
        try:
            self.logger.info(f"Starting {self.engine_id} with {self.command}")
            startupinfo = None
            if hasattr(subprocess, "STARTUPINFO"):
                startupinfo = subprocess.STARTUPINFO()
                # stop command box popups on win/pyinstaller
                startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
            self.katago_process = subprocess.Popen(
                self.command,
                startupinfo=startupinfo,
                stdin=subprocess.PIPE,
                stdout=subprocess.PIPE,
                stderr=subprocess.PIPE,
                shell=self.shell,
            )
        except Exception as e:
            self.logger.error(f"Starting {self.engine_id} failed: {e}")
            return
        self.read_katago_thread = threading.Thread(
            target=self._read_katago_thread, daemon=True
        )
        self.read_katago_thread.start()
        self.command_loop_thread = threading.Thread(
            target=self._command_loop_thread, daemon=True
        )
        self.command_loop_thread.start()

    def stop(self):
        command = "quit"
        self.send_command(command)
        self.katago_process = None
        self.logger.debug(f"stop engine {self.engine_id}.")

    def is_alive(self, os_error="", exception_if_dead=False) -> bool:
        ok = self.katago_process and self.katago_process.poll() is None
        if not ok and exception_if_dead:
            if self.katago_process:
                code = self.katago_process and self.katago_process.poll()
                if code == 3221225781:
                    self.logger.error("Engine missing DLL")
                else:
                    os_error += f"status {code}"
                    self.logger.error(f"Engine died unexpectedly, os error: {os_error}")
                self.katago_process = None
            else:
                self.logger.error(f"Engine died unexpectedly, os error: {os_error}")
        return ok

    def shutdown(self, finish=False):
        process = self.katago_process
        if process:
            self.katago_process = None
            process.terminate()
        if self.read_katago_thread:
            self.read_katago_thread.join()

    def _read_katago_thread(self):
        while self.is_alive():
            try:
                line: str = self.katago_process.stdout.readline().strip().decode()
            except OSError as e:
                self.logger.error(f"Can not read line: {e}")
                return

            if "Uncaught exception" in line:
                self.logger.error(f"Engine Failed: {line}")

            if not line:
                continue

            try:
                if "info move" in line:
                    self.analysis = self.analysis_to_df(line)
            except Exception as e:
                self.logger.error(
                    f"Unexpected exception {e} while processing Engine output {line[:20]}"
                )

    def send_command(self, command):
        try:
            self.katago_process.stdin.write(f"{command}\n".encode())
            self.katago_process.stdin.flush()
        except Exception as e:
            self.logger.error(f"Exception when sending command {command}, {e}")


import lz
from lz import *

fpath = work_path + 'reid/work.8.1'
fpath = osp.abspath(fpath)

def clean_empty():
    paths = glob.glob(fpath)
    for path in paths:
        size = os.stat(path).st_size
        # print(size)
        if size < 67:
            print(path, size)
            # shell(f'trash {path}')

clean_empty()
os.chdir((fpath))
paths = glob.glob('*')
assert len(paths) > 0, paths
# random.shuffle(paths)
res_dict = {}
cfg_dict = {}
cfgs = []
for path in paths:
    # name = args.logs_dir.split('/')[-1]
    name = path.split('/')[-1]
    print(name)
    # if 'only' in name: continue
    # if 'duke' not in name: continue
    # if 'cfisher' not in name or 'cu'  in name: continue
    # if 'tuning' not in name: continue
    # if not 'cu01' in name and not 'cuhk01' in name: continue

    assert osp.exists(path + '/conf.pkl'), path
    # if not osp.exists(path + '/conf.pkl'):
    #     continue
    args = pickle_load(path + '/conf.pkl')
    # if osp.exists(args.logs_dir + '/eval/res.json'):
    # res_path = args.logs_dir + '/eval/res.json'
    # else:
    args.logs_dir = fpath + '/' + osp.basename(osp.abspath(args.logs_dir))
    res_path = args.logs_dir + '/res.json'

    if not osp.exists(res_path):
        res, _ = shell(f'tail {osp.dirname(res_path)+"/log.txt"} -n 1')
        try:
            import json

            json.loads(res)
        except:
            continue
    else:
        # print(args.logs_dir)
        res = json_load(res_path)
    # print(args, res)
    res_dict[name] = res
    cfg_dict[name] = args
    cfgs.append(args)

df_acc = pd.DataFrame(res_dict).T
df_acc *= 100

def is_all_same(lst):
    lst = [lsti if not isinstance(lsti, np.ndarray) else lsti.tolist() for lsti in lst]
    res = [lsti == lst[0] for lsti in lst]
    # try:
    return np.asarray(res).all()
    # except Exception as e:
    #     print(e)

df = pd.DataFrame(cfgs)
if len(cfgs) == 1:
    raise ValueError
res = []
for j in range(df.shape[1]):
    if not is_all_same(df.iloc[:, j].tolist()):
        res.append(j)
res = [df.columns[r] for r in res]
df_cfg = df[res]

print(df_cfg.head())
df_cfg.index = df_cfg.logs_dir.str.replace(fpath, '').str.replace(osp.abspath(work_path + 'reid/work'), '').str.strip(
    '/')
print(df_cfg.head())
print(df_acc.head())
df_final = pd.concat((  df_cfg, df_acc), axis=1)
df_final = df_final[['top-1', 'top-5', 'top-10', 'mAP'] + list(df_final.keys())]
df_final.to_excel(work_path + 't.xlsx')
exit(0)

def f1(x):
    return r'%.2f' % x

t = df_acc[['top-1',
            'mAP',
            # 'top-5', 'top-10',
            ]]
print(t.to_latex(formatters=[f1, ] * 3))
# print(df[['top-1.rk',
#           # 'mAP.rk',
#           'top-5.rk','top-10.rk',
#           ]].to_latex(formatters=[f1, ] * 3))
# print(t)
# print(df[['top-1.rk',
#           # 'mAP.rk',
#           'top-5.rk','top-10.rk',
#           ]])


from turtle import Screen
import time
from snake import Snake
from food import Food
from scoreboard import ScoreBoard
from playside import PlaySide

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor("black")
screen.title("Snake Game")
screen.tracer(0)

playside = PlaySide()
snake = Snake()
food = Food()
scoreboard = ScoreBoard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right, "Right")

game_is_on = True
while game_is_on:
    screen.update()
    time.sleep(0.1)
    snake.snake_body_movement()

    if snake.snake_head.distance(food) < 15:
        food.spawn_food()
        scoreboard.point_obtained()
        snake.extend()

    if snake.snake_head.xcor() > 290 or snake.snake_head.xcor() < -290 or snake.snake_head.ycor() > 290 or snake.snake_head.ycor() < -290:
        scoreboard.reset()
        snake.reset()

    for segment in snake.snake_length[1:]:
        if snake.snake_head.distance(segment) < 10:
            game_is_on = False
            scoreboard.game_over()

screen.exitonclick()


import os, sys
from file import File
from pywinauto.application import Application

class MediaPlayer(object):

	def __init__(self, outputFileLocation):
		self.outputFileLocation = outputFileLocation
		self.playList = []
		self.app = Application()

	#adds a media file to the current playlist
	def addMedia(self, aFile):

		#make sure that aFile contains a valid file location
		try:
			if os.path.getsize(aFile.location) > 0:
				self.playList.append(aFile)
		except:
			pass

	#removes a file from the current playlist
	def removeMedia(self, aFile):
		self.playList.remove(aFile)

	#outputs the playlist to a file
	def toM3U(self):
		out = open(self.outputFileLocation, 'w')
		out.write("#EXTM3U\n\n")
		for mediaFile in self.playList:
			titleStr = "#EXTINF:-1, " + mediaFile.name + "\n"
			locStr = mediaFile.location + "\n\n"
			out.write(titleStr)
			out.write(locStr)

	#plays the current playlist
	def play(self):
		self.toM3U()
		connectionString = r"C:\Program Files\Windows Media Player\wmplayer.exe"
		connectionString += r" /play /fullscreen" + self.outputFileLocation
		self.app.start(connectionString)

	def stop(self):
		pass

if __name__ == '__main__':
	player = MediaPlayer( os.getcwd() + r"\selfTest.m3u")
	aFile = File()
	aFile.location = r"C:\WINDOWS\Media\tada.wav"
	aFile.name = "tada"
	player.addMedia(aFile)
	aFile = File()
	aFile.location = r"C:\WINDOWS\Media\chimes.wav"
	aFile.name = "chimes"
	player.addMedia(aFile)
	player.play()

"""
app["Windows Media Player"].TypeKeys("^u")

"""

topics/02 - scripting/windows automation/MediaPlayer.py