"""Insteon base entity."""
import logging

# import string

from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.const import CONF_VERIFY_SSL

# from homeassistant.helpers import device_registry as dr
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import CoordinatorEntity

from .const import DOMAIN, PACKAGE_NAME, _LOGGER, DEVICE_TYPE_BINARY_SENSOR, CONF_IGNORE_PLATFORM
from .vimarlink.vimarlink import VimarLink, VimarProject
from .vimar_coordinator import VimarDataUpdateCoordinator

class VimarEntity(CoordinatorEntity):
    """Vimar abstract base entity."""

    _logger = _LOGGER
    _logger_is_debug = False
    _device = []
    _device_id = 0
    _vimarconnection: VimarLink = None
    _vimarproject: VimarProject = None
    _coordinator: VimarDataUpdateCoordinator = None
    _attributes = {}

    ICON = "mdi:checkbox-marked"

    def __init__(self, coordinator: VimarDataUpdateCoordinator, device_id: int):
        """Initialize the base entity."""
        super().__init__(coordinator)
        self._coordinator = coordinator
        self._device_id = device_id
        self._vimarconnection = coordinator.vimarconnection
        self._vimarproject = coordinator.vimarproject
        self._reset_status()

        if self._device_id in self._vimarproject.devices:
            self._device = self._vimarproject.devices[self._device_id]
            self._logger = logging.getLogger(PACKAGE_NAME + "." + self.entity_platform)
            self._logger_is_debug = self._logger.isEnabledFor(logging.DEBUG)
        else:
            self._logger.warning("Cannot find device #%s", self._device_id)

        # self.entity_id = self._platform + "." + self.name.lower().replace(" ", "_") + "_" + self._device_id

    @property
    def device_name(self):
        """Return the name of the device."""
        name = self._device["device_friendly_name"]
        if name is None:
            name = self._device["object_name"]
        return name

    @property
    def name(self):
        """Return the name of the device."""
        return self.device_name

    @property
    def extra_state_attributes(self):
        """Return device specific state attributes."""
        # see: https://developers.home-assistant.io/docs/dev_101_states/
        # mostro gli attributi importati da vimar
        if self._device is not None:
            for key in self._device:
                value = self._device[key]
                if self._logger_is_debug is False and (
                    key == "status" or key == "device_class" or key == "device_friendly_name" or key == "vimar_icon"
                ):
                    # for status_name in value:
                    #    deviceItem["state_" + status_name.replace("/", "_").replace(" ", "_")] = value[status_name]["status_value"]
                    continue
                self._attributes["vimar_" + key] = value
        return self._attributes

    def request_statemachine_update(self):
        """Update the hass status."""
        # with polling, we need to schedule another poll request
        self.async_schedule_update_ha_state()
        # if not self.should_poll:
        #     # with the central update coordinator, we do this
        #     self._coordinator.async_request_refresh()

    # def change_state(self, state: str, value: str,  *args):
    def change_state(self, *args, **kwargs):
        """Change state on bus system and the local device state."""
        state_changed = False
        if "status" in self._device and self._device["status"]:

            if args and len(args) > 0:
                iter_args = iter(args)
                for state, value in zip(iter_args, iter_args):
                    if state in self._device["status"]:
                        state_changed = True
                        optionals = self._vimarconnection.get_optionals_param(state)
                        self.hass.async_add_executor_job(
                            self._vimarconnection.set_device_status,
                            self._device["status"][state]["status_id"],
                            str(value),
                            optionals,
                        )
                        self._device["status"][state]["status_value"] = str(value)
                    else:
                        self._logger.warning(
                            "Could not find state %s in device %s - %s - could not change value to: %s",
                            state,
                            self.name,
                            self._device_id,
                            value,
                        )

            if kwargs and len(kwargs) > 0:
                for state, value in kwargs.items():
                    if state in self._device["status"]:
                        state_changed = True
                        optionals = self._vimarconnection.get_optionals_param(state)
                        self.hass.async_add_executor_job(
                            self._vimarconnection.set_device_status,
                            self._device["status"][state]["status_id"],
                            str(value),
                            optionals,
                        )
                        self._device["status"][state]["status_value"] = str(value)
                    else:
                        self._logger.warning(
                            "Could not find state %s in device %s - %s - could not change value to: %s",
                            state,
                            self.name,
                            self._device_id,
                            value,
                        )

            if state_changed:
                self.request_statemachine_update()

        # TODO - call async_add_executor_job with asyncio.gather maybe?

    def get_state(self, state):
        """Get state of the local device state."""
        if self.has_state(state):
            return self._device["status"][state]["status_value"]
        else:
            self._logger.warning(
                "Could not find state %s in device %s - %s - could not get value", state, self.name, self._device_id
            )
        return None

    def has_state(self, state):
        """Return true if local device has a given state."""
        if "status" in self._device and self._device["status"] and state in self._device["status"]:
            return True
        else:
            return False

    @property
    def icon(self):
        """Icon to use in the frontend, if any."""
        if isinstance(self._device["icon"], str):
            return self._device["icon"]
        elif isinstance(self._device["icon"], list):
            return (self._device["icon"][1], self._device["icon"][0])[self.is_default_state]

        return self.ICON

    @property
    def device_class(self):
        """Return the class of this device, from component DEVICE_CLASSES."""
        return self._device["device_class"]

    @property
    def unique_id(self):
        """Return the ID of this device."""
        # self._logger.debug("Unique Id: " + DOMAIN + '_' + self._platform + '_' + self._device_id + " - " + self.name)
        prefix = self._coordinator.entity_unique_id_prefix or ""
        if len(prefix) > 0:
            prefix += "_"
        return DOMAIN + "_" + prefix + self.entity_platform + "_" + self._device_id

    def _reset_status(self):
        """Set status from _device to class variables."""

    @property
    def is_default_state(self):
        """Return True of in default state - resulting in default icon."""
        return False

    @property
    def device_info(self):
        room_name = None
        if self._device.get("room_friendly_name") and self._device["room_friendly_name"] != "":
            room_name = self._device["room_friendly_name"]
        return {
            "identifiers": {(DOMAIN, self._coordinator.entity_unique_id_prefix or "", self._device_id)},
            "name": self.device_name,
            "model": self._device.get("object_type"),
            "manufacturer": "Vimar",
            "suggested_area": room_name,
        }

    @property
    def entity_platform(self):
        """Return device_type (platform overrrided in sensor class)"""
        return self._device["device_type"]

    def get_entity_list(self) -> list:
        """return entity as list for async_add_devices, method to override if has multiple attribute, as sensor"""
        return [self]

class VimarStatusSensor(BinarySensorEntity):
    """Representation of a Sensor."""

    _coordinator: VimarDataUpdateCoordinator = None

    def __init__(self, coordinator: VimarDataUpdateCoordinator):
        """Initialize the sensor."""
        self._coordinator = coordinator
        vimarconfig = coordinator.vimarconfig
        self._name = (
            "Vimar Connection to "
            + str(coordinator.vimarconnection._host)
            + ":"
            + str(coordinator.vimarconnection._port)
        )
        self._type = "connectivity"
        self._attributes = {
            "Host": coordinator.vimarconnection._host,
            "Port": coordinator.vimarconnection._port,
            "Secure": coordinator.vimarconnection._schema == "https",
            "Verify SSL": coordinator.vimarconnection._schema == "https" and vimarconfig.get(CONF_VERIFY_SSL),
            "Vimar Url": "%s://%s:%s"
            % (
                coordinator.vimarconnection._schema,
                coordinator.vimarconnection._host,
                coordinator.vimarconnection._port,
            ),
            "Certificate": coordinator.vimarconnection._certificate,
            "Username": coordinator.vimarconnection._username,
            "SessionID": coordinator.vimarconnection._session_id,
        }
        self._data = self._attributes
        self._state = False

    @property
    def device_class(self):
        """Return the class of this sensor."""
        return self._type

    @property
    def should_poll(self):
        """Polling needed for a demo binary sensor."""
        return True

    @property
    def name(self):
        """Return the name of the binary sensor."""
        return self._name

    @property
    def unique_id(self):
        """Return the ID of this device."""
        # self._logger.debug("Unique Id: " + DOMAIN + '_' + self._platform + '_' + self._device_id + " - " + self.name)
        prefix = self._coordinator.entity_unique_id_prefix or ""
        if len(prefix) > 0:
            prefix += "_"
        return DOMAIN + "_" + prefix + "status"

    @property
    def device_state_attributes(self):
        """Return the state attributes of the sensor."""
        if self._data:
            return self._data
        else:
            return None

    @property
    def extra_state_attributes(self):
        """Return device specific state attributes."""
        return self._attributes

    @property
    def device_info(self):
        return {
            "identifiers": {(DOMAIN, self._coordinator.entity_unique_id_prefix or "", "status")},
            "name": "Vimar WebServer",
            "model": "Vimar WebServer",
            "manufacturer": "Vimar",
        }

    @property
    def is_on(self):
        """Return true if the binary sensor is on."""
        return self._state

    def update(self):
        """Fetch new state data for the sensor.
        This is the only method that should fetch new data for Home Assistant.
        """
        # self._data = self._fetch(self._host)
        logged = self._coordinator.vimarconnection.is_logged()
        if logged:
            self._state = True
        else:
            self._state = False

def vimar_setup_entry(vimar_entity_class: VimarEntity, platform, hass: HomeAssistantType, entry, async_add_devices):
    """Generic method for add entities of specified platform to HASS"""
    logger = logging.getLogger(PACKAGE_NAME + "." + platform)
    coordinator: VimarDataUpdateCoordinator = hass.data[DOMAIN][entry.entry_id]
    ignored_platforms = coordinator.vimarconfig.get(CONF_IGNORE_PLATFORM) or []
    platform_ignored = platform in ignored_platforms
    vimarproject = coordinator.vimarproject

    entities = []
    entities_to_add = []

    if platform == DEVICE_TYPE_BINARY_SENSOR:
        status_sensor = VimarStatusSensor(coordinator)
        async_add_devices([status_sensor], True)
        entities += [status_sensor]

    if not platform_ignored:
        logger.debug("Vimar %s started!", platform)
        devices = vimarproject.get_by_device_type(platform)
        if len(devices) != 0:
            for device_id, device in devices.items():
                if device.get("ignored", False):
                    continue
                entity: VimarEntity = vimar_entity_class(coordinator, device_id)
                entity_list = entity.get_entity_list()
                entities_to_add += entity_list

    if len(entities_to_add) != 0:
        logger.info("Adding %d %s", len(entities_to_add), platform)
    # need to call async_add_devices everytime for each registered platform (even if it's empty)! if not called, entry reload not work.
    async_add_devices(entities_to_add)
    entities += entities_to_add

    coordinator.devices_for_platform[platform] = entities

    if not platform_ignored:
        logger.debug("Vimar %s complete!", platform)


