from __future__ import absolute_import, print_function

import json

# pylint: disable=W0611
from autopkglib import Processor, ProcessorError, URLGetter  # noqa: F401

__all__ = ["ARCHICADUpdatesProcessor"]

# pylint: disable=E0239
# pylint: disable=R0903
class ARCHICADUpdatesProcessor(URLGetter):
    """
    This processor finds the URL for the desired version, localization, and
    type of ARCHICAD.
    """

    input_variables = {
        "major_version": {
            "required": True,
            "description": (
                "The ARCHICAD Major Version to look for available patches."
            ),
        },
        "localization": {
            "required": True,
            "description": "The Localization to looks for available patches.",
        },
        "release_type": {
            "required": True,
            "description": "The release type to look for available patches.",
        },
        "ARCHITECTURE": {
            "required": False,
            "description": "INTEL or ARM, falls back to INTEL if not set.",
        },
    }
    # Amended to output build number and version (jutonium)
    output_variables = {
        "url": {"description": "Returns the url to download."},
        "build": {"description": "Returns the build number."},
        "supported_architecture": {
            "description": "Returns a corresponding string for Munki"
        },
        "version": {
            "description": "Returns the version computed from major_version "
            "and build number. Same as CFBundleVersion."
        },
    }

    description = __doc__

    def main(self):
        """Main process."""

        # Define some variables.
        major_version = self.env.get("major_version")
        localization = self.env.get("localization")
        release_type = self.env.get("release_type")
        architecture = self.env.get("ARCHITECTURE", "INTEL")
        available_builds = {}

        # Grab the available downloads.
        # Fixed URL (jutonium)
        response = self.download(
            "https://graphisoft.com/ww/service/downloads/archicad-updates",
            headers={"Accept": "application/json"},
        )
        json_data = json.loads(response)

        # Parse through the available downloads for versions that match the
        # requested paramters.
        # Adress potential python runtime errors by checking for the existence
        # of "build". (jutonium)
        for json_object in json_data:
            if all(
                (
                    json_object.get("version") == major_version,
                    json_object.get("localization") == localization,
                    json_object.get("type") == release_type,
                    json_object.get("build"),
                )
            ):
                # Handling of new internal structure (jutonium)
                mac_link = (
                    json_object.get("downloadLinks", {})
                    .get("mac", {})
                    .get("url")
                )

                if mac_link and mac_link.endswith(f"-{architecture}.dmg"):
                    mac_link = "https://dl.graphisoft.com" + mac_link[3:]
                    available_builds[json_object.get("build")] = mac_link

        # Get the latest version.
        # Avoid unrelated errors and compute propper version (jutonium)
        if available_builds:
            build = sorted(available_builds.keys())[-1]
            version = f"{major_version}.0.0.{build}"
            url = available_builds[build]
            build = str(build)
        else:
            build = "0"
            version = "0"
            url = None

        if url:
            self.env["url"] = url
            self.output(f"Download URL: {url}")
            # Build and version instead of build as version (jutonium)
            self.env["build"] = build
            self.output(f"build: {build}")
            self.env["version"] = version
            self.output(f"version: {version}")
            if architecture == "ARM":
                self.env["supported_architecture"] = "arm64"
            else:
                self.env["supported_architecture"] = "x86_64"
        else:
            raise ProcessorError(
                "Unable to find a url based on the parameters provided."
            )

if __name__ == "__main__":
    PROCESSOR = ARCHICADUpdatesProcessor()
    PROCESSOR.execute_shell()


import warnings
from collections import OrderedDict
from io import BytesIO

import numpy as np
import pandas
from pandas.core.dtypes.cast import find_common_type
from pandas.core.dtypes.concat import union_categoricals
from pandas.io.common import infer_compression

from modin.core.execution.ray.implementations.cudf_on_ray.partitioning.partition_manager import (
    GPU_MANAGERS,
)
from modin.core.io.file_dispatcher import OpenFile
from modin.core.storage_formats.pandas.utils import split_result_of_axis_func_pandas
from modin.error_message import ErrorMessage

def _split_result_for_readers(axis, num_splits, df):  # pragma: no cover
    """Splits the DataFrame read into smaller DataFrames and handles all edge cases.

    Args:
        axis: Which axis to split over.
        num_splits: The number of splits to create.
        df: The DataFrame after it has been read.

    Returns:
        A list of pandas DataFrames.
    """
    splits = split_result_of_axis_func_pandas(axis, num_splits, df)
    if not isinstance(splits, list):
        splits = [splits]
    return splits

def find_common_type_cat(types):
    if all(isinstance(t, pandas.CategoricalDtype) for t in types):
        if all(t.ordered for t in types):
            return pandas.CategoricalDtype(
                np.sort(np.unique([c for t in types for c in t.categories])[0]),
                ordered=True,
            )
        return union_categoricals(
            [pandas.Categorical([], dtype=t) for t in types],
            sort_categories=all(t.ordered for t in types),
        ).dtype
    else:
        return find_common_type(types)

class cuDFParser(object):
    @classmethod
    def get_dtypes(cls, dtypes_ids):
        return (
            pandas.concat(cls.materialize(dtypes_ids), axis=1)
            .apply(lambda row: find_common_type_cat(row.values), axis=1)
            .squeeze(axis=0)
        )

    @classmethod
    def single_worker_read(cls, fname, *, reason, **kwargs):
        ErrorMessage.default_to_pandas(reason=reason)
        # Use default args for everything
        pandas_frame = cls.parse(fname, **kwargs)
        if isinstance(pandas_frame, pandas.io.parsers.TextFileReader):
            pd_read = pandas_frame.read
            pandas_frame.read = (
                lambda *args, **kwargs: cls.query_compiler_cls.from_pandas(
                    pd_read(*args, **kwargs), cls.frame_cls
                )
            )
            return pandas_frame
        elif isinstance(pandas_frame, (OrderedDict, dict)):
            return {
                i: cls.query_compiler_cls.from_pandas(frame, cls.frame_cls)
                for i, frame in pandas_frame.items()
            }
        return cls.query_compiler_cls.from_pandas(pandas_frame, cls.frame_cls)

    infer_compression = infer_compression

class cuDFCSVParser(cuDFParser):
    @classmethod
    def parse(cls, fname, **kwargs):
        warnings.filterwarnings("ignore")
        num_splits = kwargs.pop("num_splits", None)
        start = kwargs.pop("start", None)
        end = kwargs.pop("end", None)
        index_col = kwargs.get("index_col", None)
        gpu_selected = kwargs.pop("gpu", 0)

        if start is not None and end is not None:
            put_func = cls.frame_partition_cls.put

            # pop "compression" from kwargs because bio is uncompressed
            with OpenFile(fname, "rb", kwargs.pop("compression", "infer")) as bio:
                if kwargs.get("encoding", None) is not None:
                    header = b"" + bio.readline()
                else:
                    header = b""
                bio.seek(start)
                to_read = header + bio.read(end - start)
            pandas_df = pandas.read_csv(BytesIO(to_read), **kwargs)
        else:
            # This only happens when we are reading with only one worker (Default)
            pandas_df = pandas.read_csv(fname, **kwargs)
            num_splits = (
                1  # force num_splits to be 1 here because we don't want it partitioning
            )
        if index_col is not None:
            index = pandas_df.index
        else:
            index = len(pandas_df)
        partition_dfs = _split_result_for_readers(1, num_splits, pandas_df)
        key = [
            put_func(GPU_MANAGERS[gpu_selected], partition_df)
            for partition_df in partition_dfs
        ]
        return key + [index, pandas_df.dtypes]


import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
import numpy as np
import pandas as pd
import shutil

from LIBS.ImgPreprocess import my_preprocess
from LIBS.Neural_Networks.Heatmaps.IntegratedGradient import my_helper_gradients
from tensorflow import keras
from LIBS.Generator import my_images_generator_2d

DIR_PREPROCESS = '/media/ubuntu/data1/糖网项目/DR分级英国标准_20190119_无杂病/DR/preprocess384/'
DIR_DEST_HEATMAP = '/tmp5/DR_english_2020_6_23_new/Integrated_Gradients'

TRAIN_TYPE = 'DR_english'
DATA_VERSION = 'v1'

model_dir = '/tmp5/models_2020_6_19/DR_english/v1'
dicts_models = []
dict_model1 = {'model_file': os.path.join(model_dir, 'InceptionResnetV2-004-0.984.hdf5'),
               'input_shape': (299, 299, 3), 'model_weight': 1}
dicts_models.append(dict_model1)

for dict1 in dicts_models:
    print('prepare to load model:' + dict1['model_file'])
    dict1['model'] = keras.models.load_model(dict1['model_file'], compile=False)
    print('model load complete!')

for predict_type_name in ['split_patid_train', 'split_patid_valid', 'split_patid_test']:
    filename_csv = os.path.join(os.path.abspath('../../../'),
            'datafiles', TRAIN_TYPE, '{}_{}.csv'.format(predict_type_name, DATA_VERSION))

    my_gradients = my_helper_gradients.My_gradients(model=dicts_models[0]['model'])

    df = pd.read_csv(filename_csv)
    for _, row in df.iterrows():
        image_file = row['images']
        image_label = int(row['labels'])
        # img_source = image_file.replace('/preprocess384/', '/original/')

        assert DIR_PREPROCESS in image_file, 'preprocess directory error'
        preprocess = False
        input_shape = (299, 299, 3)
        if preprocess:
            img_preprocess = my_preprocess.do_preprocess(image_file, crop_size=384)
            img_input = my_images_generator_2d.my_gen_img_tensor(img_preprocess,
                                                                    image_shape=input_shape)
        else:
            img_source = image_file
            img_input = my_images_generator_2d.my_gen_img_tensor(image_file,
                                                                    image_shape=input_shape)

        model1 = dicts_models[0]['model']
        probs = model1.predict(img_input)
        class_predict = np.argmax(probs)

        if (class_predict == 1 and image_label == 1) or (class_predict == 1 and image_label == 0):
            filename_heatmap = my_gradients.gen_integrated_gradients(img_input=img_input,
                pred_class=class_predict, gen_gif=True)

            #jpeg, gif, file extension may be fifferent.
            _, file_name = os.path.split(filename_heatmap)
            save_dir = os.path.join(DIR_DEST_HEATMAP, predict_type_name)
            if class_predict == 1 and image_label == 1:
                dest_dir = os.path.dirname(image_file.replace(DIR_PREPROCESS, os.path.join(save_dir, '1_1/')))
            if class_predict == 1 and image_label == 0:
                dest_dir = os.path.dirname(image_file.replace(DIR_PREPROCESS, os.path.join(save_dir, '0_1/')))
            os.makedirs(dest_dir, exist_ok=True)
            file_dest = os.path.join(dest_dir, file_name)
            shutil.copy(filename_heatmap, file_dest)
            print(file_dest)

print('OK!')


#
# @lc app=leetcode.cn id=63 lang=python3
#
# [63] 不同路径 II
#

# @lc code=start
class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        # 最快
        # m, n = len(obstacleGrid), len(obstacleGrid[0])
        # dp = [[0] * n for _ in range(m)]
        # if obstacleGrid[0][0] == 0:
        #     dp[0][0] = 1
        # for i in range(m):
        #     for j in range(n):
        #         if obstacleGrid[i][j] == 0:
        #             if i == j == 0:
        #                 continue
        #             else:
        #                 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        #                 # 此时假设i==0而j!=0，但是由于i-1=-1，即最后一行中的
        #                 # 数据——0（先前初始化的），所以不影响整体，可以减少判
        #                 # 断
        # return dp[m - 1][n - 1]

        m = len(obstacleGrid)
        n = len(obstacleGrid[0])
        dp = [[0 for _ in range(n)]for _ in range(m)]
        for i in range(m):
            for j in range(n):
                if obstacleGrid[i][j] == 1:
                    continue
                else:
                    if i == j == 0:
                        dp[i][j] = 1
                    else:
                        dp[i][j] = dp[i-1][j] + dp[i][j-1]
        return dp[-1][-1]