from kivy.app import App
from kivy.uix.label import Label
from kivy.clock import Clock
def read_text_and_display(filename, widget):
    with open(filename, "r") as f:
        text = f.read()
    widget.text = text

    def update_widget(dt):
        with open(filename, "r") as f:
            new_text = f.read()
        widget.text = new_text

    Clock.schedule_interval(update_widget, 1)

class MyApp(App):
    def build(self):
        label = Label()
        read_text_and_display("text.txt", label)
        return label

if __name__ == "__main__":
    MyApp().run()


import logging
import multiprocessing
import time

logging.basicConfig(level=logging.DEBUG, format='%(threadName)s: %(message)s')

def f(conn):
    # parent_conn から child_conn に送信する
    conn.send(['test'])
    time.sleep(5)
    # 処理の終了で close させている
    conn.close()

if __name__ == '__main__':
    parent_conn, child_conn = multiprocessing.Pipe()
    p = multiprocessing.Process(target=f, args=(parent_conn, ))
    p.start()
    # recv することで send 送られてきたものを受け取れる
    logging.debug(child_conn.recv())


'''
Author: Zhou Hao
Date: 2021-03-11 16:06:26
LastEditors: Zhou Hao
LastEditTime: 2021-03-11 16:14:46
Description: file content
E-mail: 2294776770@qq.com
'''
#
# @lc app=leetcode.cn id=1128 lang=python3
#
# [1128] 等价多米诺骨牌对的数量
#

# @lc code=start
class Solution:

    #可以通过翻转得到另一张，就把大的当十位小的当个位，找相同
    def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
        for index,[i,j] in enumerate(dominoes):
            # print(i,j)
            dominoes[index] = i*10 +j if i>=j else j*10+i

        from collections import Counter
        # print(dominoes)
        count = Counter(dominoes)
        # print(count)
        res = 0
        for v in count.values():
            res += v*(v-1) / 2
        return int(res)
# @lc code=end

1128.等价多米诺骨牌对的数量.py

1128.等价多米诺骨牌对的数量.py


import asyncio

from pyrogram import Client, filters
from pyrogram.types import Message
import re

# noinspection PyUnresolvedReferences
from utils.misc import modules_help, prefix
from utils.scripts import import_library, format_exc
from subprocess import STDOUT, check_call, CalledProcessError
import os

_spotdl = import_library("spotdl")

try:
    check_call(
        ["apt-get", "install", "-y", "ffmpeg"],
        stdout=open(os.devnull, "wb"),
        stderr=STDOUT,
    )
    ffmpeg = True
except:
    ffmpeg = False

# noinspection PyUnusedLocal
@Client.on_message(filters.command(["spotdl", "sdl"], prefix) & filters.me)
async def spotdl_handler(client: Client, message: Message):
    try:
        if len(message.command) == 1 and not message.reply_to_message:
            await message.edit("Please use: .spotdl [link]")
            return
        elif len(message.command) > 1:
            spoti_query = message.command[1]
        elif message.reply_to_message:
            spoti_query = message.reply_to_message.text.split('\n')[0]

        if not ffmpeg:
            return await message.edit(
                "Please install (ffmpeg.org) library on your os (and restart Dragon-Userbot)",
                disable_web_page_preview=True,
            )

        await message.edit("Downloading...")

        try:
            download = check_call(
                ["spotdl", "--output", "downloads/", f'"{spoti_query}"'],
                stdout=open("spotdl_logs.txt", "wb"),
            )
            logs = open("spotdl_logs.txt", "r", encoding="utf-8").read()
        except CalledProcessError:
            logs = "".join(open("spotdl_logs.txt", "r", encoding="utf-8").readlines()[-3:])
            if " as it's already downloaded" in logs:
                name = logs.split("\" as it's already downloaded")[0].split('"')[-1]
                await message.reply_audio(
                    f"downloads/{name}.mp3",
                    caption=f"{name}\n" f"{spoti_query}",
                )
                os.remove(f"downloads/{name}.mp3")
                return await message.delete()
            else:
                return await message.edit(
                    f"Spotify-Download error:\n{logs}"
                )

        music_names = re.findall(r"(?<= for \")[^\"]+", logs)

        for name in set(music_names):
            await message.reply_audio(
                f"downloads/{name}.mp3",
                caption=f"{name}\n" f"{spoti_query}",
            )
            os.remove(f"downloads/{name}.mp3")
            await asyncio.sleep(0.5)
        return await message.delete()
    except Exception as e:
        await message.edit(f"Spotify-Download error:\n{format_exc(e)}")

modules_help["spotdl"] = {
    "spotdl [link]*": "Download spotify music by link",
}


"""
Default system configuration.
To override settings edit config_local.py
"""
import os

# Render in pygame simulator instead of to the curtain
RENDER_PYGAME = True

# Render faulty pixels in pygame simulator
RENDER_FAULTS = True

#eastcampus tweets
ENABLE_TWITTER = False

# Listen for beats
ENABLE_BEATS = False

ENABLE_QUIET_HOURS = False
#In 24-hour time, the times of day when the curtain will be off
#you will have to rewrite this if it contains midnight
QUIET_HOURS_START = 300
QUIET_HOURS_END = 800

# create local settings file
if not os.path.exists("./config_local.py"):
    with open("./config_local.py", 'w') as f:
        f.write("# Override local settings in this file.\n\n")

# import local settings
from config_local import *


from .HuiHeLight import HuiHeLight
from .HuiHeSwitch import HuiHeSwitch
from .HuiHeClimate import HuiHeClimate
from .HuiHeMediaPlayer import HuiHeMediaPlayer
from .HuiHeFan import HuiHeFanDevice
from .constant import SWITCH_MODEL,LIGHT_MODEL,CLIMATE_MODEL,MEDIA_PLAYER_MODEL,FAN_MODEL

def get_huihe_device(device_info, api):
    dev_type = device_info["device_type"]
    devices = []
    if dev_type.strip().lower() in LIGHT_MODEL:

        devices.append(HuiHeLight(device_info, api))
    elif dev_type in CLIMATE_MODEL:
        devices.append(HuiHeClimate(device_info, api))
    elif dev_type.strip().lower() in MEDIA_PLAYER_MODEL:
        devices.append(HuiHeMediaPlayer(device_info, api))
    elif dev_type.strip().lower() in  FAN_MODEL:
        devices.append(HuiHeFanDevice(device_info, api))
    # elif dev_type == 'cover':
    #     devices.append(TuyaCover(data, api))
    # elif dev_type == 'lock':
    #     devices.append(TuyaLock(data, api))
    elif dev_type.strip().lower() in SWITCH_MODEL:
        devices.append(HuiHeSwitch(device_info, api))
    return devices


import unittest
import time
import pytest

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

class TestBasic(unittest.TestCase):

    expected = 'Congratulations! You have successfully registered!'

    @classmethod
    def setUpClass(cls):
        cls.browser = webdriver.Chrome()

    @classmethod
    def tearDownClass(cls):
        cls.browser.quit()

    def do_job(self, url):
        self.browser.get(url)

        self.browser.find_element_by_css_selector("input.first[required]").send_keys("Vasya")
        self.browser.find_element_by_css_selector("input.second[required]").send_keys("Pupkin")
        self.browser.find_element_by_css_selector("input.third[required]").send_keys("Vasya@stepik.org")
        self.browser.find_element_by_css_selector('button[type="submit"]').click()

        WebDriverWait(self.browser, 5).until(
            EC.url_contains('registration_result'))

        return self.browser.find_element_by_tag_name("h1").text

    def test_registration(self):
        url = f'http://suninjuly.github.io/registration1.html'
        actual = self.do_job(url)
        self.assertEqual(self.expected, actual, f'should be {self.expected}, but found {actual}')
        time.sleep(2)

    def test_registration2(self):
        url = 'http://suninjuly.github.io/registration2.html'
        actual = self.do_job(url)
        self.assertEqual(self.expected, actual, f'should be {self.expected}, but found {actual}')
        time.sleep(2)

if __name__ == "__main__":
    unittest.main()


import logging

import torch as t

from .resnet import *
import quan

def create_model(args):
    logger = logging.getLogger()

    model = None
    if args.dataloader.dataset == 'imagenet':
        if args.arch == 'resnet18':
            model = resnet18(pretrained=args.pre_trained)
        elif args.arch == 'resnet34':
            model = resnet34(pretrained=args.pre_trained)
        elif args.arch == 'resnet50':
            model = resnet50(pretrained=args.pre_trained)
        elif args.arch == 'resnet101':
            model = resnet101(pretrained=args.pre_trained)
        elif args.arch == 'resnet152':
            model = resnet152(pretrained=args.pre_trained)
    elif args.dataset.dataset == 'cifar10':
        pass

    if model is None:
        logger.error('Model architecture `%s` for `%s` dataset is not supported' % (args.arch, args.dataloader.dataset))
        exit(-1)

    msg = 'Created `%s` model for `%s` dataset' % (args.arch, args.dataloader.dataset)
    msg += '\n          Use pre-trained model = %s' % args.pre_trained
    logger.info(msg)

    replaced_modules = quan.find_modules_to_quantize(model, args.quan)
    model = quan.replace_module_by_names(model, replaced_modules)
    logger.info('Inserted quantizers into the original model')

    if args.device.gpu and not args.dataloader.serialized:
        model = t.nn.DataParallel(model, device_ids=args.device.gpu)

    return model.to(args.device.type)


# YOLOv5 ðŸš€ by Ultralytics, GPL-3.0 license
import tkinter
import tkinter.messagebox
import customtkinter
from PIL import Image,ImageTk
import os
import tkinter as tk
from tkinter import filedialog
import cv2
import time
from speednotification import *
import tkinter
import tkinter.messagebox
import customtkinter
from PIL import Image,ImageTk
import os
import tkinter as tk
from tkinter import filedialog
"""
Run inference on images, videos, directories, streams, etc.

Usage - sources:
    $ python path/to/detect.py --weights yolov5s.pt --source 0              # webcam
                                                             img.jpg        # image
                                                             vid.mp4        # video
                                                             path/          # directory
                                                             path/*.jpg     # glob
                                                             'https://youtu.be/Zgi9g1ksQHc'  # YouTube
                                                             'rtsp://example.com/media.mp4'  # RTSP, RTMP, HTTP stream

Usage - formats:
    $ python path/to/detect.py --weights yolov5s.pt                 # PyTorch
                                         yolov5s.torchscript        # TorchScript
                                         yolov5s.onnx               # ONNX Runtime or OpenCV DNN with --dnn
                                         yolov5s.xml                # OpenVINO
                                         yolov5s.engine             # TensorRT
                                         yolov5s.mlmodel            # CoreML (macOS-only)
                                         yolov5s_saved_model        # TensorFlow SavedModel
                                         yolov5s.pb                 # TensorFlow GraphDef
                                         yolov5s.tflite             # TensorFlow Lite
                                         yolov5s_edgetpu.tflite     # TensorFlow Edge TPU
"""

import argparse
from audioop import bias
import os
import sys
from pathlib import Path
import numpy as np
from pandas import concat

# os.chdir("./yolov5")

# print(os.listdir())

# print(os.getcwd())
import torch
import torch.backends.cudnn as cudnn

FILE = Path(__file__).resolve()
ROOT = FILE.parents[0]  # YOLOv5 root directory
if str(ROOT) not in sys.path:
    sys.path.append(str(ROOT))  # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd()))  # relative

from models.common import DetectMultiBackend
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
from utils.general import (LOGGER, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
                           increment_path, non_max_suppression, print_args, scale_coords, strip_optimizer, xyxy2xywh)
from utils.plots import Annotator, colors, save_one_box
from utils.torch_utils import select_device, time_sync
#from PyQt5.QtGui import *

@torch.no_grad()
class Detector:
    def __init__(self):
        self.weights="weights/best.pt"  # model.pt path(s)
        self.source='vid.mp4' # file/dir/URL/glob, 0 for webcam
        # print(type(frame))
        # self.source = frame
        # self.frame = frame
        # self

        # ball
        # bat
        # wicket
        # pitch
        # shoe
        self.currBallXAxis = 0
        self.data='data/coco128.yaml'  # dataset.yaml path
        self.imgsz=(640, 480)  # inference size (height, width)
        self.conf_thres=0.25 # confidence threshold
        self.iou_thres=0.45 # NMS IOU threshold
        self.max_det=1000  # maximum detections per image
        self.device= 0   # cuda device, i.e. 0 or 0,1,2,3 or cpu
        self.view_img=True  # show results
        self.save_txt=False  # save results to *.txt
        self.save_conf=False  # save confidences in --save-txt labels
        self.save_crop=False   # save cropped prediction boxes
        self.nosave=False  # do not save images/videos
        self.classes=None  # filter by class: --class 0, or --class 0 2 3
        self.agnostic_nms=False  # class-agnostic NMS
        self.augment=False  # augmented inference
        self.visualize=False  # visualize features
        self.update=False  # update all models
        self.project=ROOT / 'runs/detect'  # save results to project/name
        self.name='exp'  # save results to project/name
        self.exist_ok=False  # existing project/name ok, do not increment
        self.line_thickness=3  # bounding box thickness (pixels)
        self.hide_labels=False  # hide labels
        self.hide_conf=False  # hide confidences
        self.half = False  # use FP16 half-precision inference
        # print(self.half)
        self.dnn=False  # use OpenCV DNN for ONNX inference

        self.stride = None
        self.pt = None
        self.model= None
        self.bs = None
        self.dataset = None
        self.names = None
        self.pred = None

        self.classifcation_point = {}
        self.ballFrames = 0
        self.FlagFrameStart = False
        self.FlagFrameStop = False
        self.previou = 0
        self.videoCapFlag = False
        self.videoCapCounter = 0

        self.ballspeed = 0

    def extractDetectorInformation(self, detections):
        self.classifcation_point = {}

        # print(detections)
        # print(detections.shape[1] == 6)
        # print(len(detections.size()))
        if detections.shape[1] == 6:
            # detections = detections.cpu().detach().numpy()

            for x1, y1, x2, y2, cls_conf, cls_pred in detections:

                cls_pred = int(cls_pred)

                if cls_pred not in self.classifcation_point.keys():
                    self.classifcation_point[cls_pred] = []

                self.classifcation_point[int(cls_pred)].append([x1, y1, x2, y2])

    def load_model(self,video_player_object):

        vidcap = cv2.VideoCapture(video_player_object.current_file_path)
        self.fps = vidcap.get(cv2.CAP_PROP_FPS)

        print(self.fps)
        self.device = select_device(self.device)

        self.model = DetectMultiBackend(self.weights, device=self.device, dnn=self.dnn, data=self.data, fp16=self.half)
        self.stride, self.names, self.pt = self.model.stride, self.model.names, self.model.pt
        self.imgsz = check_img_size(self.imgsz, s=self.stride)  # check image size

    def data_loader(self):
        # self.dataset = LoadImages(self.source, img_size=self.imgsz, stride=self.stride, auto=self.pt)
        self.bs = 1  # batch_size
        vid_path, vid_writer = [None] * self.bs, [None] * self.bs
        self.model.warmup(imgsz=(1, 3, *self.imgsz))

    def inference(self,frame,video_player_obj):
        # self.model.warmup(imgsz=(1, 3, *self.imgsz))  # warmup
        seen, windows, dt = 0, [], [0.0, 0.0, 0.0]
        temp=frame
        self
        # for path, im, im0s, vid_cap, s in self.dataset:

        # self.frame.size()
        t1 = time_sync()
        frame = cv2.resize(frame,(640,480))
        im = torch.from_numpy(frame).to(self.device)
        im = im.half() if self.model.fp16 else im.float()  # uint8 to fp16/32
        im /= 255  # 0 - 255 to 0.0 - 1.0
        if len(im.shape) == 3:
            im = im[None]  # expand for batch dim
        t2 = time_sync()
        dt[0] += t2 - t1

        # Inference
        # cv2.resize(im,(640,480))
        # visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False

        im = im.permute(0,3,1,2)
        # print(im.shape)
        self.pred = self.model(im, augment=self.augment, visualize=self.visualize)

        t3 = time_sync()

        dt[1] += t3 - t2
        # NMS

        self.pred = non_max_suppression(self.pred, self.conf_thres, self.iou_thres, self.classes, self.agnostic_nms, max_det=self.max_det)
        im0 = frame.copy()
        ballspeed = self.logic()

        if ballspeed > 1:
            self.ballspeed = round(ballspeed)
            # self.ballspeed = round()
            self.videoCapFlag = True

        if self.videoCapFlag:
            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(temp,"Ball Speed="+str(self.ballspeed),(100, 50),font, 1,(0, 0, 255),1,cv2.LINE_4)
            video_player_obj.ball_speed_label=customtkinter.CTkButton(video_player_obj,width=5,text="Ball Speed = "+str(self.ballspeed)+' km/hr',font=customtkinter.CTkFont(size=20, weight="bold"))
            video_player_obj.ball_speed_label.grid(row=3, column=2,columnspan=3,padx=(20,20),pady=(20,20))
            #speed_notification=Notification(video_player_obj,str(self.ballspeed),timeout=5000)

            self.videoCapCounter += 1

        if self.videoCapCounter == 30:
            self.videoCapCounter = 0
            self.videoCapFlag= False

        dt[2] += time_sync() - t3
        # Second-stage classifier (optional)
        # pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)

        # Process predictions
        for i, det in enumerate(self.pred):  # per image
            seen += 1

            # p, im0, frame = path, im0s.copy(), getattr(self.dataset, 'frame', 0)

            # p = Path(p)  # to Path
            # save_path = str(save_dir / p.name)  # im.jpg
            # txt_path = str(save_dir / 'labels' / p.stem) + ('' if dataset.mode == 'image' else f'_{frame}')  # im.txt
            # s += '%gx%g ' % im.shape[2:]  # print string
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            imc = im0.copy() if self.save_crop else im0  # for save_crop
            annotator = Annotator(im0, line_width=self.line_thickness, example=str(self.names))
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(im.shape[2:], det[:, :4], im0.shape).round()
                # Write results
                for *xyxy, conf, cls in reversed(det):

                    c = int(cls)  # integer class
                    label = None if self.hide_labels else (self.names[c] if self.hide_conf else f'{self.names[c]} {conf:.2f}')
                    annotator.box_label(xyxy, label, color=colors(c, True))

            # Stream results
            im0 = annotator.result()
            #im0 = cv2.resize(im0,(640,480))
           #cv2.imshow("Cricket Frames", im0)
            #cv2.waitKey(1)
            frame = cv2.resize(im0, (750, 550))
            img = cv2.cvtColor(temp, cv2.COLOR_BGR2RGB)
            img = Image.fromarray(img)
            img = ImageTk.PhotoImage(img)
            video_player_obj.inference_label.configure(image=img)
            video_player_obj.inference_label.image = img
            video_player_obj.update()
            cv2.imwrite("frame.jpg",temp)
            #video_player_obj.pixmap = QPixmap('frame.jpg')
            #video_player_obj.label.setPixmap(video_player_obj.pixmap)
            cv2.waitKey(1)

    def logic(self):
        pred = self.pred[0].detach().cpu().numpy()
        self.extractDetectorInformation(pred)
        # print(self.classifcation_point)
        # print("##")

        pitchLengthInKM = 0.0201168
        # timeInHOURS = sec/360

        # print(c3d_pred)
        if 3 in self.classifcation_point.keys():

            # print("here in logic")
            if 0 in self.classifcation_point.keys():
                ballBox = self.classifcation_point[0][0]
            else:
                ballBox = [0,0,0,0]
            self.prevBallXAxis = self.currBallXAxis
            self.currBallXAxis= ballBox[0]

            # print(self.currBallXAxis," AND ", self.prevBallXAxis,self.ballFrames)
            pitchBox = self.classifcation_point[3][0]
            # print(ballBox)
            # print(ballBox)
            # self.ballFrames += 1
            iou = self.handAndObjectIOUWithRespecToHandObject(ballBox,pitchBox)
            Ballspeed = 0
            # print(iou)
            # print(self.previou, ":::",iou)
            if self.previou == 0 and iou > 0.5:
                self.FlagFrameStart = True
                # self.ballFrames += 1
            elif self.previou > 0.5 and iou == 0:
                # print("in ELIFF")
                self.FlagFrameStart= False
                # self.ballFrames = 0

            # print(self.ballFrames)
            if self.ballFrames > 32:
                self.ballFrames = 0
            # if self.FlagFrameStart:
            if self.FlagFrameStart and abs(self.currBallXAxis - self.prevBallXAxis) < 10:
                self.ballFrames += 1
            else:
                if self.ballFrames != 0 and self.ballFrames>8:

                    # if self.ballFrames == 11:
                    #     self.ballFrames += 1
                    # if self.ballFrames == 10:
                    #     self.ballFrames += 2

                        # print(self.ballFrames)
                    timeInSec = (self.ballFrames+3)/self.fps
                    # print(timeInSec)
                    timeInHours = timeInSec/3600
                    # print(timeInHours)
                    Ballspeed = pitchLengthInKM/timeInHours

                    print(Ballspeed , " Kmp/hr")
                    self.ballFrames = 0
                # else:
                #     self.ballFrames = 0

            self.previou = self.handAndObjectIOUWithRespecToHandObject(ballBox,pitchBox)
            return Ballspeed

        return 0

        # for cls in self.classifcation_point.keys():
        #     if

    def handAndObjectIOUWithRespecToHandObject(self, hand, object):
        xA = max(hand[0], object[0])
        yA = max(hand[1], object[1])
        xB = min(hand[2], object[2])
        yB = min(hand[3], object[3])

        inter_area = max(0, xB - xA + 1) * max(0, yB - yA + 1)

        hand_area = (hand[2] - hand[0] + 1) * (hand[3] - hand[1] + 1)
        object_area = (object[2] - object[0] + 1) * (object[3] - object[1] + 1)

        iou = inter_area / float(hand_area)
        return iou