# @lc code=end


# !/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import logging

from PyQt4.QtCore import SIGNAL, QString
from basecontroller import BaseController, singleton
# from user_controller import UserController
# sys.path.append('../')

from util.util import print_trace_exception, log_callback

SEND_MSG_ID = 'SEND_MSG'
GET_MSG_ID = 'GET_MSG'
JOIN_CHAT_ROOM_ID = 'JOIN_CHAT_ROOM'
SERVICE_NAME = 'ChatService'

@singleton
class ChatController(BaseController):

    def __init__(self):
        BaseController.__init__(self, SERVICE_NAME)
        self.c.register(GET_MSG_ID, self.get_msg_cb)
        self.c.register(SEND_MSG_ID, self.send_msg_cb)
        self.c.register(JOIN_CHAT_ROOM_ID, self.join_chat_room_cb)
        self.chat_token_pool = {}  # to avoid unnecessary update
        # self.user_controller = UserController()
        self.counter = 0

    def send_msg(self, cid, uid, msg, username):
        print('called send msg')
        client = self.get_client()
        req = {
            'cid': cid,
            'uid': uid,
            'msg': msg,
            'username': username
        }
        client.send(service_name=SERVICE_NAME, method=SEND_MSG_ID, msg=req)

    def add_polling_msg_task(self, cid, uid):
        client = self.get_client()
        client.set_periodic_task(self.get_msg, (cid, uid), self.get_msg_cb, GET_MSG_ID)

    @log_callback
    def send_msg_cb(self, data):
        # logging.debug('send_msg %s', data)
        self.emit(SIGNAL("send_msg_callback(int)"), data['code'])

    def get_msg(self, cid, uid):
        logging.debug('Call get msg %d %d', cid, uid)
        client = self.get_client()
        req = {
            'cid': cid,
            'uid': uid
        }

        client.send(service_name=SERVICE_NAME, method=GET_MSG_ID, msg=req)

    @log_callback
    def get_msg_cb(self, data):
        if data and data.get('code') == 200:
            token = data.get('token')
            cid = data.get('cid')
            if cid is None:
                logging.debug("received %s", data)
            if token != self.chat_token_pool.get(cid):
                self.chat_token_pool[cid] = token
                self.emit(SIGNAL('clear'))
                for item in data.get(u'data'):
                    text = '{}: {} at{}'.format(item.get('username'),
                                                item.get('msg'),
                                                item.get('time'))
                    self.emit(SIGNAL("showRoomTextWithRGB(QString,int,int,int)"), text, 0, 0, 0)

    def join_chat_room(self, cid, uid):
        client = self.get_client()
        req = {
            'cid': cid,
            'uid': uid,
            # '-----': self.counter,
        }
        self.counter += 1
        client.send(service_name=SERVICE_NAME, method=JOIN_CHAT_ROOM_ID, msg=req)

    @log_callback
    def join_chat_room_cb(self, data):
        code = data.get('code')
        if code == 200:
            cid = data.get('cid')
            uid = data.get('uid')
            self.add_polling_msg_task(cid=cid, uid=uid)
        else:
            self.emit(SIGNAL("error_msg(QString)"), QString(data['code']))


import json
from collections import Iterable, Sized, namedtuple

import six

from .disk import Disk
from .errors import CorruptRod, DuplicateDisk
from .utils import Serializable
from .validation import Validatable

__all__ = ['Rod']

class Rod(
    namedtuple('Rod', ('name', 'disks', 'height')), Iterable, Sized, Validatable, Serializable
):
    """
    A single tower containing disks.
    """

    def __new__(cls, name, disks=None, height=0):
        """
        :param str name:
            The name of the rod.
        :param List[Disk] disks:
            (optional) mutatable list of `Disks`.
        :param int height:
            The height of the rod.
        :rtype: Rod
        :raises: See `Rod.validate`.
        """
        self = super(Rod, cls).__new__(cls, name, disks or [], height)
        self.validate()
        return self

    def to_json(self):
        """
        Return a json serializable representation of this instance.

        :rtype: object
        """
        return {
            'name': self.name,
            'height': self.height,
            'disks': [i.to_json() for i in self.disks],
        }

    @classmethod
    def from_json(cls, d):
        """
        Return a class instance from a json serializable representation.

        :param Union[str,dict] d:
            The json or decoded-json from which to create a new instance.
        :rtype: Rod
        :raises: See `Rod.__new__`.
        """
        if isinstance(d, six.string_types):
            d = json.loads(d)
        return cls(
            name=d.pop('name'),
            height=d.pop('height'),
            disks=[Disk.from_json(i) for i in d.pop('disks')],
        )

    def __len__(self):
        return self.height

    def __copy__(self):
        """
        Return a shallow copy of this instance.

        :rtype: Rod
        """
        return Rod(
            self.name,
            disks=self.disks,
            height=self.height,
        )

    def __deepcopy__(self, *d):
        """
        Return a deep copy of this instance.

        :param dict d:
            Memoisation dict.
        :rtype: Rod
        """
        return Rod(
            self.name,
            disks=self.disks[:],
            height=self.height,
        )

    def __str__(self):
        return '{name}({rod})'.format(
            name=self.name,
            rod=self.disks,
        )

    def __eq__(self, other):
        """
        Compare Rod instances for equivalence.

        :param Rod other:
        :rtype: bool
        """
        if isinstance(other, Rod):
            if other.height == self.height:
                if other.disks == self.disks:
                    return True

    def __bool__(self):
        """
        A Rod is considered True if it contains any disks.

        :rtype: bool
        """
        return self.__nonzero__()

    def __nonzero__(self):
        """
        A Rod is considered non-zero if it contains any disks.

        :rtype: bool
        """
        return bool(self.disks)

    def pop(self):
        """
        Pop the top most disk from this rod and return it

        :rtype: Disk
        """
        return self.disks.pop()

    def append(self, disk, validate=True):
        """
        Append the disk to this rod and optionally validate.

        :param Disk disk:
            The disk to add to the top of our rod.
        :param bool validate:
            True=perform self validation.
        """
        self.disks.append(disk)
        if validate:
            self.validate()

    def __iter__(self):
        """
        Iterate over all the disks in this rod.

        :rtype: Disk
        """
        for disk in self.disks:
            yield disk

    def validate(self):
        """
        Perform self validation.

        :raises DuplicateDisk:
            This rod already contains this disk
        :raises CorruptRod:
            A disk is on top of a disk of smaller size.
        :raises InvalidTowerHeight:
            The height of the tower is invalid.
        :raises InvalidDiskPosition:
            The position of the disk is invalid.
        """
        width = 0
        seen = set()

        for disk in reversed(list(iter(self))):
            disk_width = disk.width
            if disk_width in seen:
                raise DuplicateDisk(self, disk_width)
            seen.update([disk_width])

            if disk.width < width:
                raise CorruptRod(self, disk)
            width = disk_width

            disk.validate()


import ffmpeg
import numpy as np
import glob
import os
import cv2
import csv
from transnetv2 import TransNetV2

#format of path should be like this
#video_paths = sorted(glob.glob('*\\data\\video_test.mp4'))
#des_path = '*\\data\\key_frame'

class Transnet_model:

    def __init__(self,video_paths,des_path):
        self.model = TransNetV2()
        self.video_path = sorted(glob.glob((video_paths)))
        self.des_path = des_path

    def get_frames(self,fn, width=48, height=27):
        self.video_stream, err = (
        ffmpeg
        .input(fn)
        .output('pipe:', format='rawvideo', pix_fmt='rgb24', s='{}x{}'.format(width, height))
        .run(capture_stdout=True, capture_stderr=True)
        )
        self.video = np.frombuffer(self.video_stream, np.uint8).reshape([-1, height, width, 3])
        return self.video

    def process_video(self):
        folder_name = os.path.basename(self.video_path).replace('.mp4', '')
        folder_path = os.path.join(self.des_path, folder_name)
        os.makedirs(folder_path, exist_ok=True)

        video = Transnet_model.get_frames(self.video_path, width=48, height=27)
        single_frame_predictions, _ = self.model.predict_frames(video)
        scenes = self.model.predictions_to_scenes(single_frame_predictions)

        cam = cv2.VideoCapture(self.video_path)
        currentframe = 0
        index = 0

        while True:
                ret, frame = cam.read()
                if ret:
                    currentframe += 1
                    idx_first = int(scenes[index][0])
                    idx_end = int(scenes[index][1])
                    idx_025 = int(scenes[index][0] + (scenes[index][1]-scenes[index][0])/4)
                    idx_05 = int(scenes[index][0] + (scenes[index][1]-scenes[index][0])/2)
                    idx_075 = int(scenes[index][0] + 3*(scenes[index][1]-scenes[index][0])/4)

                # Sử dụng chỉ số "n" từ last_n + 1 khi ghi dữ liệu vào file CSV
                    if currentframe - 1 == idx_first:
                        filename_first = "{}/{:0>4d}.jpg".format(folder_path, idx_first)
                    # video_save = cv2.resize(video[idx_first], (1280,720))
                        cv2.imwrite(filename_first, frame)
                    if currentframe - 1 == idx_025:
                        filename_025 = "{}/{:0>4d}.jpg".format(folder_path, idx_025)
                    # video_save = cv2.resize(video[idx_025], (1280,720))
                        cv2.imwrite(filename_025, frame)

                # #### 05 ####
                    if currentframe - 1 == idx_05:
                        filename_05 = "{}/{:0>4d}.jpg".format(folder_path, idx_05)
                    # video_save = cv2.resize(video[idx_05], (1280,720))
                        cv2.imwrite(filename_05, frame)
                # #### 075 ####
                    if currentframe - 1 == idx_075:
                        filename_075 = "{}/{:0>4d}.jpg".format(folder_path, idx_075)
                    # video_save = cv2.resize(video[idx_075], (1280,720))
                        cv2.imwrite(filename_075, frame)
                    if currentframe - 1 == idx_end:
                        filename_end = "{}/{:0>4d}.jpg".format(folder_path, idx_end)
                    # video_save = cv2.resize(video[idx_end], (1280,720))
                        cv2.imwrite(filename_end, frame)
                        index += 1
                else:
                    break

        cam.release()
        cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
"""
Created on Mon Nov 23 09:30:53 2015

@author: voxxys
"""
from pylsl import StreamInlet, resolve_stream

import time
import numpy as np
from scipy import io
from scipy.signal import butter, lfilter
from scipy.linalg import eig
import matplotlib.pyplot as plt
import theano
import os
import scipy.signal as spsig

import pickle

os.chdir('D:/BCI_MINI/recordings')

class params:
    def __init__(self):
        self.numch = 0 #TOFIX to fix elsewhere

        self.srate = 0
        self.win_av = 0

        self.without_emp_mask = 0

        self.pre_fl = 0
        self.pre_fh = 0

        self.filt_order = 0

        self.M_eog = 0
        self.all_CSPs = 0
        self.freqs = 0

        self.W1_saved = 0
        self.b1_saved = 0
        self.W2_saved = 0
        self.b2_saved = 0