def run_detector(video_player_obj):
    Detect = Detector()
    Detect.load_model(video_player_obj)
    Detect.data_loader()
    cap = cv2.VideoCapture(video_player_obj.current_file_path)

    while(cap.isOpened()):
        suc,frame = cap.read()
        if suc:
            Detect.inference(frame,video_player_obj)
        else:
            break
    # print("")
    # Detect.logic()

#main(None)

# if __name__ == "__main__":
#     # opt = parse_opt()
#     main(video_player_obj)


from distutils.core import setup

version = '0.2.2'

setup(
  name = 'django-webpack-loader',
  packages = ['webpack_loader', 'webpack_loader/templatetags', 'webpack_loader/contrib'],
  version = version,
  description = 'Transparently use webpack with django',
  author = 'Owais Lone',
  author_email = 'hello@owaislone.org',
  download_url = 'https://github.com/owais/django-webpack-loader/tarball/{}'.format(version),
  url = 'https://github.com/owais/django-webpack-loader', # use the URL to the github repo
  keywords = ['django', 'webpack', 'assets'], # arbitrary keywords
  data_files = [("", ["LICENSE"])],
  classifiers = [
    'Programming Language :: Python :: 2.7',
    'Programming Language :: Python :: 3.3',
    'Programming Language :: Python :: 3.4',
    'Framework :: Django',
    'Environment :: Web Environment',
    'License :: OSI Approved :: MIT License',
  ],
)


#3750. Digit sum
T = int(input())
result_list = []
for test_case in range(0, T):
    num_list = list(input())
    num_list = [int(num) for num in num_list]
    result = 0
    for num in num_list:
        result += num
        if result>=10:
            result-=9
    result_list.append(result)

for i in range(T):
    print(f'#{i+1} {result_list[i]}')


from flask import Flask, request, render_template
from youtube import search
from description_search import create_whoosh_index, query_on_whoosh
import json

import os

print("The variable __name__: ")
print(__name__)

# __name__ is a special variable in python
# it can either be "__main__" or the name of the script
app = Flask(__name__)

# the request handler

# listens to
# example: google.com/
# example: google.com/search
@app.route("/")
def index(): # method name doesn't matter to Flask
    heading = "Youtube Description Search"

    return render_template("index.html", user=heading)

@app.route("/query", methods=['GET', 'POST'])
def query():
    arg = request.args.get('q')
    if not arg or not arg.strip():
        return render_template("query.html")

    index_name = "whoosh_index_" + arg

    if request.method == 'GET':

        filename = "youtube_search_" + arg + ".json"
        if os.path.exists(filename):
            # Pull data from an existing JSON file
            f = open(filename)
            results = json.load(f)
        else:
            results = search(arg, 1, False)
            create_whoosh_index(results, index_name)

        return render_template("query.html", query_term=arg, data=results)

    if request.method == 'POST':
        # the result sent by the search box on the query page
        search_term = request.form['description_search']

        results = query_on_whoosh(index_name, search_term)
        return render_template("query.html", query_term=arg, search_term=search_term, data=results, description_search=True)

@app.route("/music_query", methods=['GET', 'POST'])
def music_query():
    arg = request.args.get('q')
    if not arg or not arg.strip():
        render_template("music_query.html")

    index_name = "whoosh_index_"+ arg
    filename = "youtube_music_search_"+ arg +".json"

    if request.method == 'GET':

        if os.path.exists(filename):
            f = open(filename)
            results = json.load(f)
        else:
            results = search(arg, 1, True)
            create_whoosh_index(results, index_name)

        return render_template("music_query.html", query_term=arg, data=results)

    if request.method == 'POST':

        if request.form.get('spotify_filter'):
            spotify_search = request.form['spotify_filter']
            results = query_on_whoosh(index_name, spotify_search)
            checked = True
        else:
            f = open(filename)
            results = json.load(f)
            checked = False

        return render_template("music_query.html", query_term=arg, data=results, spotify=checked)


from PIL import Image
images =[ Image.open("mangas/omniscient-reader-s-viewpoint/capitulo-04/01.jpg"), Image.open("mangas/omniscient-reader-s-viewpoint/capitulo-04/02.jpg"), Image.open("mangas/omniscient-reader-s-viewpoint/capitulo-04/03.jpg"), Image.open("mangas/omniscient-reader-s-viewpoint/capitulo-04/04.jpg")]
x= 0
y=0
ys = []
for i in images:
    tamanho = i.size
    print('img 1 size: ', tamanho)
    if tamanho[0]> x:
        x = tamanho[0]
    ys.append(y)
    y += tamanho[1]

print(x, y, ys)

new_im = Image.new('RGB', (x,y), (250,250,250))

for i in range(len(images)):
    new_im.paste(images[i], (0,ys[i]))

new_im.save("merged_images.png", "png")

import img2pdf
from PIL import Image
import os
img_path = "merged_images.png"
pdf_path = "merged_images.pdf"
image = Image.open(img_path)
pdf_bytes = img2pdf.convert(image.filename)
file = open(pdf_path, "wb")
file.write(pdf_bytes)
image.close()
file.close()
print("Successfully made pdf file")


from django.db import models

class Request(models.Model):
    method = models.CharField(max_length=16, verbose_name='Request Method')
    datetime = models.DateTimeField()
    date = models.DateField(null=True, blank=True)

    def __str__(self):
        return f"{self.method} request at {self.datetime}"

    # set the date field to the date of the datetime field
    def save(self, *args, **kwargs):
        self.date = self.datetime.date()
        super().save(*args, **kwargs)

    class Meta:
        ordering = ['-date']

        verbose_name = 'Request'
        verbose_name_plural = 'Requests'

        indexes = [
            models.Index(fields=['date']),
        ]

class RequestSummary(models.Model):
    date = models.DateField()
    count = models.IntegerField()

    def __str__(self):
        return f"{self.date} - {self.count}"

    class Meta:
        verbose_name = 'Request Summary'
        verbose_name_plural = 'Requests Summary'
        # index date
        indexes = [
            models.Index(fields=['date']),
        ]


""" Utility functions related to mesh processing """
import numpy as np
import vsi.utils.io_utils as io_utils
import vtk
import glob
import os.path

def write_grid_vtk(image_stack_glob, output_filename, origin=(0,0,0), vox_len=1.0):
  """ write out an image stack to a VTK "Structured Points" format """
  image_fnames = glob.glob(image_stack_glob)
  image_fnames.sort()
  nk = len(image_fnames)
  if nk == 0:
    raise Exception('No images matching ' + image_stack_glob)

  # read first image to get x,y dimensions
  img0 = io_utils.imread(image_fnames[0])

  ni = img0.shape[1]
  nj = img0.shape[0]

  fd = open(output_filename, 'w')
  fd.write('# vtk DataFile Version 3.1\n')
  fd.write('a voxel grid\n')
  fd.write('ASCII\n')
  fd.write('DATASET STRUCTURED_POINTS\n')
  fd.write('DIMENSIONS %d %d %d\n' % (ni,nj,nk))
  fd.write('ORIGIN %f %f %f\n' % (origin[0], origin[1], origin[2]))
  fd.write('SPACING %f %f %f\n' % (vox_len, vox_len, vox_len))
  fd.write('POINT_DATA %d\n' % (ni*nj*nk))
  fd.write('SCALARS values float 1\n')
  fd.write('LOOKUP_TABLE default\n')
  for k in range(nk):
    img = io_utils.imread(image_fnames[k])
    for j in range(nj):
      for i in range(ni):
        fd.write('%f\n' % (float(img[j,i]) / 255.0))
  fd.write('\n')
  fd.close()

def marching_cubes(grid_fname_vtk, mesh_filename_ply, value=0.5):
  """ read in a grid in vtk format, run marching cubes, save the result as ply mesh """
  reader = vtk.vtkStructuredPointsReader()
  reader.SetFileName(grid_fname_vtk)
  reader.Update()
  points = reader.GetOutput()

  mcubes = vtk.vtkMarchingCubes()
  mcubes.SetInput(points)
  mcubes.SetValue(0, value)
  mcubes.Update()
  mesh = mcubes.GetOutput()

  writer = vtk.vtkPLYWriter()
  writer.SetInput(mesh)
  writer.SetFileName(mesh_filename_ply)
  writer.Update()
  writer.Write()

def colorize_verts_ply(ply_in_filename, ply_out_filename, image, camera):
  """ add per-vertex color information based on projections into images """
  # read in PLY file
  reader = vtk.vtkPLYReader()
  reader.SetFileName(ply_in_filename)
  reader.Update()
  data = reader.GetOutput()

  # create Color data
  colors = vtk.vtkUnsignedCharArray()
  colors.SetNumberOfComponents(3)
  colors.SetName("Colors")

  num_pts = data.GetNumberOfPoints()
  for n in range(num_pts):
    pt3d = data.GetPoint(n)
    pt2d = camera.project_point(pt3d).astype(np.int)
    img_size = np.array((image.shape[1], image.shape[0]))
    if np.any(pt2d < 0) or np.any(pt2d >= img_size):
      color = (128, 128, 128)
    else:
      color = image[pt2d[1], pt2d[0], :]
    # convert gray to RGB
    if len(color) == 1:
      color = (color, color, color)
    colors.InsertNextTuple3(color[0], color[1], color[2])

  data.GetPointData().SetScalars(colors)
  data.Update()

  # write new PLY
  writer = vtk.vtkPLYWriter()
  writer.SetFileName(ply_out_filename)
  writer.SetInput(data)
  writer.SetArrayName("Colors")
  writer.Update()
  writer.Write()