with open('params_0.pkl', 'rb') as input:
        params_1 = pickle.load(input)

all_CSPs = params_1.all_CSPs
filtorder = params_1.filt_order
win = params_1.win_av
freq = params_1.freqs
srate = params_1.srate
M_eog = params_1.M_eog

fmin_pre = params_1.pre_fh
fmax_pre = params_1.pre_fl

without_emp_mask = params_1.without_emp_mask

##NN

# ____________________Set NN____________________

X = theano.tensor.fmatrix('X')
Y = theano.tensor.imatrix('Y')

# initialize weights and biases
W1_init = params_1.W1_saved
b1_init = params_1.b1_saved
W2_init = params_1.W2_saved
b2_init = params_1.b2_saved

W1 = theano.shared(W1_init, name = 'W1')
b1 = theano.shared(b1_init, name = 'b1')
W2 = theano.shared(W2_init, name = 'W2')
b2 = theano.shared(b2_init, name = 'b2')

dot_1 = theano.tensor.dot(X, W1) + b1
activ_1 = theano.tensor.nnet.sigmoid(dot_1)
dot_2 = theano.tensor.dot(activ_1, W2) + b2
activ_final = theano.tensor.nnet.softmax(dot_2)

pred_y = theano.tensor.argmax(activ_final)

# Function to get classes' probabilities for a given input
pred_proba = theano.function([X], activ_final, allow_input_downcast = True)

# Function to predict class for a given input
predict_val = theano.function([X], pred_y, allow_input_downcast = True)

# Function to check accuracy on a dataset (proportion of correct)
def accuracy_for_dataset(inputs, labels):
    return sum([predict_val(inputs[i,:].reshape(1,inputs.shape[1])) == labels[i] for i in range(inputs.shape[0])])/float(inputs.shape[0])

######

numf = len(params_1.freqs)
numc = 0

num_all = len(all_CSPs)
for i in range(num_all):
    if(all_CSPs[i].shape[0] > 0):
        numc = numc + 1

numch = 24 #TOFIX

# preprocessing high and lowpass filters

a_pre_high = np.zeros((1,filtorder + 1))
b_pre_high = np.zeros((1,filtorder + 1))
a_pre_low = np.zeros((1,filtorder + 1))
b_pre_low = np.zeros((1,filtorder + 1))

Zlast_pre_high = np.zeros((1,numch,filtorder))
Zlast_pre_low = np.zeros((1,numch,filtorder))

[b_pre_high[0], a_pre_high[0]] = spsig.butter(filtorder, float(fmin_pre)/(srate/2), 'high')
[b_pre_low[0], a_pre_low[0]] = spsig.butter(filtorder, float(fmax_pre)/(srate/2), 'low')

# create bandpass filters

a_high = np.zeros((numf,filtorder + 1))
b_high = np.zeros((numf,filtorder + 1))
a_low = np.zeros((numf,filtorder + 1))
b_low = np.zeros((numf,filtorder + 1))

numch_without_emp = np.sum(without_emp_mask)

Zlast_high = np.zeros((numf,numch_without_emp,filtorder))
Zlast_low = np.zeros((numf,numch_without_emp,filtorder))

for fr in range(numf):

    fmin = freq[fr][0]
    fmax = freq[fr][1]

    [b_high[fr], a_high[fr]] = spsig.butter(filtorder, float(fmin)/(srate/2), 'high')
    [b_low[fr], a_low[fr]] = spsig.butter(filtorder, float(fmax)/(srate/2), 'low')

# create moving average filter
Zlast_ma = np.zeros((numc,win-1))
a_ma = 1
b_ma = np.ones((1,win))

###

exptime = 900
dt_rate = 0.1

# allocating buffers
received_data_buf = np.zeros((numch, exptime*srate*1.2))
states_predicted_buf = np.zeros((1, exptime*srate*1.2))
pos = 0
pos_pred = 0

# first resolve an EEG stream on the lab network
print("looking for an EEG stream...")
streams = resolve_stream('type', 'Data')

# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])

globalstart = time.time()

while (time.time() - globalstart < exptime):

    startwhile = time.time()

    chunk, timestamp = inlet.pull_chunk()
    np_ar_chunk = np.asarray(chunk)
    chunk_size = np_ar_chunk.shape[0]

    if chunk_size > 0:

        data_chunk_test = np_ar_chunk.T

        received_data_buf[:,pos:(pos+chunk_size)] = data_chunk_test
        pos = pos + chunk_size + 1

        [data_chunk_test,Zlast_pre_high[0,:,:]] = spsig.lfilter(b_pre_high[0], a_pre_high[0], data_chunk_test, 1, Zlast_pre_high[0,:,:])
        [data_chunk_test,Zlast_pre_low[0,:,:]] = spsig.lfilter(b_pre_low[0], a_pre_low[0], data_chunk_test, 1, Zlast_pre_low[0,:,:])

        data_chunk_test = data_chunk_test[without_emp_mask,:]
        #chan_names_test_used = chan_names_test[:,without_emp_mask]
        data_chunk_test = np.dot(M_eog,data_chunk_test)

        ###filt_apply_CSPs(data, sr, freq_range, all_CSPs, how_to_filt, win, order=5, normalize=False):

        N_csp_per_freq = len(all_CSPs)/len(freq)
        all_CSPs_copy = list(all_CSPs)
        transformed_data_chunk = np.zeros((0, data_chunk_test.shape[1]))

        for fr_ind in range(len(freq)):

            [data_chunk_test,Zlast_high[fr_ind,:,:]] = spsig.lfilter(b_high[fr_ind], a_high[fr_ind], data_chunk_test, 1, Zlast_high[fr_ind,:,:])
            [data_chunk_test,Zlast_low[fr_ind,:,:]] = spsig.lfilter(b_low[fr_ind], a_low[fr_ind], data_chunk_test, 1, Zlast_low[fr_ind,:,:])

            for csp_ind in range(N_csp_per_freq):
                transformed_data_chunk = np.vstack((transformed_data_chunk, np.dot(all_CSPs_copy.pop(0), data_chunk_test)))

        final_data_chunk = transformed_data_chunk[1:,:]**2
        a_ma = 1
        b_ma = np.ones(win)/float(win)

        [final_data_chunk,Zlast_ma] = spsig.lfilter(b_ma, a_ma, transformed_data_chunk, 1, Zlast_ma)

        inputs = final_data_chunk

        chunk_res = np.array([predict_val(inputs[:,i].reshape(1,inputs.shape[0])) for i in range(inputs.shape[1])])

        res_chunk_size = chunk_res.shape[0]
        states_predicted_buf[:,pos_pred:(pos_pred+res_chunk_size)] = chunk_res
        pos_pred = pos_pred+res_chunk_size

        print(chunk_res[-1])

    dif = dt_rate - time.time() + startwhile
    if(dif > 0):
        time.sleep(dif)


from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from tkinter import messagebox
import mysql.connector
import cv2
import os
import csv
from tkinter import filedialog

mydata = []

class Attendence:
    def __init__(self, root):
        self.root = root
        self.root.geometry("1530x790+0+0")
        self.root.title("Face_Recognition_System")

    # variables:
        self.var_atten_id = StringVar()
        self.var_atten_roll = StringVar()
        self.var_atten_name = StringVar()
        self.var_atten_dep = StringVar()
        self.var_atten_time = StringVar()
        self.var_atten_date = StringVar()
        self.var_atten_attendence = StringVar()

    # left image
        img_left = Image.open(r"Camera Roll\student1.jpeg")
        img_left = img_left.resize((800, 200), Image.LANCZOS)
        self.photoimg_left = ImageTk.PhotoImage(img_left)

        f_lbl = Label(self.root, image=self.photoimg_left)
        f_lbl.place(x=0, y=0, width=750, height=200)

    # right image
        img_right = Image.open(r"Camera Roll\student2.jpeg")
        img_right = img_right.resize((800, 200), Image.LANCZOS)
        self.photoimg_right = ImageTk.PhotoImage(img_right)

        f_lbl = Label(self.root, image=self.photoimg_right)
        f_lbl.place(x=750, y=0, width=750, height=200)

    # bg_image
        img3 = Image.open(
            r"Camera Roll\background.jpeg")
        img3 = img3.resize((1530, 710), Image.LANCZOS)
        self.photoimg3 = ImageTk.PhotoImage(img3)

        bg_img = Label(self.root, image=self.photoimg3)
        bg_img.place(x=0, y=150, width=1530, height=700)

        # title
        title_lbl = Label(bg_img, text="ATTENDENCE MANAGEMENT SYSTEM", font=(
            "times new roman", 35, "bold"), bg="white", fg="darkblue")
        title_lbl.place(x=0, y=0, width=1530, height=40)

        main_frame = Frame(bg_img, bd=2, bg="white")
        main_frame.place(x=10, y=55, width=1500, height=600)

    # left label frame
        left_frame = LabelFrame(main_frame, bd=2, bg="white", relief=RIDGE,
                                text="Student Attendence Details", font=("times new roman", 12, "bold"))
        left_frame.place(x=0, y=0, width=740, height=550)

    # left frame background image
        img_left = Image.open(
            r"Camera Roll\leftframe.jpeg")
        img_left = img_left.resize((200, 210), Image.LANCZOS)
        self.photoimg_left = ImageTk.PhotoImage(img_left)

        f_lbl = Label(left_frame, image=self.photoimg_left)
        f_lbl.place(x=0, y=0, width=735, height=100)

        left_inside_frame = Frame(left_frame, bd=2, relief=RIDGE, bg="white")
        left_inside_frame.place(x=5, y=105, width=730, height=300)

        # label and entry
    # Attendence id
        AttendenceID = Label(left_inside_frame, text="Attendence ID:", font=(
            "times new roman", 12, "bold"), bg="white")
        AttendenceID.grid(row=0, column=0, padx=10, pady=10, sticky=W)

        AttendenceID_entry = ttk.Entry(left_inside_frame, textvariable=self.var_atten_id, width=17, font=(
            "times new roman", 12, "bold"))
        AttendenceID_entry.grid(row=0, column=1, padx=10, pady=10, sticky=W)

    # roll:no
        Roll_no = Label(left_inside_frame, text="Roll:", font=(
            "times new roman", 12, "bold"), bg="white")
        Roll_no.grid(row=0, column=3, padx=10, pady=10, sticky=W)

        Roll_no_entry = ttk.Entry(left_inside_frame, textvariable=self.var_atten_roll, width=17, font=(
            "times new roman", 12, "bold"))
        Roll_no_entry.grid(row=0, column=4, padx=10, pady=10, sticky=W)

    # Name
        Name = Label(left_inside_frame, text="Name:", font=(
            "times new roman", 12, "bold"), bg="white")
        Name.grid(row=1, column=0, padx=10, pady=10, sticky=W)

        Name_entry = ttk.Entry(left_inside_frame, textvariable=self.var_atten_name, width=17, font=(
            "times new roman", 12, "bold"))
        Name_entry.grid(row=1, column=1, padx=10, pady=10, sticky=W)

    # Department
        Department = Label(left_inside_frame, text="Department:", font=(
            "times new roman", 12, "bold"), bg="white")
        Department.grid(row=1, column=3, padx=10, pady=10, sticky=W)

        Department_entry = ttk.Entry(left_inside_frame, textvariable=self.var_atten_dep, width=17, font=(
            "times new roman", 12, "bold"))
        Department_entry.grid(row=1, column=4, padx=10, pady=10, sticky=W)

    # Time
        Time = Label(left_inside_frame, text="Time:", font=(
            "times new roman", 12, "bold"), bg="white")
        Time.grid(row=2, column=0, padx=10, pady=10, sticky=W)

        Time_entry = ttk.Entry(left_inside_frame, textvariable=self.var_atten_time, width=17, font=(
            "times new roman", 12, "bold"))
        Time_entry.grid(row=2, column=1, padx=10, pady=10, sticky=W)

    # Date
        Date = Label(left_inside_frame, text="Date:", font=(
            "times new roman", 12, "bold"), bg="white")
        Date.grid(row=2, column=3, padx=10, pady=10, sticky=W)

        Date_entry = ttk.Entry(left_inside_frame, textvariable=self.var_atten_date, width=17, font=(
            "times new roman", 12, "bold"))
        Date_entry.grid(row=2, column=4, padx=10, pady=10, sticky=W)

    # Attendence status
        Attendence_status = Label(left_inside_frame, text="Attendence status:", font=(
            "times new roman", 12, "bold"), bg="white")
        Attendence_status.grid(row=3, column=1, padx=10, sticky=W)

        Attendence_status_combo = ttk.Combobox(left_inside_frame, textvariable=self.var_atten_attendence, font=(
            "times new roman", 12, "bold"), width=17, state="readonly")
        Attendence_status_combo["values"] = (
            "Status", "Present", "Absent")
        Attendence_status_combo.current(0)
        Attendence_status_combo.grid(
            row=3, column=2, padx=2, pady=10, sticky=W)

    # Buttons
        btn_frame = LabelFrame(left_inside_frame, bd=2,
                               bg="white", relief=RIDGE)
        btn_frame.place(x=2, y=253, width=720, height=38)

    # import csv button
        import_btn = Button(btn_frame, text="import csv", command=self.importCSV, width=27, font=(
            "times new roman", 12, "bold"), bg="black", fg="white")
        import_btn.grid(row=0, column=1)

    # export csv button
        export_btn = Button(btn_frame, text="export csv", command=self.exportCSV, width=27, font=(
            "times new roman", 12, "bold"), bg="black", fg="white")
        export_btn.grid(row=0, column=2)

    # Update button
        """Update_btn = Button(btn_frame, text="Update", width=19, font=(
            "times new roman", 12, "bold"), bg="black", fg="white")
        Update_btn.grid(row=0, column=3)"""

    # Reset button
        Reset_btn = Button(btn_frame, text="Reset", command=self.reset_data, width=27, font=(
            "times new roman", 12, "bold"), bg="black", fg="white")
        Reset_btn.grid(row=0, column=4)

    # right label frame
        right_frame = LabelFrame(main_frame, bd=2, bg="white", relief=RIDGE,
                                 text="Attendence Details", font=("times new roman", 12, "bold"))
        right_frame.place(x=750, y=0, width=740, height=550)

        right_inside_frame = Frame(right_frame, bd=2, relief=RIDGE, bg="white")
        right_inside_frame.place(x=3, y=5, width=730, height=500)

    ####### scroll bar table#########

        scrollbar_x = ttk.Scrollbar(right_inside_frame, orient=HORIZONTAL)
        scrollbar_y = ttk.Scrollbar(right_inside_frame, orient=VERTICAL)

        self.AttendenceReportTable = ttk.Treeview(right_inside_frame, column=(
            "id", "roll", "name", "department", "time", "date", "attendence status"), xscrollcommand=scrollbar_x.set, yscrollcommand=scrollbar_y.set)

        scrollbar_x.pack(side=BOTTOM, fill=X)
        scrollbar_y.pack(side=RIGHT, fill=Y)

        scrollbar_x.config(command=self.AttendenceReportTable.xview)
        scrollbar_y.config(command=self.AttendenceReportTable.yview)

        self.AttendenceReportTable.heading("id", text="Attendence ID")
        self.AttendenceReportTable.heading("roll", text="Roll")
        self.AttendenceReportTable.heading("name", text="Name")
        self.AttendenceReportTable.heading("department", text="Department")
        self.AttendenceReportTable.heading("time", text="Time")
        self.AttendenceReportTable.heading("date", text="Date")
        self.AttendenceReportTable.heading(
            "attendence status", text="Attendence Status")

        # to remove space from table at start
        self.AttendenceReportTable["show"] = "headings"

        self.AttendenceReportTable.column("id", width=100)
        self.AttendenceReportTable.column("roll", width=100)
        self.AttendenceReportTable.column("name", width=100)
        self.AttendenceReportTable.column("department", width=100)
        self.AttendenceReportTable.column("time", width=100)
        self.AttendenceReportTable.column("date", width=100)
        self.AttendenceReportTable.column("attendence status", width=120)

        self.AttendenceReportTable.pack(fill=BOTH, expand=1)

        self.AttendenceReportTable.bind("<ButtonRelease>", self.get_cursor)

    ######## fetch data#######
    def fetchData(self, rows):
        self.AttendenceReportTable.delete(
            *self.AttendenceReportTable.get_children())
        for i in rows:
            self.AttendenceReportTable.insert("", END, values=i)

    def importCSV(self):
        global mydata
        mydata.clear()
        fln = filedialog.askopenfilename(initialdir=os.getcwd(), title="Open CSV", filetypes=(
            ("CSV File", "*.csv"), ("All File", "*.*")), parent=self.root)
        with open(fln) as myfile:
            csvread = csv.reader(myfile, delimiter=",")
            for i in csvread:
                mydata.append(i)
            self.fetchData(mydata)

    ### export csv###
    def exportCSV(self):
        try:
            if len(mydata) < 1:
                messagebox.showerror(
                    "No Data", "No Data To Show", parent=self.root)
                return False
            fln = filedialog.asksaveasfilename(initialdir=os.getcwd(), title="Open CSV", filetypes=(
                ("CSV File", "*.csv"), ("All File", "*.*")), parent=self.root)
            with open(fln, mode="w", newline="") as myfile:
                exp_write = csv.writer(myfile, delimiter=",")
                for i in mydata:
                    # a function which appends the data form file.
                    exp_write.writerow(i)
                messagebox.showinfo("Data Success", "Data Successfuly Exported To:" +
                                    os.path.basename(fln) + "", parent=self.root)

        except Exception as es:
            messagebox.showerror(
                "Error", f"Due to:{str(es)}", parent=self.root)

    # function to diplay detials in student details frame :
    # there no value for event just we need to pass some argumnet so we are passing
    def get_cursor(self, event=""):
        cursor_row = self.AttendenceReportTable.focus()
        content = self.AttendenceReportTable.item(cursor_row)
        rows = content['values']
        self.var_atten_id.set(rows[0])
        self.var_atten_roll.set(rows[1])
        self.var_atten_name.set(rows[2])
        self.var_atten_dep.set(rows[3])
        self.var_atten_time.set(rows[4])
        self.var_atten_date.set(rows[5])
        self.var_atten_attendence.set(rows[6])

    # Reset function
    def reset_data(self):
        self.var_atten_id.set("")
        self.var_atten_roll.set("")
        self.var_atten_name.set("")
        self.var_atten_dep.set("")
        self.var_atten_time.set("")
        self.var_atten_date.set("")
        self.var_atten_attendence.set("")

# REMOVE UPDATE FUNCTION######## BUTTON
if __name__ == "__main__":
    root = Tk()
    obj = Attendence(root)
    root.mainloop()


from linked_list import *

def addLists(a, b):
    c = LinkedList()
    current_a = a.head
    current_b = b.head
    carry = 0
    while current_a != None and current_b != None:
        val = current_a.value + current_b.value
        c.append((val + carry) % 10)
        carry = int((val + carry) / 10)
        current_a = current_a.next
        current_b = current_b.next
    if current_a == None and current_b == None and carry != 0:
        c.append(carry)
    elif current_a != None:
        while current_a != None:
            c.append(current_a.value + carry)
            carry = 0
            current_a = current_a.next
    elif current_b != None:
        while current_b != None:
            c.append(current_b.value + carry)
            carry = 0
            current_b = current_b.next
    return c

a = LinkedList()
b = LinkedList()
a.append(9)
a.append(9)
a.append(9)
b.append(1)
b.append(1)
b.append(1)
b.append(1)
addLists(a, b).print_linked_list()


from datetime import datetime

class Greeter:

    def greet(self, name):
        hour = int(datetime.strftime(datetime.now(), "%H"))
        name = name.strip().capitalize()
        if 6 <= hour < 12:
            return "Доброе утро {}".format(name)
        elif 18 <= hour < 22:
            return "Добрый вечер {}".format(name)
        elif 22 <= hour < 24:
            return "Доброй ночи {}".format(name)
        elif 0 <= hour < 6:
            return "Доброй ночи {}".format(name)
        return "Привет {}".format(name)

if __name__ == "__main__":
    g = Greeter()
    g.greet("A")


from PyQt5 import QtCore
from PyQt5.QtGui import *
from PyQt5.QtWidgets import QMainWindow, QWidget, QApplication, QTextEdit, QPushButton, QLabel, QFileDialog
from PyQt5.QtCore import Qt
import sys
import socket

"""HEADER = 64
PORT = 12345
FORMAT = 'utf-8'
DISCONNECT_MESSAGE = "!DISCONNECT"
SERVER = "10.69.56.75"
ADDR = (SERVER, PORT)

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)"""