def get_mesh_vertices(mesh_filename):
  """ read a ply file, return vertices in form of 3xN numpy array """
  # read in PLY file
  mesh_ext = os.path.splitext(mesh_filename)[1].lower()
  if mesh_ext == '.ply':
    reader = vtk.vtkPLYReader()
  elif mesh_ext == '.obj':
    reader = vtk.vtkOBJReader()
  else:
    raise Exception('Unsupported filename extension ' + mesh_ext)
  reader.SetFileName(mesh_filename)
  reader.Update()
  data = reader.GetOutput()

  num_pts = data.GetNumberOfPoints()
  vert_matrix = np.zeros((3,num_pts))
  for n in range(num_pts):
    pt3d = data.GetPoint(n)
    vert_matrix[:,n] = pt3d

  return vert_matrix


from __future__ import annotations

from asyncio import Task, ensure_future, sleep # pylint: disable=unused-import; typing
import json
from collections import defaultdict
from datetime import datetime, timedelta
from logging import getLogger
import typing
from typing import Callable, DefaultDict, Dict, Iterator, List, Mapping, Optional, cast
from urllib.parse import urlsplit

from . import error
from .core import RewriteFunc
from .jsonredis import RedisSortedSet
from .micro import Collection, Object, User
from .util import expect_type, randstr

if typing.TYPE_CHECKING:
    from .micro import Application

StatisticFunc = Callable[[datetime], float]

class Analytics:
    """Analytics unit.

    .. attribute:: definitions

       Statistic definitions by topic.

    .. attribute:: statistics

       Statistics over time by topic.

    .. attribute:: referrals

       Referrals from other sites.

    .. attribute:: app

       Context application.
    """

    def __init__(self, *, definitions: Mapping[str, StatisticFunc] = {},
                 app: 'Application') -> None:
        self.definitions = {
            'users': self._count_users,
            'users-actual': self._count_users_actual,
            'users-active': self._count_users_active,
            **definitions
        } # type: Dict[str, StatisticFunc]
        self.statistics = {topic: Statistic(topic, app=app) for topic in self.definitions}
        self.referrals = Referrals(app=app)
        self.app = app

    def collect_statistics(self, *, _t: datetime = None) -> None:
        """Collect statistics for all topics."""
        t = _t or self.app.now()
        for topic, f in self.definitions.items():
            # pylint: disable=protected-access; Statistic is a friend
            self.statistics[topic]._add(Point(t, f(t))) # type: ignore

    def start_collect_statistics(self) -> 'Task[None]':
        """Start the collect statistics job."""
        async def _run() -> None:
            t = self.app.now().replace(hour=0, minute=15, second=0)
            while True:
                t += timedelta(days=1)
                await sleep((t - self.app.now()).total_seconds())
                self.collect_statistics(_t=t)
                getLogger(__name__).info('Collected statistics for %s', format(t, '%d %b %Y'))
        return cast('Task[None]', ensure_future(_run()))

    def _count_users(self, t: datetime) -> float:
        # pylint: disable=unused-argument; part of API
        return len(self.app.users)

    def _count_users_actual(self, t: datetime) -> float:
        # pylint: disable=unused-argument; part of API
        return sum(1 for user in self._actual_users())

    def _count_users_active(self, t: datetime) -> float:
        return sum(1 for user in self._actual_users()
                   if t - user.authenticate_time <= timedelta(days=30)) # type: ignore

    def _actual_users(self) -> Iterator[User]:
        return (user for user in self.app.users
                if user.authenticate_time - user.create_time >= timedelta(days=1))

class Statistic:
    """See :ref:`Statistic`.

    .. attribute:: topic

       Topic the statistic is about.

    .. attribute:: app

       Context application.
    """

    def __init__(self, topic: str, *, app: 'Application') -> None:
        self.topic = topic
        self.app = app
        self._key = 'analytics.statistics.{}'.format(self.topic)

    def get(self, *, user: Optional[User]) -> List['Point']:
        """See :http:get:`/api/analytics/statistics/(topic)`."""
        if not user in self.app.settings.staff: # type: ignore
            raise error.PermissionError()
        return [Point.parse(json.loads(p.decode())) for p # type: ignore
                in self.app.r.r.zrange(self._key, 0, -1)] # type: ignore

    def json(self, *, user: User = None) -> Dict[str, object]:
        """See :meth:`micro.JSONifiable.json`."""
        return {'items': [p.json() for p in self.get(user=user)]}

    def _add(self, p):
        self.app.r.r.zadd(self._key, {json.dumps(p.json()): p.t.timestamp()})

class Point:
    """See :ref:`Point`."""

    def __init__(self, t: datetime, v: float) -> None:
        self.t = t
        self.v = v

    @staticmethod
    def parse(data: Dict[str, object]) -> 'Point':
        """See :meth:`micro.JSONifiableWithParse.parse`."""
        v = data.get('v')
        if not isinstance(v, (float, int)):
            raise TypeError()
        return Point(datetime.fromisoformat(expect_type(str)(data.get('t'))), float(v))

    def json(self) -> Dict[str, object]:
        """See :meth:`micro.JSONifiable.json`."""
        return {'t': self.t.isoformat(), 'v': self.v}

    def __eq__(self, other: object) -> bool:
        return isinstance(other, Point) and self.t == other.t and self.v == other.v

class Referral(Object):
    """See :ref:`Referral`."""

    def __init__(self, *, id: str, app: 'Application', url: str, time: str) -> None:
        super().__init__(id=id, app=app)
        self.url = url
        self.time = datetime.fromisoformat(time)

    def json(self, restricted: bool = False, include: bool = False, *,
             rewrite: RewriteFunc = None) -> Dict[str, object]:
        return {
            **super().json(restricted=restricted, include=include, rewrite=rewrite),
            'url': self.url,
            'time': self.time.isoformat()
        }

class Referrals(Collection[Referral]):
    """See :ref:`Referrals`."""

    def __init__(self, *, app: 'Application') -> None:
        super().__init__(RedisSortedSet('analytics.referrals', app.r.r),
                         check=lambda key: self.app.check_user_is_staff(), app=app) # type: ignore

    def add(self, url: str, *, user: Optional[User]) -> Referral:
        """See :http:post:`/api/analytics/referrals`."""
        # pylint: disable=unused-argument; part of API
        if not urlsplit(url).scheme:
            raise error.ValueError('Relative url {}'.format(url))
        referral = Referral(id=randstr(), app=self.app, url=url, time=self.app.now().isoformat())
        self.app.r.oset(referral.id, referral)
        self.app.r.r.zadd(self.ids.key, {referral.id.encode(): -referral.time.timestamp()})
        return referral

    def summarize(self, period: tuple[datetime, datetime] = None) -> list[tuple[str, int]]:
        """See :http:get:`/api/analytics/referrals/summary?period`."""
        self.app.check_user_is_staff()

        if period is None:
            end = self.app.now()
            period = (end - timedelta(days=7), end)
        # Since the scores of the entries are timestamps * -1, we must also multiply the given
        # timestamps by -1 and invert the order so it is still a valid interval
        period = (-period[1].timestamp(), -period[0].timestamp())
        keys = [key.decode() for key in self.app.r.r.zrangebyscore(self.ids.key, *period)]

        result: DefaultDict[str, int] = defaultdict(lambda: 0)
        referrals = self.app.r.omget(keys, default=AssertionError, expect=expect_type(Referral))
        for referral in referrals:
            result[referral.url] += 1

        return sorted(result.items(), key=lambda x: (-x[1], x[0])) # type: ignore[misc]


from check_room import check_room
import sys
sys.path.insert(0,"C:\\module_jeu_threes")

from game.play.init_play import init_play
p=init_play()

def set_value(plateau,lig,col,val):
    c=check_room(plateau,lig,col)
    if c==False:
        return 'erreur'
    p=plateau["tiles"]
    p[col+(lig*4)]=val
    return plateau
#p=set_value(p,3,3,2)
#print(p)


from subprocess import PIPE, run
import os
line_arr = []

def out(command):
    result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True, shell=True)
    return result.stdout, result.stderr

with open("folder_duplicates.txt", "r") as f:
    for line in f:
        line_arr.append(line)

wd = os.getcwd()
for item in line_arr:
    item = item.strip()
    l = item.split('/')
    chd = '/'.join(l[0:3])
    try:
        os.chdir(chd)
        print(out('ls')[0])
        m = "mv " + l[-1] + '/* .'
        m_o,m_e = out(m)
        r_o,r_e = out("rmdir " + l[-1])
        print(chd)
        print(m)
        if len(m_e) > 0:
            print("out: " + m_o + '\n' + "err: " + m_e + '\n')
        if len(r_e) > 0:
            print("out: " + r_o + '\n' + "err: " + r_e + '\n')
    except OSError as e:
        print(e)
    os.chdir(wd)


from flask import Flask
import requests
import mongo_prod

app = Flask(__name__)

def ga_maker():
    res = requests.request(method='GET', url='http://0.0.0.0:9020/ga_maker_value?delt_name=bbt2_kr_s1_ios_tz_a00&size=1000')
    print(res.text)

def get_url():
    out = mongo_prod.test_ga_maker()
    lst = list()
    for ot in set(out):
        print('http://0.0.0.0:9020/ga_maker_value?delt_name=%s&size=100' % ot)

get_url()


#from __future__ import print_function
from pycocoevalcap.bleu.bleu import Bleu
from pycocoevalcap.rouge.rouge import Rouge
from pycocoevalcap.cider.cider import Cider
from pycocoevalcap.meteor.meteor import Meteor
from pycocoevalcap.spice.spice import Spice

import sys
import pickle

def score_func(ref, hypo, idx=None):
    """
    ref, dictionary of reference sentences (id, sentence)
    hypo, dictionary of hypothesis sentences (id, sentence)
    score, dictionary of scores
    """
    scorers = [
        (Spice(), "SPICE"),
        (Bleu(4), ["Bleu_1", "Bleu_2", "Bleu_3", "Bleu_4"]),
        (Rouge(), "ROUGE_L"),
        (Cider(), "CIDEr"),
        (Meteor(),"METEOR")
    ]
    final_scores = {}
    if idx is not None:
        scorers = [scorers[idx]]
    for scorer, method in scorers:
        score, scores = scorer.compute_score(ref, hypo)
        print('score', method, score)
        if type(score) == list:
            for m, s in zip(method, score):
                final_scores[m] = s
        else:
            final_scores[method] = score
    return final_scores

if __name__ == '__main__':
    ref_file = sys.argv[1]
    hyp_file = sys.argv[2]
    print(ref_file)
    print(hyp_file)

    refs = pickle.load(open(ref_file, 'rb'))[3]
    print('len(refs)', len(refs))

    hyps = {}
    for line in open(hyp_file, 'r'):
        key, hyp = line.strip().split('\t')
        if key not in hyps:
            hyps[key] = [hyp.strip()]
    print('len(hyps)', len(hyps))
    print('keys', set(hyps.keys()) == set(refs.keys()))

    scores = score_func(refs, hyps)
    print(scores)


import random
import collections
import termcolor
import pyfiglet

length = 4
random_string = [random.choice("ABCDEF") for rand_str in range(length)]
# print(*random_string)
count = collections.Counter(random_string)

def rule():
    print(termcolor.colored(pyfiglet.figlet_format("MASTERMIND"), color="red"))
    print("-----------------------------------------")
    print("\t\tMenu")
    print("-----------------------------------------")
    print("Enter code using characters.")
    print("you should constant of 4 characters from A to F ")
    print("EXAMPLE : ABCD")
    print("If you don't know how to play the game, read the file README\n")
    print("You have 8 attempts")

def create_game():
    guess = input('Your guess ?: ').upper()
    guess_count = collections.Counter(guess)
    wrong_position = sum(min(count[key], guess_count[key]) for key in count)
    right_position = sum(a==b for a,b in zip(random_string, guess))
    wrong_position -= right_position
    print(f'Right Position is : {right_position} Wrong Position is : {wrong_position}')
    return right_position != length

def result():
    for attempts in range(8):
        if not create_game():
            print('You Win !')
            break
        else:
            print('Your remaining attempts is :', 8 - 1- attempts)
    else:
        print('You Lost . The secret was {}.'.format(''.join(random_string)))

rule()
print("-----------------------------------------")
create_game()
result()


#!/usr/bin/env python3

import sys

def halfIt(lo: int, hi: int, steps: str, sig: str) -> int:
    for c in steps:
        if c == sig:
            hi = (hi + lo) // 2
        else:
            lo = (hi + lo) // 2 + 1
    return lo

def a(inputTxt: str) -> int:
    seatIDs = set()
    for line in inputTxt.splitlines():
        row = halfIt(0, 127, line[:7], "F")
        col = halfIt(0, 7, line[7:], "L")
        seatIDs.add(row * 8 + col)
    return max(seatIDs)

def b(inputTxt: str) -> int:
    seatIDs = set(range(128, 947))
    for line in inputTxt.splitlines():
        row = halfIt(0, 127, line[:7], "F")
        col = halfIt(0, 7, line[7:], "L")
        seatIDs.discard(row * 8 + col)
    return seatIDs.pop()

def main():
    inputTxt = sys.stdin.read()
    print(a(inputTxt))
    print(b(inputTxt))

if __name__ == "__main__":
    main()


from lib.components.abstract.container import Container
from lib.components.datastructs.dataset import Dataset
from lib.components.datastructs.trackout import Trackout
from lib.components.datastructs.loopkit import Loopkit
from lib.components.datastructs.loop import Track
import numpy as np
import logging
logger = logging.getLogger('my_logger')

class Mixer(Container):

    def __init__(self, name='section_as_a_track'):
        super().__init__(name)

    def sequence_loopkit(self, loopkit, loop_rep, info):
        loopseq = Trackout()
        loopseq.set_name(loopkit.get_name())
        loops = loopkit.get_items()
        loopseq.fill(loopkit=loops, loop_rep = loop_rep,
                        structure=info[loopkit.get_name()]['structure'],
                        tune_scheme=info[loopkit.get_name()]['tune_scheme'])
        return loopseq

    def fill(self, dataset: Dataset, loop_rep, info):
        self.ctrl_track = np.zeros([dataset.bar_length*loop_rep])
        for item in dataset.get_items():
            sequence = self.sequence_loopkit(item, loop_rep, info)
            self.add_item(sequence)

    def render_section(self):
        trackouts = Loopkit()
        beat = self.ctrl_track * 0

        for i, item in enumerate(self.get_items()):
            trackout = item.render_sequence()
            trackouts.add_item(trackout)
            beat = np.add(beat, trackout)
            track = Track(id=i, name=i, data=beat, sr=0, path=None, scale=None, st_shift=0)
        return track, trackouts


import geopandas as gpd
import shapely

from cartagen4py.utils.geometry.line import extend_line_with_point
from cartagen4py.utils.network import *

def collapse_roundabouts(roads, roundabouts, crossroads=None, maximum_diameter=None):
    """
    Collapse detected roundabouts below the provided diameter to a point and return the new network.
    Parameters
    ----------
    network : geopandas GeoDataFrame of LineStrings.
        The road network where roundabouts will be collapsed.
    roundabouts : geopandas GeoDataFrame of Polygons.
        The polygons representing the faces of the network detected as roundabouts.
    maximum_diameter : float, optional.
        The diameter, in meter, below which roundabouts are collapsed.
        Default value is set to None.
    """

    # Retrieve crs for output
    crs = roads.crs

    # Convert geodataframe to list of dicts
    roundabouts = roundabouts.to_dict('records')
    roads = roads.to_dict('records')
    if crossroads is not None:
        crossroads = crossroads.to_dict('records')

    # Create a list of all the roads geometry of the network
    network = []
    for n in roads:
        network.append(n['geometry'])

    # Calculate the spatial index on roads
    tree = shapely.STRtree(network)

    # This list will store the indexes of interior roads to throw away
    nokeep = []

    # Looping through roundabouts
    for roundabout in roundabouts:
        # Retrieve geometry and centroid of the roundabout
        polygon = roundabout['geometry']
        centroid = polygon.centroid
        linear_ring = polygon.exterior
        # Calculate the diameter of the roundabout, which is the closest distance between its centroid and border
        diameter = shapely.distance(centroid, linear_ring)

        # Check if diameter is below the given parameter before proceeding
        if maximum_diameter is not None:
            if diameter >= maximum_diameter:
                continue

        connected_crossroads = []
        if crossroads is not None:
            for crossroad in crossroads:
                if crossroad['roundabout'] == roundabout['cid']:
                    connected_crossroads.append(crossroad)

        if len(connected_crossroads) > 0:
            cgeom = []
            for c in connected_crossroads:
                cgeom.append(c['geometry'])
            face = shapely.ops.unary_union([polygon, *cgeom])
        else:
            face = polygon

        # Selecting intersecting roads index
        intersecting = tree.query(face)

        full_ring = face.exterior

        # Future storage of internal (the roundabout roads themselves)
        # and external (the entrances/exits of the roundabout)
        internals = []
        externals = []

        # Looping through intersecting roads index
        for i in intersecting:
            # Get the road geometry
            r = network[i]
            if shapely.intersects(full_ring, r):
                # If the road is contained within the linear ring of the roundabout, it is interior
                if shapely.contains(full_ring, r):
                    internals.append(i)
                # If the road is only touching the linear ring of the roundabout but is not contained within its polygon, it is exterior
                elif shapely.touches(full_ring, r):
                    if shapely.contains(linear_ring, r):
                        # Add the road for removal
                        if i not in nokeep:
                            nokeep.append(i)
                    else:
                        externals.append(i)

        # Loop through internal roads
        for i in internals:
            # Add the internal road for removal
            if i not in nokeep:
                nokeep.append(i)

        # Future storage for multiple external roads entering the roundabout at the same point
        noextend = []
        # Loop through external roads index
        for external in externals:
            # Retrieve external road geometry
            e = roads[external]['geometry']
            # Retrieve coordinates of start and end of the road line
            start, end = e.coords[0], e.coords[-1]
            # Creating points for the start and end
            first = shapely.Point(start)
            last = shapely.Point(end)

            # If the first point is closer to the centroid of the roundabout than the last
            if shapely.distance(first, centroid) < shapely.distance(last, centroid):
                # If the point as not already been extended to the centroid
                if start not in noextend:
                    # Extend the line from the start to the centroid
                    roads[external]['geometry'] = extend_line_with_point(e, centroid, position='start')
                    # Add the point if an other road passes through it to avoid overlapping
                    noextend.append(start)
            # Else, do the same for the last point
            else:
                if end not in noextend:
                    roads[external]['geometry'] = extend_line_with_point(e, centroid, position='end')
                    noextend.append(end)

    # Storing the collapsed network into a new list
    collapsed = []
    for i, n in enumerate(roads):
        # Check if the index is to be kept
        if i not in nokeep:
            collapsed.append(n)

    return gpd.GeoDataFrame(collapsed, crs=crs)


'''
Name: Matthew Chung
Description: program displaying various drinks as well as options to select them
'''

typeOfdrink = int(input("Which type of drink would you like? \nPress 1 for Arizona iced Tea a small is $1.00, medium $2.00, large $3.00\
                            \nPress 2 for a Coca-Cola, a small is $1.50, medium is $3.00, large is $4.50\
                            \nPress 3 for a Water, a small is $0.75, medium is $1.50, large is $2.25\
                            \nPress 4 for a Orange Juice, a small is $2.00, medium is $4.00, large is $6.00"))
if(typeOfdrink == 1):
    cost = 1.00
    print("You have selected Arizona Iced Tea, a small costs $"+ str(cost)+ ".")
elif(typeOfdrink == 2):
    cost = 1.50
    print("You have selected Coca-Cola, a small costs $"+ str(cost)+ ".")
elif(typeOfdrink == 3):
    cost = 0.75
    print("You have entered a Water, a small costs $"+ str(cost)+ ".")
elif(typeOfdrink == 4):
    cost = 2.00
    print("You have entered a Orange Juice, a small costs $"+ str(cost)+ ".")
else:
    print("You have made an invalid selection please try again.")

size = raw_input("What size drink would you like? Please enter: \n'L' for Large \n'M' for Medium \n'S' for small ")