class Valve(QWidget):
    """ Valve class
    """
    count = 0
    label_width = 122
    label_height = 153
    valve_center_radius = 17
    valve_wing_length = 37

    def __init__(self, parent=None, x_offset=0, y_offset=0, margin=5):
        """__init__
            Main constructor
        :return:None
        """
        super().__init__(parent)
        label_x = (self.label_width + margin) * x_offset + margin
        label_y = (self.label_height + margin) * y_offset + margin

        '''if y_offset ==1:
            label_x += self.label_width
        else:
            label_x += + self.label_width/2'''

        #if y_offset == 1:
        #    label_x += self.label_width + self.label_width / 2 + 2 + margin

        self.setGeometry(label_x, label_y, self.label_width, self.label_height)
        self.setStyleSheet("background-color: white;"
                           "font-size: 17px;")
        self.__create_body__()
        self.__create_footer__()
        self.id = Valve.count + 1
        self.script = ""
        self.script_path = "path"
        Valve.count += 1

        self.status = False

        self.id_label = QLabel(self)
        self.id_label.setText(str(self.id))
        self.id_label.adjustSize()
        self.id_label.move(7, 7)
        self.id_label.setStyleSheet("color: gray")

    def __create_body__(self):
        pass

    def paintEvent(self, event):
        """__paint_event__
            Function for drawing the design for each valve

            :return: None

        """
        qp = QPainter()
        qp.begin(self)
        qp.setRenderHint(QPainter.Antialiasing)
        qp.setPen(Qt.NoPen)
        qp.setBrush(QColor(255, 255, 255))
        qp.drawRect(0, 0, self.label_width, self.label_height - 31)

        valveForm = QPainterPath()
        valveForm.moveTo(self.width() / 10, (self.height() - 31) / 2 - 1)
        valveForm.lineTo(self.width() / 4, (self.height() - 31) / 2 - 1)
        valveForm.lineTo(self.width() / 4, (self.height() - 31) / 2 - 20)
        valveForm.lineTo(self.width() / 2, (self.height() - 31) / 2 - 3)
        valveForm.lineTo(self.width() / 2, (self.height() - 31) / 2 + 3)
        valveForm.lineTo(self.width() / 4, (self.height() - 31) / 2 + 20)
        valveForm.lineTo(self.width() / 4, (self.height() - 31) / 2 + 1)
        valveForm.lineTo(self.width() / 10, (self.height() - 31) / 2 + 1)
        qp.fillPath(valveForm, QBrush(QColor("black")))

        valveForm.moveTo(self.width() * 9 / 10, (self.height() - 31) / 2 - 1)
        valveForm.lineTo(self.width() * 3 / 4, (self.height() - 31) / 2 - 1)
        valveForm.lineTo(self.width() * 3 / 4, (self.height() - 31) / 2 - 20)
        valveForm.lineTo(self.width() / 2, (self.height() - 31) / 2 - 3)
        valveForm.lineTo(self.width() / 2, (self.height() - 31) / 2 + 3)
        valveForm.lineTo(self.width() * 3 / 4, (self.height() - 31) / 2 + 20)
        valveForm.lineTo(self.width() * 3 / 4, (self.height() - 31) / 2 + 1)
        valveForm.lineTo(self.width() * 9 / 10, (self.height() - 31) / 2 + 1)
        qp.fillPath(valveForm, QBrush(QColor("black")))

        if self.status == True:
            valveForm.clear()
            valveForm.moveTo(self.width() / 4 + 4, (self.height() - 31) / 2 - 13)
            valveForm.lineTo(self.width() / 2 - 5, (self.height() - 31) / 2)
            valveForm.lineTo(self.width() / 4 + 4, (self.height() - 31) / 2 + 13)
            valveForm.moveTo(self.width() * 3 / 4 - 4, (self.height() - 31) / 2 - 12)
            valveForm.lineTo(self.width() / 2 + 5, (self.height() - 31) / 2)
            valveForm.lineTo(self.width() * 3 / 4 - 4, (self.height() - 31) / 2 + 12)
            qp.fillPath(valveForm, QBrush(QColor("white")))

        qp.end()

    def __create_footer__(self, parent=None):
        """__create_footer__
            Function for creating footer with load and print buttons

            :return:None

        """
        self.load_button = QPushButton(self)
        self.print_button = QPushButton(self)
        self.load_button.setText("Load")
        self.print_button.setText("Print")

        self.load_button.setGeometry(-1, self.height() - 30, self.width() / 2 + 1, 31)
        self.print_button.setGeometry(self.width() / 2, self.height() - 30, self.width() / 2 + 1, 31)
        self.load_button.setStyleSheet("border-top: 5px solid lightgray; "
                                       "font-size: 17px;"
                                       "border-right: 2px solid lightgray; color: black;")
        self.print_button.setStyleSheet("border-top: 5px solid lightgray; "
                                        "font-size: 17px;"
                                        "border-left: 2px solid lightgray; color: gray;background-color:lightgray")

        self.load_button.clicked.connect(lambda: self.__open_file_name_dialog__())
        self.print_button.clicked.connect(lambda: self.__print_content__())

    def __print_content__(self):
        """__print_content__
            Updates the valve nr. and the path
        :return:None
        """
        if len(self.script) > 0:
            self.parent().textArea.setText(self.script)
            self.parent().label1.setText("Valve {}".format(str(self.id)))
            self.parent().label2.setText(self.script_path)

    def __open_file_name_dialog__(self):
        """__open_file_name_dialog
            Opens the dialog for selecting a file
            :return :None
        """
        options = QFileDialog.Options()
        options |= QFileDialog.DontUseNativeDialog
        self.file_name, _ = QFileDialog.getOpenFileName(self, "Open file", "",
                                                        "All files (*);;Python Files (*.py)", options=options)
        if self.file_name:
            self.f = open(self.file_name, "r")
            self.script = self.f.read()
            self.script_path = str(self.file_name)
            self.load_button.setStyleSheet("border-top: 5px solid lightgray;"
                                           "border-right: 2px solid lightgray; color: black; background-color: LimeGreen")
            self.print_button.setStyleSheet("border-top: 5px solid lightgray;"
                                            "border-left: 2px solid lightgray; color: black; background-color: white")

            event = "Valve {} load event : \n \n".format(self.id)
            event = event.encode(self.parent().FORMAT)
            msg_length = len(event)
            send_length = str(msg_length).encode(self.parent().FORMAT)
            send_length += b' ' * (64 - len(send_length))

            self.parent().client.send(send_length)
            self.parent().client.send(event)

            script = self.script.encode(self.parent().FORMAT)
            msg_length = len(script)
            send_length = str(msg_length).encode(self.parent().FORMAT)
            send_length += b' ' * (64 - len(send_length))

            self.parent().client.send(send_length)
            self.parent().client.send(script)


from django.conf.urls import url
from . import views

app_name = 'project'

urlpatterns = [
    url(r'^$', views.index, name='index'),

    # project urls
    url(r'^project-list/$', views.project_list, name='project-list'),
    url(r'^(?P<project_id>[0-9]+)/project-detail/$', views.project_view, name='project-detail'),
    url(r'^project-new/', views.project_create, name='project-create'),
    url(r'^project-update/$', views.project_update, name='project-update'),
    url(r'^(?P<project_id>[0-9]+)/project-delete/$', views.project_delete, name='project-delete'),

    # employee urls
    url(r'^employee-list/$', views.employee_list, name='employee-list'),
    url(r'^(?P<employee_id>[0-9]+)/employee-detail/$', views.employee_view, name='employee-detail'),
    url(r'^employee-new/', views.employee_create, name='employee-create'),
    url(r'^(?P<employee_id>[0-9]+)/employee-update/$', views.employee_update, name='employee-update'),
    url(r'^(?P<employee_id>[0-9]+)/employee-delete/$', views.employee_delete, name='employee-delete'),

    # income urls
    url(r'^income-list/$', views.income_list, name='income-list'),
    url(r'^income-new/$', views.income_create, name='income-create'),
    url(r'^income-update/$', views.income_update, name='income-update'),
    url(r'^(?P<income_id>[0-9]+)/income-delete/$', views.income_delete, name='income-delete'),
    url(r'^(?P<income_id>[0-9]+)/income-detail/$', views.income_view, name='income-detail'),

    # transaction urls
    url(r'^transaction-list/$', views.transaction_list, name='transaction-list'),
    url(r'^transaction-new/$', views.transaction_create, name='transaction-create'),
    # url(r'^income-update/$', views.income_update, name='income-update'),
    # url(r'^(?P<income_id>[0-9]+)/income-delete/$', views.income_delete, name='income-delete'),
    # url(r'^(?P<income_id>[0-9]+)/income-detail/$', views.income_view, name='income-detail'),

    # tasks urls
    url(r'^task-list/$', views.task_list, name='task-list'),
    url(r'^task-new/$', views.task_create, name='task-create'),
    url(r'^task-update/$', views.task_update, name='task-update'),
    url(r'^(?P<task_id>[0-9]+)/task-delete/$', views.task_delete, name='task-delete'),

    # salary urls
    url(r'^salary-list/$', views.salary_list, name='salary-list'),
    url(r'^salary-new/$', views.salary_create, name='salary-create'),
    url(r'^salary-update/$', views.salary_update, name='salary-update'),
    url(r'^(?P<salary_id>[0-9]+)/salary-delete/$', views.salary_delete, name='salary-delete'),

    # debt urls
    url(r'^debt-list/$', views.debt_list, name='debt-list'),
    url(r'^debt-new/$', views.debt_create, name='debt-create'),
    url(r'^debt-update/$', views.debt_update, name='debt-update'),
    url(r'^(?P<debt_id>[0-9]+)/debt-delete/$', views.debt_delete, name='debt-delete'),

    # CompanyEquipment
    url(r'^companyEquipment-list/$', views.company_equipment_list, name='companyEquipment-list'),
    url(r'^companyEquipment-new/$', views.company_equipment_create, name='companyEquipment-create'),
    url(r'^companyEquipment-update/$', views.company_equipment_update, name='companyEquipment-update'),
    url(r'^(?P<companyEquipment_id>[0-9]+)/companyEquipment-delete/$', views.company_equipment_delete,
        name='companyEquipment-delete'),

    # employee work days urls
    url(r'^workDay-list/$', views.workDay_list, name='workDay-list'),
    url(r'^workDay-new/$', views.workDay_create, name='workDay-create'),
    url(r'^workDay-update/$', views.workDay_update, name='workDay-update'),
    url(r'^(?P<workDay_id>[0-9]+)/workDay-delete/$', views.workDay_delete, name='workDay-delete'),

    # financial urls
    url(r'^financial/$', views.financial, name='financial'),

    # 505 urls
    url(r'^505/$', views.pageNotExist, name='pageNotExist'),
]


from django import forms
from django.forms import CharField, Textarea, IntegerField, ChoiceField, CheckboxSelectMultiple, ImageField, FileField, MultipleChoiceField
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class HospitalBookForm(UserCreationForm):
    name = CharField(label="Hospital Name",
                     required=True,
                     strip=True)
    hospiAddress = CharField(label="Full Address ",
                             required=True,
                             strip=True)
    pincode = forms.IntegerField(label="Pincode", required=True,)
    phICU = forms.IntegerField(label="ICU Contact Number", required=True,)
    phSuperDoc = forms.IntegerField(
        label="Supervising Doctor's Contact No", required=True,)
    phHospi = forms.IntegerField(label="Hospital's contact No", required=True,)
    piAmb = forms.IntegerField(label="Ambulance Contact  No", required=True,)
    CATEGORYTYPE = [('L1', 'L1'),
                    ('L2', 'L2'),
                    ('L3', 'L3'),
                    ('Monitoring', 'Monitoring')]
    category1 = forms.MultipleChoiceField(
        choices=CATEGORYTYPE, widget=forms.CheckboxSelectMultiple, label="Category of Covid Patients allowed")
    YesNoforApprove = [('Yes', 'Yes'),
                       ('No', 'No'), ]
    YesorNO = forms.ChoiceField(
        choices=YesNoforApprove, widget=forms.RadioSelect, label="Approved to treat Covid-19 Patients")
    CHOICESTYPE = [('Government', 'Government'),
                   ('Private', 'Private')]
    BedNo = forms.IntegerField(
        label="Total Number of Beds For Covid Patients", required=True,)

    CHOICESHOSTYPE = [('Hospital', 'Hospital'),
                      ('Medical College / Institute', 'Medical College / Institute'),
                      ('Community Health Centre', 'Community Health Centre'),
                      ('Corona Center', 'Corona Center'),
                      ('Primary Health Centre', 'Primary Health Centre'),
                      ('Others', 'Others'), ]
    CostandAvailiable = forms.ImageField(label="Cost and Avaliability")
    noOfPeopleMonitored = forms.IntegerField(
        label="No. of People To be Monitored", required=True,)
    HospitalDirectives = forms.ImageField(
        allow_empty_file=False, label="Hospital Directives")
    govOrPri = forms.ChoiceField(
        choices=CHOICESTYPE, widget=forms.RadioSelect, label="Are You")
    typeOfHos = forms.ChoiceField(
        choices=CHOICESHOSTYPE, widget=forms.RadioSelect, label="Health Care Provider Type")
    regNo = forms.IntegerField(label="Registration Number", required=True,)

    def __init__(self, *args, **kwargs):
        super(HospitalBookForm, self).__init__(*args, **kwargs)

        for fieldname in ['username', 'password1', 'password2']:
            self.fields[fieldname].help_text = None

    class Meta:
        model = User
        fields = ['username', 'name', 'email', 'password1', 'password2', 'govOrPri', 'typeOfHos', 'regNo', 'CostandAvailiable', 'HospitalDirectives',
                  'hospiAddress', 'pincode', 'phICU', 'phSuperDoc', 'phHospi', 'piAmb', 'category1', 'YesorNO', 'BedNo', 'noOfPeopleMonitored']