if((size == 'S') or (size == 's')):
    price = 1
    print("You have ordered a small drink. Thank you.")
elif(size == 'M') or (size == 'm'):
    price = 2
    print("You have ordered a medium drink. Thank you.")
elif(size == 'L') or (size == 'l'):
    price = 3
    print("You have ordered a large drink. Thank you.")
else:
    print("You have entered an invalid selection. Please try again")


from tgbot.commands.UserAccess import UserAccess
from tgbot.commands.base import BaseCommand

class SubHistory(BaseCommand):
    command_names = ['subhistory']
    access_level = UserAccess.CHAT_ADMIN

    def __init__(self, event, parsed):
        super().__init__(event, parsed, SubHistory.access_level)
        self.must_be_reply = True

    async def process(self):
        await self.fetch_data()

        if not (await self.can_process()):
            return

        target = await self.db.getUserByTgChatId(self.reply_message.sender_id)
        if target is None or len(target) == 0:
            await self.reply_fail(self.get_translation("CMD_SUB_HISTORY_NOT_VERIFIED"))
            return

        # Join two list results and order by timestamp

        datetime_string_format = '%Y-%m-%d %H:%M:%S'

        data_rows = await self.db.getTwitchSubHistoryRecords(self.channel['channel_id'], target[0]['user_id'])
        notification_rows = await self.db.getTwitchSubNotificationHistory(self.channel['channel_id'], target[0]['user_id'])

        result_rows = []
        if data_rows is not None:
            for data in data_rows:
                obj = {}
                obj['type'] = self.parse_event_type(data['event_type'])
                obj['is_gift'] = data['is_gift']
                obj['ts'] = data['event_ts'].strftime(datetime_string_format)

                result_rows.append(obj)

        if notification_rows is not None:
            for notification in notification_rows:
                obj = {}
                obj['type'] = 'NOTIFICATION' if notification['notice_type'] != 'subgift' else 'SUBSCRIBE'
                obj['is_gift'] = 1 if notification['notice_type'] == 'subgift' else 0
                obj['ts'] = notification['ts'].strftime(datetime_string_format)

                result_rows.append(obj)

        if result_rows is None or len(result_rows) == 0:
            await self.event.reply(self.get_translation('CMD_SUB_HISTORY_EMPTY'))
            return

        text = "{} {}\n\n".format(self.get_translation('CMD_SUB_HISTORY_TITLE'), target[0]['dname'] if target[0]['dname'] is not None else target[0]['name'])
        result_rows = sorted(result_rows, key=lambda row: row['ts'], reverse=True)
        for data in result_rows:
            text += "{} {}".format(data['ts'], self.get_translation('CMD_SUB_HISTORY_TYPE_{}'.format(data['type'])))
            if data['is_gift']:
                text += ' (gift)'
            text += '\n'

        await self.event.reply(text, link_preview=False)

    def parse_event_type(self, event_type):
        try:
            return event_type.split('.')[-1].upper()
        except Exception as ex:
            return 'unknown'


import streamlit as st
import time,datetime,pytz,os,json
import pandas as pd
import altair as alt
from PIL import Image

from timeplus import *

st.set_page_config(layout="wide")
col_img, col_txt, col_link = st.columns([1,8,5])
with col_img:
    image = Image.open("detailed-analysis@2x.png")
    st.image(image, width=100)
with col_txt:
    st.title("Real-time Insights for Github")
with col_link:
    st.markdown("[Source Code](https://github.com/timeplus-io/streamlit_apps/blob/main/pages/203_%F0%9F%92%BB_github_dashboard.py)", unsafe_allow_html=True)

env = Environment().address(st.secrets["TIMEPLUS_HOST"]).apikey(st.secrets["TIMEPLUS_API_KEY"]).workspace(st.secrets["TIMEPLUS_TENANT"])

# a wrapper to run batch SQL, return headers and rows
def batchQuery(bathSQL):
    q=Query(env=env).sql(query=bathSQL).create()
    header=q.metadata()["result"]["header"]
    rows=[]
    for event in q.result():
        if event.event != "metrics" and event.event != "query":
            for row in json.loads(event.data):
                rows.append(row)
    q.cancel()
    q.delete()
    return header,rows

def show_table_for_query(sql,table_name,row_cnt):
    st.code(sql, language="sql")
    query = Query(env=env).sql(query=sql).create()
    col = [h["name"] for h in query.metadata()["result"]["header"]]
    def update_table(row,name):
        data = {}
        for i, f in enumerate(col):
            data[f] = row[i]
            #hack show first column as more friendly datetime diff
            if i==0 and isinstance(row[i], str):
                data[f]=datetime.datetime.strptime(row[i], '%Y-%m-%dT%H:%M:%S').replace(tzinfo=pytz.UTC)
                # Get current UTC datetime with timezone awareness
                current_datetime = datetime.datetime.now(pytz.UTC)
                minutes=divmod((current_datetime-data[f]).total_seconds(),60)
                data[f]=f"{row[i]} ({int(minutes[0])} min {int(minutes[1])} sec ago)"

        df = pd.DataFrame([data], columns=col)
        if name not in st.session_state:
            st.session_state[name] = st.table(df)
        else:
            st.session_state[name].add_rows(df)
    # iterate query result
    limit = row_cnt
    count = 0
    for event in query.result():
        if event.event != "metrics" and event.event != "query":
            for row in json.loads(event.data):
                update_table(row,table_name)
                count += 1
                if count >= limit:
                    break
            # break the outer loop too
            if count >= limit:
                break
    query.cancel()
    query.delete()

col1, col2, col3 = st.columns([3,3,1])

with col1:
    st.header('New events every minute')
    sql="""SELECT window_end AS time,count() AS count from tumble(table(github_events),1m)
WHERE _tp_time > date_sub(now(), 2h) GROUP BY window_end"""
    st.code(sql, language="sql")
    result=batchQuery(sql)
    col = [h["name"] for h in result[0]]
    df = pd.DataFrame(result[1], columns=col)
    c = alt.Chart(df).mark_line(point=alt.OverlayMarkDef()).encode(x='time:T',y='count:Q',tooltip=['count'],color=alt.value('#D53C97'))
    st.altair_chart(c, use_container_width=True)

    st.header('Recent events')
    show_table_for_query('SELECT created_at,actor,type,repo FROM github_events','live_events',3)

with col2:
    #st.header('New repos')
    #show_table_for_query("""SELECT created_at,actor,repo,json_extract_string(payload,'master_branch') AS branch \nFROM github_events WHERE type='CreateEvent'""",'new_repo',3)

    st.header('Default branch for new repos')
    sql="""SELECT payload:master_branch AS branch,count(*) AS cnt
FROM table(github_events) WHERE _tp_time>date_sub(now(),1h) AND type='CreateEvent'
GROUP BY branch ORDER BY cnt DESC LIMIT 3"""
    st.code(sql, language="sql")
    result=batchQuery(sql)
    col = [h["name"] for h in result[0]]
    df = pd.DataFrame(result[1], columns=col)
    base = alt.Chart(df).encode(theta=alt.Theta('cnt:Q',stack=True),color=alt.Color('branch:N',legend=None),tooltip=['branch','cnt'])
    pie=base.mark_arc(outerRadius=80)
    text = base.mark_text(radius=110, size=16).encode(text='branch:N')
    st.altair_chart(pie+text, use_container_width=True)

    st.header('Hot repos')
    sql="""SELECT max(created_at) AS followed_at, repo, count(distinct actor) AS new_followers
FROM table(github_events) WHERE _tp_time>date_sub(now(),10m) AND type ='WatchEvent'
GROUP BY repo ORDER BY new_followers DESC LIMIT 3
"""
    show_table_for_query(sql,'star_table',3)

# show a changing single value for total events
with col3:
    st.header('Event count')
    st.code("SELECT count(*) FROM github_events EMIT periodic 1s", language="sql")
    with st.empty():
        #show the initial events first
        sql="select count(*) from table(github_events)"
        cnt=batchQuery(sql)[1][0][0]
        st.metric(label="Github events", value="{:,}".format(cnt))
        st.session_state.last_cnt=cnt

        #create a streaming query to update counts
        sql=f"select {cnt}+count(*) as events from github_events emit periodic 1s"
        query = Query(env=env).sql(query=sql).create()
        def update_row(row):
            delta=row[0]-st.session_state.last_cnt
            if (delta>0):
                st.metric(label="Github events", value="{:,}".format(row[0]), delta=row[0]-st.session_state.last_cnt, delta_color='inverse')
                st.session_state.last_cnt=row[0]
        # iterate query result
        limit = 200
        count = 0
        for event in query.result():
            if event.event != "metrics" and event.event != "query":
                for row in json.loads(event.data):
                    update_row(row)
                    count += 1
                    if count >= limit:
                        break
                # break the outer loop too
                if count >= limit:
                    break
        query.cancel()
        query.delete()


mat1 = []
mat2 = []
tempm1=[]
print('Addition of matrix')
rows1 = int(input('Enter number of rows1: '))
colm1 = int(input('Enter number of colm1: '))
rows2 = int(input('Enter number of rows2: '))
colm2 = int(input('Enter number of colm2: '))
if rows1==rows2 and colm1==colm2:
    for a1 in range(rows1):
        for b1 in range(colm1):
            print('Enter input for matrix 1 for [%d] [%d]'%(a1,b1))
            in1 = int(input())
            tempm1.append(in1)
        tempc = tempm1.copy()
        mat1.append(tempc)
        tempm1.clear()

    for a1 in range(rows2):
        for b1 in range(colm2):
            print('Enter input for matrix 2 for [%d] [%d]'%(a1,b1))
            in1 = int(input())
            tempm1.append(in1)
        tempc = tempm1.copy()
        mat2.append(tempc)
        tempm1.clear()
    print('\nMatrix1: ',mat1)
    print('Matrix2: ',mat2)

    res2=[]
    temp=[]

    for x1 in range(rows1):
        res=[]
        for y1 in range(colm1):
            res.append(mat1[x1][y1] + mat2[x1][y1])
        temp = res.copy()
        res2.append(temp)

    print('Result : ',res2)
    print('\nMatrix:')
    for innerlist in res2:
        print(innerlist)
#         for num in innerlist:
#             print(num,end=' ')
#             print()
else:
    print('Rows and Columns are not equal for Addition of matrix')

print('\n \n \n \n \n \n \n \n \n \n \n \n')


import sys
sys.path.insert(0,"C:\\module_jeu_threes\\game\\play")
sys.path.insert(0,'C:\\module_jeu_threes\\ui\\play_display')

from tableau_al import tableau_al
from full_display import full_display
from columns_moves import columns_moves
from lines_moves import lines_moves

a=tableau_al(2)

def play_move(plateau,sens):
    if sens=='h':
        sens=1
        columns_moves(plateau,sens)
    elif sens=='b':
        sens=0
        columns_moves(plateau,sens)
    elif sens=='g':
        sens=1
        lines_moves(plateau,sens)
    elif sens=='d':
        sens=0
        lines_moves(plateau,sens)
    return plateau

#full_display(a)
#full_display(play_move(a,'d'))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Susanne Reinhardt & Rafal Kowalewski

Calculates nearest neighbor distances within datasets and between both
imaging rounds. Results are saved as csv in a subfolder called called
'AdditionalOutputs'.
For the crossNND distance between imaging rounds, the coordinates of the respective
partner in the other dataset are saved as additional columns in the _resi..hdf5
files as well as their distance. This file is then called _resi.._info.hdf5

"""
import numpy as _np
import numpy as np
import pandas as pd
import sys
import os
from sklearn.neighbors import NearestNeighbors as NN

from Functions import tools

def nn_analysis(
    x1, x2,
    y1, y2,
    z1, z2,
    nn_count,
    same_channel,
):
    '''
    Searches the nearest neighbor of dataset 2 coordinates in dataset 1.

    Parameters
    ----------
    x1 : pandas series
    x2 : pandas series
    y1 : pandas series
    y2 : pandas series
    z1 : pandas series
    z2 : pandas series
        Coordinates of two datasets.
    nn_count : int
        Input value for sklearn's NearestNeighbors function. Sets up until
        which order higher nearest neighbors should be calculated,
        f.ex. 1st, 2nd or until 3rd NND
    same_channel : bool
        if True, both datasets are equal and the NND distribution is calculated
        within one dataset.
        if False, both datasets differ and the nearest neighbor of each
        coordinate in dataset 2 is searched in dataset 1.

    Returns
    -------
    nnd : list
        Nearest Neighbor Distance. Optionally higher NNDs in further columns.
    nn_indices : list
        Index of nearest neighbors in dataset 1 to dataset 2 coordinates.
    nn_partner : np array
        Coordinates of nearest neighbors in dataset 1 to dataset 2 coordinates.

    '''
    if z1 is not None: # 3D
        input1 = _np.stack((x1, y1, z1)).T
        input2 = _np.stack((x2, y2, z2)).T
    else: # 2D
        input1 = _np.stack((x1, y1)).T
        input2 = _np.stack((x2, y2)).T
    if same_channel:
        model = NN(n_neighbors=nn_count+1)
    else:
        model = NN(n_neighbors=nn_count)
    model.fit(input1)
    nnd, indices = model.kneighbors(input2)

    if same_channel:
        nnd = nnd[:, 1:] # ignore the zero distance

        # Get indices for first NND partners (if same+channel = True the first
        # column corresponds to the distance measured to itself)
        nn_indices = [sublist[1] for sublist in indices]

    else:
        # Get indices for first NND partners
        nn_indices = [sublist[0] for sublist in indices]

    nn_partner = np.array([input1[nn_indices[i]] for i in range(len(input2))])

    return nnd, nn_indices, nn_partner

def nearest_neighbor(channel1_name, file_resi1, channel2_name, file_resi2, px_size):
    '''
    Initiates nearest neighbor calculations betweend two datasets than can be
    equal or different.
    Saves calculated distances in .csv format. In case of two different
    datasets it adds columns to the resi hdf5 files with the coordinates
    of the nearest neighbor in the other file and the distance to it.

    Parameters
    ----------
    channel1_name : string
        Name of channel 1.
    file_resi1 : string
        Path and filename of the hdf5 file containing the channel 1 RESI locs.
    channel2_name : string
        Name of channel 2.
    file_resi2 : string
        Path and filename of the hdf5 file containing the channel 2 RESI locs.
    px_size : ing
        Pixel size in nm..

    '''

    # NND within channel or crossNND betwen channels?
    # used for avoiding zero distances (to self)
    same_channel = file_resi1 == file_resi2

    """load Resi files"""

    df_resi1 = pd.read_hdf(file_resi1, key = 'locs')
    x1 = df_resi1['x']*px_size  # Input is in px
    y1 = df_resi1['y']*px_size
    try:
        z1 = df_resi1['z'] # Input is in nm
        flag_3D_1 = True
    except:
        z1 = None
        flag_3D_1 = False

    if not same_channel: # load second channel
        df_resi2 = pd.read_hdf(file_resi2, key = 'locs')
        x2 = df_resi2['x']*px_size  # Input is in px
        y2 = df_resi2['y']*px_size
        try:
            z2 = df_resi2['z'] # Input is in nm
            flag_3D_2 = True
        except:
            z2 = None
            flag_3D_2 = False

        if not flag_3D_1 == flag_3D_2:
            sys.exit("Both datasets have to be either 2D or 3D.")
    else: # same channel
        x2 = x1
        y2 = y1
        z2 = z1

    flag_3D = flag_3D_1

    if same_channel:
        nn_count = 1 # only first nearest neighbor
        # The first NN will be calculated to itself, so we will later discard
        # the first column and take only the second column corresponding to the
        # the conventioanl first neareast neighbor.
    else:
        nn_count = 1 # only first cross nearest neighbor

    nnd, nn_indices, nn_partner = nn_analysis(
        x1, x2,
        y1, y2,
        z1, z2,
        nn_count,
        same_channel,
    )

    # Create subfolder for nearest neighbor csv files
    try:
        os.mkdir(os.path.split(file_resi1)[0] + '/AdditionalOutputs')
    except OSError:
        pass
    path =  os.path.split(file_resi1)[0] + "/AdditionalOutputs/"
    fname = path + os.path.split(file_resi1)[1]

    # save nn distances as csv
    if same_channel:
        np.savetxt('%s_nn_%s.csv' %(fname[:-5], channel1_name), nnd)
    else:
        np.savetxt('%s_nn_%s_to_%s.csv' %(fname[:-5], channel1_name, channel2_name), nnd)

    # Extend the content of file_resi_2 with columns containing the coordinates
    # to its nearest neighbors in file_resi1 as well as their distance and
    # orientation in the xy plane to each other

    if not same_channel:
        df_resi2['crossNND_ID'] = nn_indices
        df_resi2['crossNND_x'] = nn_partner[:,0]/px_size # Back from nm to pix
        df_resi2['crossNND_y'] = nn_partner[:,1]/px_size
        if flag_3D:
            df_resi2['crossNND_z'] = nn_partner[:,2]/px_size # save this in pix
        df_resi2['crossNND'] = nnd
        if flag_3D:
            df_resi2['crossNND_dxy'] = np.sqrt((df_resi2['x']-df_resi2['crossNND_x'])**2+
                                                 (df_resi2['y']-df_resi2['crossNND_y'])**2)*px_size
            df_resi2['crossNND_dz'] = (df_resi2['z']-df_resi2['crossNND_z']*px_size)
        df_resi2['orientation'] = tools.angle(df_resi2['x'], df_resi2['y'], df_resi2['crossNND_x'], df_resi2['crossNND_y'])

        path = os.path.split(file_resi2)[0] + "/"
        filename_old = os.path.split(file_resi2)[1]
        filename_new = '%s_info.hdf5' % (filename_old[:-5])
        tools.picasso_hdf5(df_resi2, filename_new, filename_old, path)


from pathlib import Path
import json
import logging
import os
from typing import Dict, Iterator
from composer.efile.xmlio import JsonTranslator
from concurrent.futures import ProcessPoolExecutor

logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)

root_dir: str = "/Volumes/Bulk/efile"
xml_dir: str = os.path.join(root_dir, "xml")
json_dir: str = os.path.join(root_dir, "json")

translate: JsonTranslator = JsonTranslator()

# This works fast. Why does filings.py work slow?
def convert(xml_path: Path):
    xml_fn: str = str(xml_path)
    json_relpath: str = "/".join(xml_fn.split("/")[-3:]).split(".")[0] + ".json"
    json_fn: str = os.path.join(json_dir, json_relpath)
    json_dirpath: str = "/".join(json_fn.split("/")[:-1])
    os.makedirs(json_dirpath, exist_ok=True)
    with open(xml_fn) as xml_fh:
        raw_xml = xml_fh.read()
        if raw_xml.strip() == "":
            logging.error("%s is empty. Skipping." % xml_fn)
            return
    with open(json_fn, "w") as json_fh:
        as_json: Dict = translate(raw_xml)
        json.dump(as_json, json_fh)

xml_paths: Iterator[Path] = Path(xml_dir).glob("**/*.xml")

with ProcessPoolExecutor() as executor:
    executor.map(convert, xml_paths)


# encoding:utf-8
import socket
import json
from utils.convert import *
def udp_receive_message(ip_addr,port):
    """使用udp连接方式循环接收数据，输入IP地址(字符串类型)和端口（数值类型）"""
    ip_addr_str = str(ip_addr)  # 转换成字符串类型
    # 1.创建套接字
    udp_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
    # 2.绑定本地信息
    addr = (ip_addr_str,port)
    udp_socket.bind(addr)
    # 3.创建存储发动机转速数据的结构
    latitude_deg_data=[]
    longitude_deg_data=[]
    # 3接受数据
    while True:
        rec_data = udp_socket.recvfrom(1024)
        rec_msg = rec_data[0].decode()
        str_recmsg = "{"+rec_msg[:-1]+"}"
        dict_recmsg = json.loads(str_recmsg)
        latitude_deg_data.append(dict_recmsg.get("latitude-deg"))
        longitude_deg_data.append(dict_recmsg.get("longitude-deg"))
        #savedata2xlsx(latitude_deg_data)
        longitude_deg_data = [str(i) for i in latitude_deg_data]
        latitude_deg_data = [str(i) for i in latitude_deg_data]
        location=[longitude_deg_data,latitude_deg_data]
        xw_toexcel(location,'E:\\test_data\\test.xlsx')
        #send_addr = rec_data[1] 主机地址信息
        # 打印收到的数据
        # print(rec_data)
        #coordinate=zip(longitude_deg_data,latitude_deg_data)
        #print(dict(coordinate))
        #print(rec_data)  #数据来源
        #print(type(data))
        # print("%s:%s" % (str(send_addr), rec_msg.decode("gb18030")))
    # 关闭套接字
    udp_socket.close()