import numpy as np
import matplotlib.pyplot as plt
from scipy.integrate import odeint
from lmfit import minimize, Parameters, Parameter, report_fit
from decimal import Decimal

N = 1000

# Defining system of equations
def f(y,t,params):
  S = y[0]
  I = y[1]

  try:
    k0 = params['k0'].value
  except keyError:
    k0 = params

  f1 = (.0109 * N) - (.007 * S) - (k0 * S * I)/N
  f2 = (k0 * S * I)/N - (.007 + .0819)*I - (.9181 * S)
  return [f1,f2]

# Solving ODE with initial condition
def g(t, x0, param):
  x = odeint(f,x0,t, args=(params,))
  return x

# Computing residual between actual and fitted
def residual(params, t, data):
  init = params['S0'].value, params['I0'].value
  model = g(t,init,params)
  I_model = model[:,1]
  return (I_model - data).ravel()

def estimate(S0,I0,N,k0):
# initial conditions
  y0 = [S0,I0]

# insert data
  time = np.linspace(0, 9, 10)
  I_measured = np.array([1,9,15,29,50,85,120,140,152,160])

# insert parameters
  params = Parameters()
  params.add('S0', value=S0, vary=False)
  params.add('I0',value=I0, vary=False)
  params.add('k0',value=.4, min=.00001, max=10.)

# fit model
  result = minimize(residual, params, args=(time, I_measured), method='leastsq')  # leastsq nelder
# check results of the fit
  data_fitted = g(time, y0, result.params)
  estimated_infected = (timepoint, y0, result.params)
  print("There are " + estimated_infected[1,1] + " estimated infected")
  print("The infection rate is approximately " + k0 + " infections per infected")
  print("Statistical analysis of the model wll also be provided")
  # display fitted statistics
  return report_fit(result)

ninput = input("Input initial total population: ")
try:
  N = int(ninput)
  print("Accepted")
except ValueError:
  print("Please try again with a numeral input")

s0input = input("Input initial infected population: ")
try:
  I0 = int(s0input)
except ValueError:
  print("Please try again with a numeral input")

S0 = N - I0

k0input = input("What is your first guess for infection rate? (Usually a decimal from 0 to 10) ")
try:
  k0 = Decimal(k0input)
  print("Accepted")
except ValueError:
  print("Please try again with a numeral input")

tinput = input("Input a timepoint at which you would like to predict the total infected population: ")
try:
  timepoint = int(tinput)
  print("Accepted. Calculating total infected population and adjusted infection rate... ")
except ValueError:
  print("Please try again with a numeral input")


#!/usr/bin/env python
########################################################################
# File :    dirac-wms-get-queue-cpu-time.py
# Author :  Federico Stagni
########################################################################
"""
Report CPU length of queue, in seconds
This script is used by the dirac-pilot script to set the CPUTime left, which is a limit for the matching
"""
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
__RCSID__ = "$Id$"

import DIRAC
from DIRAC.Core.Utilities.DIRACScript import DIRACScript as Script

@Script()
def main():
  Script.registerSwitch("C:", "CPUNormalizationFactor=", "CPUNormalizationFactor, in case it is known")
  Script.parseCommandLine(ignoreErrors=True)

  CPUNormalizationFactor = 0.0
  for unprocSw in Script.getUnprocessedSwitches():
    if unprocSw[0] in ("C", "CPUNormalizationFactor"):
      CPUNormalizationFactor = float(unprocSw[1])

  from DIRAC.WorkloadManagementSystem.Client.CPUNormalization import getCPUTime
  cpuTime = getCPUTime(CPUNormalizationFactor)
  # I hate this kind of output... PhC
  print("CPU time left determined as", cpuTime)
  DIRAC.exit(0)

if __name__ == "__main__":
  main()


#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
from collections import namedtuple

from shapely.geometry import Point, Polygon

from src.utils.catastro_logger import CadastroLogger

'''Logger'''
logger = CadastroLogger(__name__).logger

class GeoPolygon:
    """
    A GeoPolygon is a series of lon,lat points in a json. This class uses shapely.geometry
    to convert points into Point objects and these into a Polygon class.
    """

    def __init__(self, file):
        self.polygon = None
        try:
            with open(file, "r") as f:
                content = f.read()

                data = json.loads(content, object_hook=lambda d: namedtuple('X', d.keys())(*d.values()))
                points = data.geo_polygon.location.points
                points_list = []
                for point in points:
                    points_list.append((point.lon, point.lat))
                self.polygon = Polygon(points_list)
        except Exception as e:
            logger.error("{} is not formatted properly. Please take a look at the examples.".format(file))

    def is_point_in_polygon(self, lon, lat):
        """
        Check if a point (lot, lat) is inside this Polygon
        :param lon: longitude
        :param lat: latitude
        :return: True if point is inside polygon. False otherwise
        """
        p = Point(lon, lat)
        return self.polygon.contains(p)

    def get_bounding_box(self):
        """
        Gets the bounding box of a polygon
        :return: A Box object from shapely.geometry containing inside the Polygon
        """
        if self.polygon is not None:
            return self.polygon.bounds
        else:
            return None


"""
    Contains all information for a Clash team
"""
from src.league.clash.Player import Player

class Team:
    def __init__(self, TeamDto):
        self.id = TeamDto['id']
        self.tournamentId = TeamDto['tournamentId']
        self.name = TeamDto['name']
        self.iconId = TeamDto['iconId']
        self.tier = TeamDto['tier']
        self.captain = TeamDto['captain']
        self.abbreviation = TeamDto['abbreviation']
        self.players = self.initPlayers(TeamDto['players'])

    def __str__(self):
        return (f'Team name: {self.name}\nAbbreviation: {self.abbreviation}\nCaptain: {self.captain}\nTeam ID: {self.id}\n'
                f'Tier: {self.tier}\n')

    def initPlayers(self, playersList):
        players = []
        for obj in playersList:
            players.append(Player(obj, self.id))
        return players


import PySimpleGUI as psg
import string
# from output_g_code import conversion_van

psg.theme("default1")

layout = [
    [
        psg.Text("Enter Text: ", size=(10, 1)),
        psg.InputText(do_not_clear=False)
    ],
    [
        psg.Text("Select Options: "),
        psg.Radio("H = 2", "group1"),
        psg.Radio("H = 3", "group1"),
        psg.Radio("H = 4", "group1"),
        psg.Radio("H = 5", "group1"),
        psg.Radio("H = 6", "group1"),
    ],
    [
        psg.Button("Convert"),
        psg.Button("Exit")
    ]
]

window = psg.Window("Form", layout)

a_var = []
e_var = []
h_var = ""
low_string = list(string.ascii_lowercase)

while True:
    event, values = window.read()
    if event == "Exit" or event == psg.WIN_CLOSED:
        break

    elif event == "Convert":
        in_string = values[0]
        for index in in_string:
            a_var.append(index)
        for i in in_string:
            e_var.append(low_string.index(i) + 1)

        var_list = [values[1], values[2], values[3],
                    values[4], values[5],
                    ]
        for index in var_list:
            # print(index) debugging
            if index is True:
                h_var = str(var_list.index(index) + 2)

        # output finished code
        for index in values[0]:
            print("G65 P8200 H{0}. E{1} F100. D100. R3. Z-2.5 ({2})"
                  .format(h_var, e_var, a_var))

        # debugging
        print(a_var)
        print(e_var)
        print("H" + h_var + ".")
        print(values)

window.close()


import sys

from awx.main.utils.pglock import advisory_lock
from awx.main.models import Instance, InstanceGroup

from django.core.management.base import BaseCommand, CommandError
from django.db import transaction

class InstanceNotFound(Exception):
    def __init__(self, message, changed, *args, **kwargs):
        self.message = message
        self.changed = changed
        super(InstanceNotFound, self).__init__(*args, **kwargs)

class RegisterQueue:
    def __init__(
        self, queuename, instance_percent, inst_min, hostname_list, is_container_group=None, pod_spec_override=None, max_forks=None, max_concurrent_jobs=None
    ):
        self.instance_not_found_err = None
        self.queuename = queuename
        self.instance_percent = instance_percent
        self.instance_min = inst_min
        self.hostname_list = hostname_list
        self.is_container_group = is_container_group
        self.pod_spec_override = pod_spec_override
        self.max_forks = max_forks
        self.max_concurrent_jobs = max_concurrent_jobs

    def get_create_update_instance_group(self):
        created = False
        changed = False
        (ig, created) = InstanceGroup.objects.get_or_create(name=self.queuename)
        if ig.policy_instance_percentage != self.instance_percent:
            ig.policy_instance_percentage = self.instance_percent
            changed = True
        if ig.policy_instance_minimum != self.instance_min:
            ig.policy_instance_minimum = self.instance_min
            changed = True

        if self.is_container_group and (ig.is_container_group != self.is_container_group):
            ig.is_container_group = self.is_container_group
            changed = True

        if self.pod_spec_override and (ig.pod_spec_override != self.pod_spec_override):
            ig.pod_spec_override = self.pod_spec_override
            changed = True

        if self.max_forks and (ig.max_forks != self.max_forks):
            ig.max_forks = self.max_forks
            changed = True

        if self.max_concurrent_jobs and (ig.max_concurrent_jobs != self.max_concurrent_jobs):
            ig.max_concurrent_jobs = self.max_concurrent_jobs
            changed = True

        if changed:
            ig.save()

        return (ig, created, changed)

    def add_instances_to_group(self, ig):
        changed = False

        instance_list_unique = {x for x in (x.strip() for x in self.hostname_list) if x}
        instances = []
        for inst_name in instance_list_unique:
            instance = Instance.objects.filter(hostname=inst_name).exclude(node_type='hop')
            if instance.exists():
                instances.append(instance[0])
            else:
                raise InstanceNotFound("Instance does not exist or cannot run jobs: {}".format(inst_name), changed)

        ig.instances.add(*instances)

        instance_list_before = ig.policy_instance_list
        instance_list_after = instance_list_unique
        new_instances = set(instance_list_after) - set(instance_list_before)
        if new_instances:
            changed = True
            ig.policy_instance_list = ig.policy_instance_list + list(new_instances)
            ig.save()

        return (instances, changed)

    def register(self):
        with advisory_lock('cluster_policy_lock'):
            with transaction.atomic():
                changed2 = False
                (ig, created, changed1) = self.get_create_update_instance_group()
                if created:
                    print("Creating instance group {}".format(ig.name))
                elif not created:
                    print("Instance Group already registered {}".format(ig.name))

                try:
                    (instances, changed2) = self.add_instances_to_group(ig)
                    for i in instances:
                        print("Added instance {} to {}".format(i.hostname, ig.name))
                except InstanceNotFound as e:
                    self.instance_not_found_err = e

        if changed1 or changed2:
            print('(changed: True)')

class Command(BaseCommand):
    def add_arguments(self, parser):
        parser.add_argument('--queuename', dest='queuename', type=str, help='Queue to create/update')
        parser.add_argument(
            '--hostnames', dest='hostnames', type=str, help='Comma-Delimited Hosts to add to the Queue (will not remove already assigned instances)'
        )
        parser.add_argument(
            '--instance_percent', dest='instance_percent', type=int, default=0, help='The percentage of active instances that will be assigned to this group'
        ),
        parser.add_argument(
            '--instance_minimum',
            dest='instance_minimum',
            type=int,
            default=0,
            help='The minimum number of instance that will be retained for this group from available instances',
        )

    def handle(self, **options):
        queuename = options.get('queuename')
        if not queuename:
            raise CommandError("Specify `--queuename` to use this command.")
        inst_per = options.get('instance_percent')
        instance_min = options.get('instance_minimum')
        hostname_list = []
        if options.get('hostnames'):
            hostname_list = options.get('hostnames').split(",")

        rq = RegisterQueue(queuename, inst_per, instance_min, hostname_list)
        rq.register()
        if rq.instance_not_found_err:
            print(rq.instance_not_found_err.message)
            sys.exit(1)


"""
Code used for the ACROBAT 2023 Grand Challenge
"""

import pathlib
import os
import shutil
from time import time
import argparse
import numpy as np
import pandas as pd
import pyvips

from valis import registration, warp_tools, preprocessing, slide_io
from valis.micro_rigid_registrar import MicroRigidRegistrar

ANON_COL = "anon_id"
PT_COL = "point_id"
SRC_COL = "wsi_source"
TARGET_COL = "wsi_target"
LANDMARK_COL = "landmarks_csv"
DST_DIR_COL = "output_dir_name"

SRC_MMP = "mpp_source"
SRC_X_COL = "x_source"
SRC_Y_COL = "y_source"

TARGET_X_COL = "x_target"
TARGET_Y_COL = "y_target"
TARGET_MMP = "mpp_target"

TARGET_IMG_NAME = "registered_source_image.ome.tiff"
TARGET_LANDMARK_NAME = "registered_landmarks.csv"

if __name__ == "__main__":
    import argparse
    parser = argparse.ArgumentParser(description='Register images for the 2023 ACROBAT Grand Challenge')
    parser.add_argument('-PATH_TABLE_CSV', type=str, help='csv containing image pairs and landmarks')
    parser.add_argument('-PATH_IMAGES_DIR', type=str, help='csv containing image pairs and landmarks')
    parser.add_argument('-PATH_ANNOT_DIR', type=str, help='csv containing image pairs and landmarks')
    parser.add_argument('-PATH_OUTPUT_DIR', type=str, help='csv containing image pairs and landmarks')
    parser.add_argument('-row_idx', type=int, help='name/row of sample')
    parser.add_argument('-micro_reg_fraction', type=str, help='Size of images used for 2nd registation')
    parser.add_argument('-use_masks', type=str, help='Whether or not to use masks for registration')

    args = vars(parser.parse_args())

    micro_reg_fraction = args["micro_reg_fraction"]
    row_idx = args["row_idx"]
    img_src_dir = args["PATH_IMAGES_DIR"]
    landmark_src_dir = args["PATH_ANNOT_DIR"]
    parent_dst_dir = args["PATH_OUTPUT_DIR"]
    input_table = args["PATH_TABLE_CSV"]
    use_masks = eval(args["use_masks"])

    micro_reg_fraction = eval(micro_reg_fraction)
    input_df = pd.read_csv(input_table)
    sample_row = input_df.iloc[row_idx]

    src_img_f = sample_row[SRC_COL]
    target_img_f = sample_row[TARGET_COL]
    landmarks_f = os.path.join(landmark_src_dir, sample_row[LANDMARK_COL])
    sample_id = str(sample_row[DST_DIR_COL])
    dst_dir = os.path.join(parent_dst_dir, sample_id)

    print(sample_id)
    # Do initial registration, setting the reference image to be the H&E image
    img_list = [os.path.join(img_src_dir, d) for d in [target_img_f, src_img_f]]

    start = time()
    registrar = registration.Valis("./",  os.path.split(dst_dir)[0],
                                   crop="reference",
                                   reference_img_f=target_img_f,
                                   align_to_reference=True,
                                   img_list=img_list,
                                   create_masks=use_masks,
                                   max_processed_image_dim_px=500,
                                   max_non_rigid_registration_dim_px=2000,
                                   micro_rigid_registrar_cls=MicroRigidRegistrar,
                                   name=sample_id)

    rigid_registrar, non_rigid_registrar, error_df = registrar.register(brightfield_processing_cls=preprocessing.StainFlattener,
                                                                        brightfield_processing_kwargs={"adaptive_eq":True})

    # Determine how large of an image to use for micro registration
    img_dims = np.array([slide_obj.slide_dimensions_wh[0] for slide_obj in registrar.slide_dict.values()])
    min_max_size = np.min([np.max(d) for d in img_dims])
    img_areas = [np.multiply(*d) for d in img_dims]
    max_img_w, max_img_h = tuple(img_dims[np.argmax(img_areas)])

    if micro_reg_fraction == 1.0:
        # Full size image
        micro_reg_size = None
    if isinstance(micro_reg_fraction, float):
        micro_reg_size = np.floor(min_max_size*micro_reg_fraction).astype(int)
    else:
        micro_reg_size = micro_reg_fraction
        micro_reg_fraction = micro_reg_fraction/min_max_size

    micro_reg, micro_error = registrar.register_micro(max_non_rigid_registration_dim_px=micro_reg_size,
                                                      reference_img_f=target_img_f,
                                                      align_to_reference=True,
                                                      brightfield_processing_cls=preprocessing.StainFlattener)
    stop = time()
    elapsed = stop - start
    elapsed_min = np.round(elapsed/60, 6)

    # Create benchmarking results
    pathlib.Path(dst_dir).mkdir(exist_ok=True, parents=True)

    non_rigid_error = np.nanmean(micro_error["non_rigid_D"].values)
    rigid_error = np.nanmean(micro_error["rigid_D"].values)
    apply_non_rigid = non_rigid_error < rigid_error
    if not apply_non_rigid:
        print(f"Non-rigid registration didn't improve alignments for {registrar.name}")

    # Read in points
    pt_df = pd.read_csv(landmarks_f)
    src_mpp = pt_df[SRC_MMP].values[0]
    src_xy_um = pt_df[[SRC_X_COL, SRC_Y_COL]].values
    src_xy_px = src_xy_um/src_mpp

    # Warp points
    src_slide = registrar.get_slide(src_img_f)
    ref_slide = registrar.get_slide(target_img_f)
    warped_xy_px = src_slide.warp_xy_from_to(src_xy_px, ref_slide, non_rigid=apply_non_rigid)

    # Clip any points that fell outside of image
    ref_slide_shape_wh = ref_slide.slide_dimensions_wh[0]
    warped_xy_px[:, 0] = np.clip(warped_xy_px[:, 0], 0, ref_slide_shape_wh[0])
    warped_xy_px[:, 1] = np.clip(warped_xy_px[:, 1], 0, ref_slide_shape_wh[1])

    dst_mpp = pt_df[TARGET_MMP].values[0]
    warped_xy_um = warped_xy_px*dst_mpp

    registered_df = pd.DataFrame({ANON_COL: pt_df[ANON_COL].values,
                                  PT_COL: pt_df[PT_COL].values,
                                  TARGET_X_COL: warped_xy_um[:, 0],
                                  TARGET_Y_COL: warped_xy_um[:, 1]})

    pt_f_out = os.path.join(dst_dir, TARGET_LANDMARK_NAME)
    registered_df.to_csv(pt_f_out, index=False)

    # Save registered source image
    s = 1/8
    source_slide = registrar.get_slide(src_img_f)
    warped_slide = source_slide.warp_slide(level=0, non_rigid=apply_non_rigid)
    warped_thumb = warp_tools.rescale_img(warped_slide, s)
    thumb_xyzct = slide_io.get_shape_xyzct((warped_thumb.width, warped_thumb.height), warped_thumb.bands)
    bf_dtype = slide_io.vips2bf_dtype(warped_thumb.format)
    thumb_px_phys_size = (dst_mpp/s, dst_mpp/s, 'µm')

    ome_xml_obj = slide_io.update_xml_for_new_img(source_slide.reader.metadata.original_xml,
                                                  new_xyzct=thumb_xyzct,
                                                  bf_dtype=bf_dtype,
                                                  is_rgb=source_slide.reader.metadata.is_rgb,
                                                  series=source_slide.reader.series,
                                                  pixel_physical_size_xyu=thumb_px_phys_size,
                                                  channel_names=source_slide.reader.metadata.channel_names
                                                  )

    ome_xml_obj.creator = f"pyvips version {pyvips.__version__}"
    ome_xml_str = ome_xml_obj.to_xml()

    dst_f = os.path.join(dst_dir, TARGET_IMG_NAME)
    slide_io.save_ome_tiff(warped_thumb, dst_f, ome_xml_str)

    # Delete output not needed by acrobat
    for f in os.listdir(dst_dir):
        if not f in [TARGET_LANDMARK_NAME, TARGET_IMG_NAME]:
            full_f = os.path.join(dst_dir, f)
            if os.path.isdir(full_f):
                # remove directories
                shutil.rmtree(full_f)
            else:
                # remove files
                os.remove(full_f)

    registration.kill_jvm()


from pathlib import Path
from clip.clip import load
from CLIP import CLIP, build_transform
from clip_tokenizer import SimpleTokenizer
import PIL
from PIL import Image
import torch
from torchvision import transforms
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pickle
import types
from dawnet.data.image import show_images

def get_attention_maps(model, visual=True):
    if visual:
        component = model.visual.transformer
    else:   # for text
        component = model.transformer

    attention_layers = []
    for name, module in component.named_modules():
        if hasattr(module, 'attention_masks_out'):
            attention_layers.append(module.attention_masks_out)

    return attention_layers

intermediate = {}
def debug_hook(module, input, output):
    if isinstance(output, PIL.Image.Image):
        return output
    name = str(type(module))
    idx = len(intermediate)
    if idx == 3:
        import pdb; pdb.set_trace()
        print(input[0].sum())
    if isinstance(output, tuple):
        to_log = tuple([each.cpu().data.numpy() for each in output])
    else:
        to_log = output.cpu().data.numpy()
    log = {
        'name': name,
        'output': to_log
    }
    intermediate[idx] = log
    return output

# torch.nn.modules.module.register_module_forward_hook(debug_hook)

if __name__ == '__main__':

    MODEL_PATH = 'clip.pth'
    VOCAB_PATH = 'bpe_simple_vocab_16e6.txt.gz'

    # model = CLIP(attention_probs_dropout_prob=0, hidden_dropout_prob=0)
    # model.load_state_dict(state_dict = torch.load(MODEL_PATH))
    model, transform = load('ViT-B/32', jit=False)

    tokenizer = SimpleTokenizer(
            bpe_path=VOCAB_PATH,
            context_length=model.context_length)
    # transform = build_transform(model.input_resolution.item())
    view_transform = transforms.Compose([
        transforms.Resize(224, interpolation=Image.BICUBIC),
        transforms.CenterCrop(224),
        lambda image: image.convert('RGB')])
    is_fp16 = False

    # device = "cuda" if torch.cuda.is_available() else "cpu"
    device = 'cpu'
    if is_fp16:
        model.to(device=device).eval().half()
    else:
        model.to(device=device).eval().float()

    model.eval()
    # model.register_module_forward_hook(debug_hook)
    with torch.no_grad():
        query = ["a horse", "a human", "an apple", "a tiger", "a cat", "a human and a tiger"]
        # query = ["a photo of a tinca tinca", "a photo of a wombat", "a photo of a restaurant"]
        text = tokenizer.encode(query).to(device)
        text_features = model.encode_text(text)  # N_queries x 512

        # image_path = "/home/john/datasets/imagenet/object_localization/val/n01440764/ILSVRC2012_val_00002138.JPEG"
        image_path = 'images/tiger1.jpg'
        image_name = Path(image_path).stem
        image_vis = np.asarray(view_transform(Image.open(image_path)))
        image = transform(Image.open(image_path)).unsqueeze(0).to(device)
        image_features = model.encode_image(image) # 1 x 512

        visual_attention = get_attention_maps(model, visual=True) #[<n_heads, t, t>]

        for layer_n, each_attention_layer in enumerate(visual_attention):
            layer_images = []
            for idx in range(each_attention_layer.size(0)):
                vis = each_attention_layer[idx, 0, 1:].reshape(7,7).detach().numpy()
                vis -= vis.min()
                vis /= vis.max()
                vis = cv2.resize(vis, (224, 224))[...,np.newaxis]
                result = (vis * image_vis).astype(np.uint8)
                layer_images.append(result)

            output_file = Path(f'logs/{image_name}/layer_{layer_n:02d}.png')
            output_file.parent.mkdir(parents=True, exist_ok=True)
            show_images(layer_images, max_columns=4, show=False, output=str(output_file))

        logits_per_image, logits_per_text = model(image, text)
        probs = logits_per_image.softmax(dim=-1).cpu().numpy()

    print(query)
    print("Label probs:", probs)


def ler(nome_arq):
    arquivo = open(nome_arq, 'r', encoding = 'utf-8')
    conteudo_arq = arquivo.read()
    arquivo.close()

    return conteudo_arq

texto = ler('Ubirajara.txt')

def concordanciador(alvo, texto):
    texto = texto.replace('\n', ' ')
    texto = texto.replace('\t', ' ')

    ocorrencias = list()
    encontrado_aqui = texto.find(alvo, 0)
    while encontrado_aqui > 0:
        pos_inicial = encontrado_aqui - (40 - len(alvo) // 2)
        ocorrencias.append(texto[pos_inicial : pos_inicial + 80])

        encontrado_aqui = texto.find(alvo, encontrado_aqui + 1)

    return ocorrencias

resultados = concordanciador('serpente', texto)
for i in resultados:
    print(i)


def run():
    print("Where should I look?")
    #ask the user which room to look in
    room = str(input())
    if room == "in the bedroom":
        print("Where in the bedroom shall i look?")
        #ask user where in the bedroom to look
        bedroom2 = str(input())
        if bedroom2 == "under the bed":
            print("Found some shoes but no battery")
        else:
            print("Found some mess but no battery")

    elif room == "in the bathroom":
        print("Where in the bathroom shall i look?")
        #ask the user where in the bathroom to look
        bathroom2 = str(input())
        if bathroom2 == "in the bathtub":
            print("Found a rubber duck but no battery")
        else:
            print("Found a wet surface but no battery")

    elif room == "in the lab":
        print("Where in the lab should I look?")
        #ask the user where in the lab to look
        lab2 = str(input())
        if lab2 == "on the table":
            print("Yes! I found my battery")
        else:
            print("Found some tools but no battery")

    else:
        print("I do not know where that is but I will keep looking")

if __name__ == "__main__":
    run()


from bs4 import BeautifulSoup
from urllib.request import urlparse
from urllib.request import urlopen
from requests import get
import re
from random import choice

url = "https://proesi.com.br/"

internal_urls = []
external_urls = []

def get_soup(url):
    html = get(url)
    soup = BeautifulSoup(html.text, "lxml")
    return soup

def busca_links(soup):
    for elemento in soup.find_all("a",{"href": re.compile(
            r"((http|ftp|https)://)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:/~+#-]*[\w@?^=%&/~+#-])?")}):
        if "href" in elemento.attrs:
            if "https://proesi.com.br" in elemento.attrs["href"]:
                if elemento.attrs["href"] not in internal_urls:
                    internal_urls.append(elemento.attrs["href"])

            if "https://proesi.com.br" not in elemento.attrs["href"]:
                if elemento.attrs["href"] not in external_urls:
                    external_urls.append(elemento.attrs["href"])
            print(elemento.attrs["href"])

def links_internos(start_link):
    while len(internal_urls) < 1000:
        internal_urls.append(start_link)
        domain = choice(internal_urls)
        busca_links(get_soup(domain))
        print(len(internal_urls))
    with open("Domains.txt", "w") as domains:
        for i in internal_urls:
            domains.write(i)
            domains.write("\n")

links_internos(url)

# for element in soup.find_all("div", {"class":"infobox"}):

        # print("{} : {}".format(element.find("h2",{"class" : "product-name"}).text,
        #                      element.find("span", {"class": "boletoBox priceAvista"}).find(
                                 # "span",{"class":"price"}).text))


from flask import Flask, jsonify, abort, request, make_response, url_for
import time
import sys
sys.path.append("Service")
import twitterService
import collectRadius
from flask_httpauth import HTTPBasicAuth
import uuid
import threading

app = Flask(__name__, static_url_path = "")

# Error Handling
@app.errorhandler(400)
def bad_request(error):
    return make_response(jsonify( { 'error': 'Bad request' } ), 400)

@app.errorhandler(404)
def not_found(error):
    return make_response(jsonify( { 'error': 'Not found' } ), 404)

# API
'''
### Name: startCollectTweet
### API: /stream/startCollectTweet
### Description:
'''
@app.route('/stream/startCollectTweet', methods = ['POST'])
def startCollectTweet():
    if not request.json or not 'keyWords' in request.json or not 'databaseName' in request.json or not 'ConsumerKey' in request.json or not 'ConsumerSecret' in request.json or not 'AccessToken' in request.json or not 'TokenSecret' in request.json:
        abort(400)
    databaseName = request.json['databaseName']
    key_words = request.json['keyWords']
    consumer_key = request.json['ConsumerKey']
    consumer_secret = request.json['ConsumerSecret']
    access_token = request.json['AccessToken']
    access_token_secret = request.json['TokenSecret']

    return_info = twitterService.startStreamTweet(databaseName,key_words,consumer_key,consumer_secret,access_token,access_token_secret)
    return jsonify( return_info ), 200

'''
### Name: stopCollectTweet
### API: /stream/stopCollectTweet
### Description:
'''
@app.route('/stream/stopCollectTweet', methods = ['POST'])
def stopCollectTweet():
    if not request.json or not 'stream_id' in request.json:
        abort(400)
    stream_id = request.json['stream_id']
    return_info = twitterService.stopStreamTweet(stream_id)
    return jsonify(return_info), 200

'''
### Name: queryStreamList
### API: '/stream/queryStreamList'
### Description: ''
'''
@app.route('/stream/queryStreamList', methods = ['GET'])
def queryStreamList():
    return_info = twitterService.queryStreamList()
    return jsonify(return_info), 200

'''''''''''''''''''''''''''''''''''''''''''''

'''''''''''''''''''''''''''''''''''''''''''''

'''
### Name: startCollectByRadius
### API: '/search/startCollectByRadius'
### Description: ''
'''
australia = '-29.1425,133.1389,2081km'
melbourne = '-37.7867,144.9082,100km'
sydney = '-33.8813,151.2128,100km'
brisbane = '-27.5394,153.1024,100km'
adelaide = '-34.9328,138.6444,100km'
perth = '-32.0379,115.8808,100km'

collecting_thread_information = []
collecting_thread_list = []
@app.route('/search/startCollectByRadius', methods = ['POST'])
def startCollectByRadius():
    if not request.json:
        abort(400)
    provinces = ""
    geocodes = []
    query = ""
    since = ""
    until = ""
    db_name = None
    if(request.json['db_name'] !=None):
        db_name = request.json['db_name']

    if(request.json['provinces'] !=None):
        provinces = request.json['provinces']

    if(request.json['geocodes'] !=None):
        geocodes = request.json['geocodes']

    if(request.json['since'] !=None):
        since = request.json['since']

    if(request.json['until']!=None):
        until = request.json['until']

    if(request.json['query'] !=None):
        query = request.json['query']

    #thread = threading.Thread(args=(query, provinces, geocodes, since, until))
    thread_id = str(uuid.uuid1())
    thread = collectRadius.StoppableThreadForCollectTweet(args=(query, provinces, geocodes, since, until,db_name,thread_id))
    thread_entity = {
        "thread_id":thread_id,
        "thread":thread,
        "information":{
            "provinces":provinces,
            "geocodes":geocodes,
            "since":since,
            "until":until,
            "query":query
        }
    }
    collecting_thread_list.append(thread_entity)

    thread_information = {
        "thread_id":thread_id,
        "information":{
            "provinces":provinces,
            "geocodes":geocodes,
            "since":since,
            "until":until,
            "query":query
        }
    }
    collecting_thread_information.append(thread_information)

    try:
        thread.start()
    except Exception as e:
        return jsonify( {"errorMessage":e, 'isSuccess': False } ), 200

    return jsonify( {"threadEntity":thread_information, 'isSuccess': True } ), 200

'''
### Name: stopCollectByRadius
### API: '/search/stopCollectByRadius'
### Description: ''
'''
@app.route('/search/stopCollectByRadius', methods = ['POST'])
def stopCollectByRadius():
    thread_ids = request.json['ids']
    for thread_id in thread_ids:
        thread_entity = None
        thread_information = None
        for i in range(len(collecting_thread_list)):
            if(collecting_thread_list[i]["thread_id"] == thread_id):
                thread_entity = collecting_thread_list.pop(i)
                thread_information = collecting_thread_information.pop(i)
                break

        if(thread_entity == None):
            return jsonify( {"errorMessage":"Thread not found", 'isSuccess': False } ), 200
        else:
            thread = thread_entity["thread"]
            try:
                thread.stop()
                thread.join()
                return jsonify( {"threadEntity":thread_information, 'isSuccess': False } ), 200
            except Exception as e:
                print(str(e))
                return jsonify( {"threadEntity":thread_information, 'isSuccess': True } ), 200
'''
### Name: collectByRadiusList
### API: '/search/queryCollectingThreadList'
### Description: ''
'''
@app.route('/search/queryCollectingThreadList', methods = ['GET'])
def collectByRadiusList():
    return jsonify( {"threadList":collecting_thread_information, 'isSuccess': True } ), 200

if __name__ == '__main__':
    app.run(port=5001,debug=True,threaded=True,host='0.0.0.0')


import random
import BinaryStrings
import Permutations
import SignedPermutations

def main():
    # Create a list of RankObjects.
    RankObjects = []
    RankObjects.append(BinaryStrings.BinaryStrings())
    RankObjects.append(Permutations.Permutations())
    RankObjects.append(SignedPermutations.SignedPermutations())

    # Do some random tests on each RankObject.
    n = 4
    for RankObject in RankObjects:

        # Print out the name of this RankObject.
        print("Testing of " + RankObject.name)
        print("")

        # Get a random object and rank it.
        obj = RankObject.random(n)
        index = RankObject.rank(obj)
        print("Random object: " + RankObject.string(obj))
        print("Rank: " + str(index))
        print("")

        # Get a random index and unrank it.
        index = random.randrange(0, RankObject.total(n))
        obj = RankObject.unrank(index, n)
        print("Random index: " + str(index))
        print("Object: " + RankObject.string(obj))
        print("")

        # List out all objects for this value of n.
        L = RankObject.listing(n)
        print(L)

        # Test objects for larger values of n.
        RankObject.test_all()
        print("")
        print("")

if __name__ == "__main__":
    main()