from rpython.jit.backend.llsupport import jitframe
from rpython.jit.backend.llsupport.memcpy import memcpy_fn, memset_fn
from rpython.jit.backend.llsupport.symbolic import WORD
from rpython.jit.backend.llsupport.codemap import CodemapBuilder
from rpython.jit.metainterp.history import (INT, REF, FLOAT, JitCellToken,
    ConstInt, BoxInt, AbstractFailDescr)
from rpython.jit.metainterp.resoperation import ResOperation, rop
from rpython.rlib import rgc
from rpython.rlib.debug import (debug_start, debug_stop, have_debug_prints_for,
                                debug_print)
from rpython.rlib.rarithmetic import r_uint
from rpython.rlib.objectmodel import specialize, compute_unique_id
from rpython.rtyper.annlowlevel import cast_instance_to_gcref, llhelper
from rpython.rtyper.lltypesystem import rffi, lltype

DEBUG_COUNTER = lltype.Struct('DEBUG_COUNTER',
    # 'b'ridge, 'l'abel or # 'e'ntry point
    ('i', lltype.Signed),      # first field, at offset 0
    ('type', lltype.Char),
    ('number', lltype.Signed)
)

class GuardToken(object):
    def __init__(self, cpu, gcmap, faildescr, failargs, fail_locs, exc,
                 frame_depth, is_guard_not_invalidated, is_guard_not_forced):
        assert isinstance(faildescr, AbstractFailDescr)
        self.cpu = cpu
        self.faildescr = faildescr
        self.failargs = failargs
        self.fail_locs = fail_locs
        self.gcmap = self.compute_gcmap(gcmap, failargs,
                                        fail_locs, frame_depth)
        self.exc = exc
        self.is_guard_not_invalidated = is_guard_not_invalidated
        self.is_guard_not_forced = is_guard_not_forced

    def compute_gcmap(self, gcmap, failargs, fail_locs, frame_depth):
        # note that regalloc has a very similar compute, but
        # one that does iteration over all bindings, so slightly different,
        # eh
        input_i = 0
        for i in range(len(failargs)):
            arg = failargs[i]
            if arg is None:
                continue
            loc = fail_locs[input_i]
            input_i += 1
            if arg.type == REF:
                loc = fail_locs[i]
                if loc.is_core_reg():
                    val = self.cpu.all_reg_indexes[loc.value]
                else:
                    val = loc.get_position() + self.cpu.JITFRAME_FIXED_SIZE
                gcmap[val // WORD // 8] |= r_uint(1) << (val % (WORD * 8))
        return gcmap

class BaseAssembler(object):
    """ Base class for Assembler generator in real backends
    """

    def __init__(self, cpu, translate_support_code=False):
        self.cpu = cpu
        self.memcpy_addr = 0
        self.memset_addr = 0
        self.rtyper = cpu.rtyper
        self._debug = False

    def setup_once(self):
        # the address of the function called by 'new'
        gc_ll_descr = self.cpu.gc_ll_descr
        gc_ll_descr.initialize()
        if hasattr(gc_ll_descr, 'minimal_size_in_nursery'):
            self.gc_minimal_size_in_nursery = gc_ll_descr.minimal_size_in_nursery
        else:
            self.gc_minimal_size_in_nursery = 0
        if hasattr(gc_ll_descr, 'gcheaderbuilder'):
            self.gc_size_of_header = gc_ll_descr.gcheaderbuilder.size_gc_header
        else:
            self.gc_size_of_header = WORD # for tests
        self.memcpy_addr = self.cpu.cast_ptr_to_int(memcpy_fn)
        self.memset_addr = self.cpu.cast_ptr_to_int(memset_fn)
        self._build_failure_recovery(False, withfloats=False)
        self._build_failure_recovery(True, withfloats=False)
        self._build_wb_slowpath(False)
        self._build_wb_slowpath(True)
        self._build_wb_slowpath(False, for_frame=True)
        # only one of those
        self.build_frame_realloc_slowpath()
        if self.cpu.supports_floats:
            self._build_failure_recovery(False, withfloats=True)
            self._build_failure_recovery(True, withfloats=True)
            self._build_wb_slowpath(False, withfloats=True)
            self._build_wb_slowpath(True, withfloats=True)
        self._build_propagate_exception_path()
        if gc_ll_descr.get_malloc_slowpath_addr is not None:
            # generate few slowpaths for various cases
            self.malloc_slowpath = self._build_malloc_slowpath(kind='fixed')
            self.malloc_slowpath_varsize = self._build_malloc_slowpath(
                kind='var')
        if hasattr(gc_ll_descr, 'malloc_str'):
            self.malloc_slowpath_str = self._build_malloc_slowpath(kind='str')
        else:
            self.malloc_slowpath_str = None
        if hasattr(gc_ll_descr, 'malloc_unicode'):
            self.malloc_slowpath_unicode = self._build_malloc_slowpath(
                kind='unicode')
        else:
            self.malloc_slowpath_unicode = None
        self.cond_call_slowpath = [self._build_cond_call_slowpath(False, False),
                                   self._build_cond_call_slowpath(False, True),
                                   self._build_cond_call_slowpath(True, False),
                                   self._build_cond_call_slowpath(True, True)]

        self._build_stack_check_slowpath()
        self._build_release_gil(gc_ll_descr.gcrootmap)
        if not self._debug:
            # if self._debug is already set it means that someone called
            # set_debug by hand before initializing the assembler. Leave it
            # as it is
            self.set_debug(have_debug_prints_for('jit-backend-counts'))
        # when finishing, we only have one value at [0], the rest dies
        self.gcmap_for_finish = lltype.malloc(jitframe.GCMAP, 1,
                                              flavor='raw',
                                              track_allocation=False)
        self.gcmap_for_finish[0] = r_uint(1)

    def setup(self, looptoken):
        if self.cpu.HAS_CODEMAP:
            self.codemap_builder = CodemapBuilder()
        self._finish_gcmap = lltype.nullptr(jitframe.GCMAP)

    def set_debug(self, v):
        r = self._debug
        self._debug = v
        return r

    def rebuild_faillocs_from_descr(self, descr, inputargs):
        locs = []
        GPR_REGS = len(self.cpu.gen_regs)
        XMM_REGS = len(self.cpu.float_regs)
        input_i = 0
        if self.cpu.IS_64_BIT:
            coeff = 1
        else:
            coeff = 2
        for pos in descr.rd_locs:
            pos = rffi.cast(lltype.Signed, pos)
            if pos == 0xFFFF:
                continue
            elif pos < GPR_REGS:
                locs.append(self.cpu.gen_regs[pos])
            elif pos < GPR_REGS + XMM_REGS * coeff:
                pos = (pos - GPR_REGS) // coeff
                locs.append(self.cpu.float_regs[pos])
            else:
                i = pos - self.cpu.JITFRAME_FIXED_SIZE
                assert i >= 0
                tp = inputargs[input_i].type
                locs.append(self.new_stack_loc(i, tp))
            input_i += 1
        return locs

    def store_info_on_descr(self, startspos, guardtok):
        withfloats = False
        for box in guardtok.failargs:
            if box is not None and box.type == FLOAT:
                withfloats = True
                break
        exc = guardtok.exc
        target = self.failure_recovery_code[exc + 2 * withfloats]
        fail_descr = cast_instance_to_gcref(guardtok.faildescr)
        fail_descr = rffi.cast(lltype.Signed, fail_descr)
        base_ofs = self.cpu.get_baseofs_of_frame_field()
        positions = [rffi.cast(rffi.USHORT, 0)] * len(guardtok.fail_locs)
        for i, loc in enumerate(guardtok.fail_locs):
            if loc is None:
                position = 0xFFFF
            elif loc.is_stack():
                assert (loc.value & (WORD - 1)) == 0, \
                    "store_info_on_descr: misaligned"
                position = (loc.value - base_ofs) // WORD
                assert 0 < position < 0xFFFF, "store_info_on_descr: overflow!"
            else:
                assert loc is not self.cpu.frame_reg # for now
                if self.cpu.IS_64_BIT:
                    coeff = 1
                else:
                    coeff = 2
                if loc.is_float():
                    position = len(self.cpu.gen_regs) + loc.value * coeff
                else:
                    position = self.cpu.all_reg_indexes[loc.value]
            positions[i] = rffi.cast(rffi.USHORT, position)
        # write down the positions of locs
        guardtok.faildescr.rd_locs = positions
        return fail_descr, target

    def enter_portal_frame(self, op):
        if self.cpu.HAS_CODEMAP:
            self.codemap_builder.enter_portal_frame(op.getarg(0).getint(),
                                                    op.getarg(1).getint(),
                                                    self.mc.get_relative_pos())

    def leave_portal_frame(self, op):
        if self.cpu.HAS_CODEMAP:
            self.codemap_builder.leave_portal_frame(op.getarg(0).getint(),
                                                    self.mc.get_relative_pos())

    def call_assembler(self, op, guard_op, argloc, vloc, result_loc, tmploc):
        self._store_force_index(guard_op)
        descr = op.getdescr()
        assert isinstance(descr, JitCellToken)
        #
        # Write a call to the target assembler
        # we need to allocate the frame, keep in sync with runner's
        # execute_token
        jd = descr.outermost_jitdriver_sd
        self._call_assembler_emit_call(self.imm(descr._ll_function_addr),
                                        argloc, tmploc)

        if op.result is None:
            assert result_loc is None
            value = self.cpu.done_with_this_frame_descr_void
        else:
            kind = op.result.type
            if kind == INT:
                assert result_loc is tmploc
                value = self.cpu.done_with_this_frame_descr_int
            elif kind == REF:
                assert result_loc is tmploc
                value = self.cpu.done_with_this_frame_descr_ref
            elif kind == FLOAT:
                value = self.cpu.done_with_this_frame_descr_float
            else:
                raise AssertionError(kind)

        gcref = cast_instance_to_gcref(value)
        if gcref:
            rgc._make_sure_does_not_move(gcref)
        value = rffi.cast(lltype.Signed, gcref)
        je_location = self._call_assembler_check_descr(value, tmploc)
        #
        # Path A: use assembler_helper_adr
        assert jd is not None
        asm_helper_adr = self.cpu.cast_adr_to_int(jd.assembler_helper_adr)

        self._call_assembler_emit_helper_call(self.imm(asm_helper_adr),
                                                [tmploc, vloc], result_loc)

        jmp_location = self._call_assembler_patch_je(result_loc, je_location)

        # Path B: fast path.  Must load the return value

        #
        self._call_assembler_load_result(op, result_loc)
        #
        # Here we join Path A and Path B again
        self._call_assembler_patch_jmp(jmp_location)
        # XXX here should be emitted guard_not_forced, but due
        #     to incompatibilities in how it's done, we leave it for the
        #     caller to deal with

    @specialize.argtype(1)
    def _inject_debugging_code(self, looptoken, operations, tp, number):
        if self._debug:
            s = 0
            for op in operations:
                s += op.getopnum()

            newoperations = []
            self._append_debugging_code(newoperations, tp, number,
                                        None)
            for op in operations:
                newoperations.append(op)
                if op.getopnum() == rop.LABEL:
                    self._append_debugging_code(newoperations, 'l', number,
                                                op.getdescr())
            operations = newoperations
        return operations

    def _append_debugging_code(self, operations, tp, number, token):
        counter = self._register_counter(tp, number, token)
        c_adr = ConstInt(rffi.cast(lltype.Signed, counter))
        operations.append(
            ResOperation(rop.INCREMENT_DEBUG_COUNTER, [c_adr], None))

    def _register_counter(self, tp, number, token):
        # YYY very minor leak -- we need the counters to stay alive
        # forever, just because we want to report them at the end
        # of the process

        # XXX the numbers here are ALMOST unique, but not quite, use a counter
        #     or something
        struct = lltype.malloc(DEBUG_COUNTER, flavor='raw',
                               track_allocation=False)
        struct.i = 0
        struct.type = tp
        if tp == 'b' or tp == 'e':
            struct.number = number
        else:
            assert token
            struct.number = compute_unique_id(token)
        self.loop_run_counters.append(struct)
        return struct

    def finish_once(self):
        if self._debug:
            debug_start('jit-backend-counts')
            for i in range(len(self.loop_run_counters)):
                struct = self.loop_run_counters[i]
                if struct.type == 'l':
                    prefix = 'TargetToken(%d)' % struct.number
                else:
                    num = struct.number
                    if num == -1:
                        num = '-1'
                    else:
                        num = str(r_uint(num))
                    if struct.type == 'b':
                        prefix = 'bridge %s' % num
                    else:
                        prefix = 'entry %s' % num
                debug_print(prefix + ':' + str(struct.i))
            debug_stop('jit-backend-counts')

    @staticmethod
    @rgc.no_collect
    def _reacquire_gil_asmgcc(css, old_rpy_fastgil):
        # Before doing an external call, 'rpy_fastgil' is initialized to
        # be equal to css.  This function is called if we find out after
        # the call that it is no longer equal to css.  See description
        # in translator/c/src/thread_pthread.c.

        if old_rpy_fastgil == 0:
            # this case occurs if some other thread stole the GIL but
            # released it again.  What occurred here is that we changed
            # 'rpy_fastgil' from 0 to 1, thus successfully reaquiring the
            # GIL.
            pass

        elif old_rpy_fastgil == 1:
            # 'rpy_fastgil' was (and still is) locked by someone else.
            # We need to wait for the regular mutex.
            after = rffi.aroundstate.after
            if after:
                after()
        else:
            # stole the GIL from a different thread that is also
            # currently in an external call from the jit.  Attach
            # the 'old_rpy_fastgil' into the chained list.
            from rpython.memory.gctransform import asmgcroot
            oth = rffi.cast(asmgcroot.ASM_FRAMEDATA_HEAD_PTR, old_rpy_fastgil)
            next = asmgcroot.gcrootanchor.next
            oth.next = next
            oth.prev = asmgcroot.gcrootanchor
            asmgcroot.gcrootanchor.next = oth
            next.prev = oth

        # similar to trackgcroot.py:pypy_asm_stackwalk, second part:
        # detach the 'css' from the chained list
        from rpython.memory.gctransform import asmgcroot
        old = rffi.cast(asmgcroot.ASM_FRAMEDATA_HEAD_PTR, css)
        prev = old.prev
        next = old.next
        prev.next = next
        next.prev = prev

    @staticmethod
    @rgc.no_collect
    def _reacquire_gil_shadowstack():
        # Simplified version of _reacquire_gil_asmgcc(): in shadowstack mode,
        # 'rpy_fastgil' contains only zero or non-zero, and this is only
        # called when the old value stored in 'rpy_fastgil' was non-zero
        # (i.e. still locked, must wait with the regular mutex)
        after = rffi.aroundstate.after
        if after:
            after()

    _REACQGIL0_FUNC = lltype.Ptr(lltype.FuncType([], lltype.Void))
    _REACQGIL2_FUNC = lltype.Ptr(lltype.FuncType([rffi.CCHARP, lltype.Signed],
                                                 lltype.Void))

    def _build_release_gil(self, gcrootmap):
        if gcrootmap is None or gcrootmap.is_shadow_stack:
            reacqgil_func = llhelper(self._REACQGIL0_FUNC,
                                     self._reacquire_gil_shadowstack)
            self.reacqgil_addr = self.cpu.cast_ptr_to_int(reacqgil_func)
        else:
            reacqgil_func = llhelper(self._REACQGIL2_FUNC,
                                     self._reacquire_gil_asmgcc)
            self.reacqgil_addr = self.cpu.cast_ptr_to_int(reacqgil_func)

    def _is_asmgcc(self):
        gcrootmap = self.cpu.gc_ll_descr.gcrootmap
        return bool(gcrootmap) and not gcrootmap.is_shadow_stack

def debug_bridge(descr_number, rawstart, codeendpos):
    debug_start("jit-backend-addr")
    debug_print("bridge out of Guard 0x%x has address 0x%x to 0x%x" %
                (r_uint(descr_number), r_uint(rawstart),
                    r_uint(rawstart + codeendpos)))
    debug_stop("jit-backend-addr")


def upload(file_pattern, destination='Private', leaf_folders_as_items=False,
           reuse_existing=False):
    """
    Upload a pattern of files. This will recursively walk down every tree in
    the file pattern to create a hierarchy on the server. As of right now, this
    places the file into the currently logged in user's home directory.

    :param file_pattern: a glob type pattern for files
    :type file_pattern: string
    :param destination: (optional) name of the midas destination folder,
        defaults to Private
    :type destination: string
    :param leaf_folders_as_items: (optional) whether leaf folders should have
        all files uploaded as single items
    :type leaf_folders_as_items: bool
    :param reuse_existing: (optional) whether to accept an existing item of the
        same name in the same location, or create a new one instead
    :type reuse_existing: bool
    """
    session.token = verify_credentials()

    # Logic for finding the proper folder to place the files in.
    parent_folder_id = None
    user_folders = session.communicator.list_user_folders(session.token)
    if destination.startswith('/'):
        parent_folder_id = _find_resource_id_from_path(destination)
    else:
        for cur_folder in user_folders:
            if cur_folder['name'] == destination:
                parent_folder_id = cur_folder['folder_id']
    if parent_folder_id is None:
        print('Unable to locate specified destination. Defaulting to {0}.'
              .format(user_folders[0]['name']))
        parent_folder_id = user_folders[0]['folder_id']

    for current_file in glob.iglob(file_pattern):
        current_file = os.path.normpath(current_file)
        if os.path.isfile(current_file):
            print('Uploading item from {0}'.format(current_file))
            _upload_as_item(os.path.basename(current_file),
                            parent_folder_id,
                            current_file,
                            reuse_existing)
        else:
            _upload_folder_recursive(current_file,
                                     parent_folder_id,
                                     leaf_folders_as_items,
                                     reuse_existing)


# -*- coding: utf-8 -*-
'''
整合爬蟲程式跟分析關鍵字並輸入資料庫
只要改import的爬蟲py檔
再標誌好該網站對應的category(詳見category_dic)
就可以開始作業
'''
import time
import sqlite3 as sql
from db_tools.db_functions import mp_analyze,input_tempdic,input_db
from threading import Thread as thr
from threading import Semaphore as sm
import queue
import scrapy.ettoday_scrapy as ettoday

if __name__=='__main__':
    category_dic = {"政治":"政治","財經":"投資","論壇":"政治",
                    "國際":"政治","大陸":"政治","社會":"生活",
                    "地方":"生活","新奇":"生活","生活":"生活",
                    "寵物動物":"生活","影劇":"娛樂","體育":"運動",
                    "旅遊":"娛樂","消費":"娛樂","名家":"娛樂",
                    "ET來了":"閒聊","3C家電":"科技","健康":"生活",
                    "男女":"心情","公益":"生活","遊戲":"遊戲",
                    "電影":"娛樂","時尚":"娛樂","網搜":"閒聊",
                    "電商":"投資","親子":"心情","房產雲":"投資",
                    "ET車雲":"娛樂","軍武":"政治","保險":"投資",
                    "法律":"學術","直銷雲":"投資","探索":"生活",
                    "運勢":"閒聊"}

    db = sql.connect('test.db')
    cursor = db.cursor()
    que_scrapy = queue.Queue()
    que_input = queue.Queue()
    sem_scrapy = sm(10)
    temp_dic = {}
    counter = 0

    thr(target=ettoday.start,args=(1000000,que_scrapy,sem_scrapy)).start()
    print('scrapy already.')
    time.sleep(5)
    thr(target=mp_analyze,args=(que_scrapy,que_input)).start()
    print('analyze already.')
    time.sleep(5)
    print('go')

    while 1:
        if que_input.empty():
            time.sleep(10)
            if que_input.empty():
                print('\nmain input waiting..')
                continue
        type,url,result = que_input.get()
        print(' '*79,end='\r')
        print(type,url,end='\r')
        cursor.execute("select * from urls where url = '{}'".format(url))
        if cursor.fetchone():
            print('\ndrop out.find url.')
            continue
        input_tempdic(temp_dic,category_dic[type],url,result)
        counter+=1
        if counter>=3000 or que_input.empty():
            print('\n',counter,'datas to insert.')
            input_db(temp_dic,cursor)
            db.commit()
            counter=0
            temp_dic={}


"""
A module to pre-process and read knee x-rays

(c) Aleksei Tiulpin, University of Oulu, 2016-2018.

"""

import pydicom as dicom
import numpy as np
import cv2
import os

cv2.ocl.setUseOpenCL(False)
cv2.setNumThreads(0)
import scipy.ndimage

def resample(image, scan, new_spacing=[0.2, 0.2]):
    # Determine current pixel spacing
    spacing = map(float, (scan.PixelSpacing))
    spacing = np.array(list(spacing))

    resize_factor = spacing / new_spacing
    new_real_shape = image.shape * resize_factor
    new_shape = np.round(new_real_shape)
    real_resize_factor = new_shape / image.shape
    new_spacing = spacing / real_resize_factor

    image = scipy.ndimage.interpolation.zoom(image, real_resize_factor)

    return image, new_spacing

def read_dicom(filename):
    """
    Reads a dicom file

    Parameters
    ----------
    filename : str
        Full path to the image

    Returns
    -------
    out : tuple
        Image itself as uint16, spacing, and the DICOM metadata

    """

    try:
        data = dicom.read_file(filename)
    except:
        return None
    img = np.frombuffer(data.PixelData, dtype=np.uint16).copy().astype(np.float64)

    if data.PhotometricInterpretation == 'MONOCHROME1':
        img = img.max() - img
    try:
        img = img.reshape((data.Rows, data.Columns))
    except:
        return None

    try:
        if isinstance(data.ImagerPixelSpacing, str):
            data.ImagerPixelSpacing = data.ImagerPixelSpacing.split()
    except:
        pass

    try:
        if isinstance(data.PixelSpacing, str):
            data.PixelSpacing = data.PixelSpacing.split()
    except:
        pass

    try:
        return img, float(data.ImagerPixelSpacing[0]), data
    except:
        pass
    try:
        return img, float(data.PixelSpacing[0]), data
    except:
        return None

def process_xray(img, cut_min=5, cut_max=99, multiplier=255):
    """
    Processes an X-ray image by truncating the histogram and
    applying a global contrast normalization (GCN) to it.

    Parameters
    ----------
    img : ndarray
        Input image
    cut_min : int or float
        Lowest percentile to truncate the histogram.
    cut_max : in or float
        Highest percentile to truncate the histogram
    multiplier : a multiplication factor to use after GCN

    Returns
    -------
    out : ndarray
        A preprocessed image in np.float64.

    """
    # This function changes the histogram of the image by doing global contrast normalization
    # cut_min - lowest percentile which is used to cut the image histogram
    # cut_max - highest percentile

    img = img.copy().astype(np.float64)
    lim1, lim2 = np.percentile(img, [cut_min, cut_max])
    img[img < lim1] = lim1
    img[img > lim2] = lim2

    img -= lim1
    img /= img.max()
    img *= multiplier

    return img

def read_pts(fname):
    """
    Reads the points annotated using BineFinder.

    Parameters
    ----------
    fname : full path to the annotation

    Returns
    -------
    out : ndarray
        Nx2 ndarray of (x,y) landmark points

    """
    with open(fname) as f:
        content = f.read()
    arr = np.array(list(map(lambda x: [float(x.split()[0]), float(x.split()[1])], content.split('\n')[3:-2])))
    return arr

def f_2_b(img):
    """
    Converts a float [0..255] image into [0, 255] uint8.
    First teh function rounds the image and then clips it.

    Parameters
    ----------
    img : ndarray
        Input image

    Returns
    -------
    out : ndarray
        Results

    """
    img = np.round(img)
    img = np.clip(img, 0, 255)
    return img.astype(np.uint8)

def pad(img, padding):
    """
    Pads an image with zero padding from each side.

    Parameters
    ----------
    img : ndarray
        Input image
    padding : int
        Padding

    Returns
    -------
    out : ndarray
        Padded image

    """
    row, col = img.shape
    tmp = np.zeros((row + 2 * padding, col + 2 * padding), dtype=img.dtype)
    tmp[padding:padding + row, padding:padding + col] = img
    return tmp

def rotate(img, c, p1, p2):
    """
    Rotates an image around the point c without changing the size of the coordinate frame
    so that the line going through the points p1, p2 is horizontal.
    Used for teh alignment of tibial plateau.

    Parameters
    ----------
    img : ndarray
    c : tuple or or list or ndarray
        Center of rotation
    p1 : tuple or or list or ndarray
        First point on the line
    p2 : tuple or or list or ndarray
        Second point on teh line
    Returns
    -------
    out : tuple
        Image and the corresponding rotation matrix
    """
    # Based on https://www.pyimagesearch.com/2017/01/02/rotate-images-correctly-with-opencv-and-python/
    W = img.shape[0]
    ang = np.degrees(np.arctan2(p2[1] - p1[1], p2[0] - p1[0]))
    M = cv2.getRotationMatrix2D((c[0], c[1]), ang, 1)

    cos = np.abs(M[0, 0])
    sin = np.abs(M[0, 1])

    # compute the new bounding dimensions of the image
    nW = int((W * sin) + (W * cos))
    nH = int((W * cos) + (W * sin))

    img = cv2.warpAffine(img, M, (nW, nH), cv2.INTER_CUBIC)
    return img, M

def get_ost_jsw_patches(I, p1, p2, f_p1, f_p2, size_w, size_h, return_rects=False):
    """
    Cuts the medial and the lateral patches of size_h x size_w mm from the
    the knee image. The center of the patches will be the mean of tibial and the lateral landmarks.

    Parameters
    ----------
    I : ndarray
        Input image
    p1 : tuple or ndarray
        Tibal landmark (lateral)
    p2 : tuple or ndarray
        Tibial landmark (medial)
    f_p1 : tuple or ndarray
        Femoral landmark (lateral)
    f_p2 : tuple or ndarray
        Femoral landmark (medial)
    size_w : int
        Width in mm
    size_h : int
        Height in mm.
    return_rects : bool
        Whether to return bounding rects in the format (x0, y0, x1, y1) together with the images

    Returns
    -------
    out : tuple
        Tuple, which contains two images and their bounding boxes in the following format:
        image lateral, image medial, lateral rect, medial rect.
        If return_rects is False, then only the images are returned.

    """
    p1 = np.array([p1[0], (p1[1] + f_p1[1]) // 2])
    p2 = np.array([p2[0], (p2[1] + f_p2[1]) // 2])

    rect_l = [p1[0] - size_w // 2, p1[1] - size_h // 2, p1[0] + size_w // 2, p1[1] + size_h // 2]

    rect_m = [p2[0] - size_w // 2, p2[1] - size_h // 2, p2[0] + size_w // 2, p2[1] + size_h // 2]

    L = I[rect_l[1]:rect_l[3], rect_l[0]:rect_l[2]]
    M = I[rect_m[1]:rect_m[3], rect_m[0]:rect_m[2]]
    if return_rects:
        return L, M, rect_l, rect_m
    else:
        return L, M

def rotate_amir(coordinates, M):
    import pandas as pd
    list = []
    for i in range(len(coordinates)):
        dot = coordinates[i, :]
        dot = np.dot(M, np.array(dot.tolist() + [1])).astype(int)
        list.append(dot)
    output = np.vstack(list)

    return output

def extract_patches(I, landmarks, landmarks2, spacing, sizemm, o_sizemm_w, o_sizemm_h):
    """
    Extracts full images of left and right knees, as well as the side patches.
    Such patches are cropped for the exactly the same anatomical locations.

    Parameters
    ----------
    I : ndarray
        Input bilateral image
    spacing : float
        Image spacing
    sizemm : int
        Size of the ROI to crop (in mm)
    landmarks : dict
        Landmarks produced using Bone Finder and stored into dict per bone per knee.
    o_sizemm_w : int
        Width of the side osteophyte patch
    o_sizemm_h : int
        Width of the side osteophyte patch

    Returns
    -------
    out : tuple
        The result containes the tuple of dictionaries.
        One corresponds to the full image, then side patches and then
        the meta-information, which can be further used: bounding boxes and the rotation matrices.

    """
    # Width of the ROI
    W = int(sizemm / spacing)

    # size of the osteophyte patches in pixels
    o_size_w = int(o_sizemm_w / spacing)
    o_size_h = int(o_sizemm_h / spacing)

    # Getting the corner points from the landmarks
    p1r = landmarks['TR'][0, :].copy()
    p1l = landmarks['TL'][0, :].copy()

    p2r = landmarks['TR'][-1, :].copy()
    p2l = landmarks['TL'][-1, :].copy()

    f_p1r = landmarks['FR'][0, :].copy()
    f_p1l = landmarks['FL'][0, :].copy()

    f_p2r = landmarks['FR'][-1, :].copy()
    f_p2l = landmarks['FL'][-1, :].copy()

    # Determining the center of the joint using tibial landmarks
    Lcx, Lcy = landmarks['TL'][landmarks['TL'].shape[0] // 2, :].astype(int)
    Rcx, Rcy = landmarks['TR'][landmarks['TR'].shape[0] // 2, :].astype(int)

    # Defing the bounding boxes
    bboxR = [Rcx - W // 2, Rcy - W // 2, Rcx + W // 2, Rcy + W // 2]
    bboxL = [Lcx - W // 2, Lcy - W // 2, Lcx + W // 2, Lcy + W // 2]

    # Cropping the ROIs (left flipped)
    RR = I[bboxR[1]:bboxR[3], bboxR[0]:bboxR[2]]
    LL = cv2.flip(I[bboxL[1]:bboxL[3], bboxL[0]:bboxL[2]], 1)

    # Adjusting the points to the new coordinate frame,
    # which is within each bounding box.
    cr = np.array([Rcx, Rcy])
    cl = np.array([Lcx, Lcy])

    p1r -= bboxR[:2]
    p2r -= bboxR[:2]
    p1l -= bboxL[:2]
    p2l -= bboxL[:2]

    f_p1r -= bboxR[:2]
    f_p2r -= bboxR[:2]
    f_p1l -= bboxL[:2]
    f_p2l -= bboxL[:2]

    cr -= bboxR[:2]
    cl -= bboxL[:2]

    p1l[0] = W - p1l[0]
    p2l[0] = W - p2l[0]
    f_p1l[0] = W - f_p1l[0]
    f_p2l[0] = W - f_p2l[0]

    # Rotating the joints for normalization
    L, M1 = rotate(LL, cl, p1l, p2l)
    R, M2 = rotate(RR, cr, p1r, p2r)

    landmarks2['L'] -= bboxL[:2]
    landmarks2['L'][:, 0] = W - landmarks2['L'][:, 0]
    rotated_landmarks2 = rotate_amir(landmarks2['L'], M1)

    landmarks2['R'] -= bboxR[:2]
    rotated_landmarks1 = rotate_amir(landmarks2['R'], M2)

    # Rotating the corresponding points
    p1l = np.dot(M1, np.array(p1l.tolist() + [1])).astype(int)
    p2l = np.dot(M1, np.array(p2l.tolist() + [1])).astype(int)

    p1r = np.dot(M2, np.array(p1r.tolist() + [1])).astype(int)
    p2r = np.dot(M2, np.array(p2r.tolist() + [1])).astype(int)

    f_p1l = np.dot(M1, np.array(f_p1l.tolist() + [1])).astype(int)
    f_p2l = np.dot(M1, np.array(f_p2l.tolist() + [1])).astype(int)

    f_p1r = np.dot(M2, np.array(f_p1r.tolist() + [1])).astype(int)
    f_p2r = np.dot(M2, np.array(f_p2r.tolist() + [1])).astype(int)

    right_lateral, right_medial, = get_ost_jsw_patches(R, p1r, p2r, f_p1r, f_p2r, o_size_w, o_size_h)
    left_lateral, left_medial, = get_ost_jsw_patches(L, p1l, p2l, f_p1l, f_p2l, o_size_w, o_size_h)

    full_images = {'R': R, 'L': L}
    side_patches = {'R': {'lat': f_2_b(right_lateral), 'med': f_2_b(right_medial)},
                    'L': {'lat': f_2_b(left_lateral), 'med': f_2_b(left_medial)}}

    metadata = {'R': {'bbox': bboxR, 'rotM': M2},
                'L': {'bbox': bboxL, 'rotM': M1}}
    import matplotlib.pyplot as plt
    # plt.figure()
    # plt.imshow(RR)

    return full_images, side_patches, metadata, rotated_landmarks2, rotated_landmarks1, R, L

def read_pts_tibia_femur(pts_fname, spacing, padding):
    """
    Reads only the tibial and femoral plateaus' landmarks

    Parameters
    ----------
    pts_fname : str
        Full path to the file with points annotated with BoneFinder
    spacing : float
        Image spacing from DICOM file
    padding : int
        Padding to add to the image

    Returns
    -------
    out : tuple
        Femoral and tibial landmarks

    """
    points = np.round(read_pts(pts_fname) * 1. / spacing) + padding
    # landmarks_f = points[12:25, :]
    # landmarks_t = points[47:64, :]
    return points

def read_pts_tibia_femur2(pts_fname, spacing, padding):
    """
    Reads only the tibial and femoral plateaus' landmarks

    Parameters
    ----------
    pts_fname : str
        Full path to the file with points annotated with BoneFinder
    spacing : float
        Image spacing from DICOM file
    padding : int
        Padding to add to the image

    Returns
    -------
    out : tuple
        Femoral and tibial landmarks

    """
    points = np.round(read_pts(pts_fname) * 1. / spacing) + padding
    landmarks_f = points[12:25, :]
    landmarks_t = points[47:64, :]
    return landmarks_f, landmarks_t

def worker(job_data):
    """
    General worker to be used in multi-core processing of X-rays stored in DICOM
    format.

    Parameters
    ----------
    job_data : tuple or list
        Job data, which has sufficient information to extract
        filename to the DICOM image, full path to the landmarks (left and right ones),
        and, finally the path to save the results
    job_preproc_hook : function
        function, which must return scirpt's arguments, filename to the DICOM image, full path to the landmarks (left and right ones),
        and, finally the path to save the results

    Returns
    -------
    out : int
        Returns 0, if the data were successfully read and 1 if not.

    """
    args, fname, pts_fname_l, pts_fname_r, path_save = job_data
    if os.path.isfile(path_save):
        return 0
    res = read_dicom(fname)
    if res is None:
        return 1
    I, orig_spacing, img_metadata = res
    dd = img_metadata.pixel_array
    scale = orig_spacing / args.spacing

    I = process_xray(I).astype(np.uint8)
    I = pad(I, padding=args.pad)
    row, col = I.shape

    landmarks_l = read_pts_tibia_femur(pts_fname_l, orig_spacing, args.pad)
    landmarks_r = read_pts_tibia_femur(pts_fname_r, orig_spacing, args.pad)

    landmarks_r[:, 0] = col - landmarks_r[:, 0]

    # displ_img(I,landmarksTL, landmarksFL, landmarksTR, landmarksFR)
    landmarks2 = {'R': landmarks_r * scale,
                  'L': landmarks_l * scale}

    landmarks_fl, landmarks_tl = read_pts_tibia_femur2(pts_fname_l, orig_spacing, args.pad)
    landmarks_fr, landmarks_tr = read_pts_tibia_femur2(pts_fname_r, orig_spacing, args.pad)

    landmarks_fr[:, 0] = col - landmarks_fr[:, 0]
    landmarks_tr[:, 0] = col - landmarks_tr[:, 0]

    # displ_img(I,landmarksTL, landmarksFL, landmarksTR, landmarksFR)
    landmarks = {'TR': landmarks_tr * scale,
                 'FR': landmarks_fr * scale,
                 'TL': landmarks_tl * scale,
                 'FL': landmarks_fl * scale}

    # Scaling to the new spacing
    I = cv2.resize(I, (int(col * scale), int(row * scale)), interpolation=cv2.INTER_CUBIC)
    try:
        full_images, side_patches, metadata, rotated_landmarks_L, rotated_landmarks_R, R, L = extract_patches(I,
                                                                                landmarks,
                                                                                landmarks2,
                                                                                args.spacing,
                                                                                args.sizemm,
                                                                                args.o_sizemm_w,
                                                                                args.o_sizemm_h)
    except:
        return 1
    # import os
    # imageR, new_spacing = resample(RR, img_metadata)
    # imageL, new_spacing = resample(RR, img_metadata)

    import matplotlib
    import matplotlib.pyplot as plt
    # plt.figure(figsize=(10.8, 10.8))
    # plt.imshow(image, cmap=plt.cm.bone)
    # Displacement = metadata['R']['bbox']
    # rightlanmark = landmarks2['R']
    # rightlanmark[:, 0] -= Displacement[0]
    # rightlanmark[:, 1] -= Displacement[1]
    # plt.scatter(x=rotated_landmarks1[:, 0], y=rotated_landmarks1[:, 1], c='r', s=10)
    # plt.axis('off')
    ##### os.mkdir(path_save)
    # plt.savefig(path_save + 'R.jpg', bbox_inches='tight')
    # plt.figure(figsize=(10.8, 10.8))
    # plt.imshow(L, cmap=plt.cm.bone)
    # plt.scatter(x=rotated_landmarks2[:, 0], y=rotated_landmarks2[:, 1], c='r', s=10)
    # plt.axis('off')
    # plt.savefig(path_save + 'L.jpg', bbox_inches='tight')

    # np.save(path_save, [full_images, side_patches, metadata, landmarks, landmarks2, img_metadata.Modality, args.spacing])
    R = R.astype('float')
    L = L.astype('float')
    # matplotlib.image.imsave(path_save + 'R.jpg', imageR,
    #                         cmap=plt.cm.bone)
    #
    # matplotlib.image.imsave(path_save + 'L.jpg', imageL,
    #                         cmap=plt.cm.bone)

    return 0, rotated_landmarks_R, rotated_landmarks_L, L, R


# Kopyalama atan balası

from userbot.cmdhelp import CmdHelp
from telethon.tl import functions
from telethon.tl.functions.messages import GetFullChatRequest
from telethon.errors import (
    ChannelInvalidError,
    ChannelPrivateError,
    ChannelPublicGroupNaError)
from telethon.tl.functions.channels import GetFullChannelRequest
from userbot.events import register as aykhan

async def get_chatinfo(event):
    chat = event.pattern_match.group(1)
    chat_info = None
    if chat:
        try:
            chat = int(chat)
        except ValueError:
            pass
    if not chat:
        if event.reply_to_msg_id:
            replied_msg = await event.get_reply_message()
            if replied_msg.fwd_from and replied_msg.fwd_from.channel_id is not None:
                chat = replied_msg.fwd_from.channel_id
        else:
            chat = event.chat_id
    try:
        chat_info = await event.client(GetFullChatRequest(chat))
    except BaseException:
        try:
            chat_info = await event.client(GetFullChannelRequest(chat))
        except ChannelInvalidError:
            await event.reply("`Səhv Kanal/Qrup`")
            return None
        except ChannelPrivateError:
            await event.reply("`Bu özəl bir kanal/qrupdur və ya oradan mənə qadağa qoyulub`")
            return None
        except ChannelPublicGroupNaError:
            await event.reply("`Kanal və ya superqrup yoxdur`")
            return None
        except (TypeError, ValueError):
            await event.reply("`Səhv Kanal/Qrup`")
            return None
    return chat_info

@aykhan(outgoing=True, pattern=r"^\.add(?: |$)(.*)")
async def get_users(event):
    sender = await event.get_sender()
    me = await event.client.get_me()
    if not sender.id == me.id:
        ram = await event.reply("`Əlavə olunur...`")
    else:
        ram = await event.edit("`Əlavə olunur biraz gözləyin...`")
    ramubotteam = await get_chatinfo(event)
    chat = await event.get_chat()
    if event.is_private:
        return await ram.edit("`Üzr istəyirik, bura bir istifadəçi əlavə edin`")
    s = 0
    f = 0
    error = 'None'

    await ram.edit("**Terminal vəziyyəti**\n\n`İstifadəçilərin toplanması.......`")
    async for user in event.client.iter_participants(ramubotteam.full_chat.id):
        try:
            if error.startswith("Too"):
                return await ram.edit(f"**Terminal Xəta ilə Tamamlandı**\n(`Telethon Limit Xətası Alıb Zəhmət olmasa Daha Sonra Yenidən Sınayın`)\n**Xəta** : \n`{error}`\n\n• Uğurlu: \n `{s}` istifadəçi \n• Uğursuz: \n `{f}` istifadəçi")
            await event.client(functions.channels.InviteToChannelRequest(channel=chat, users=[user.id]))
            s = s + 1
            await ram.edit(f"**Terminal Çalışır...**\n\n• Uğurlu: \n `{s}` istifadəçi \n• Uğursuz: \n `{f}` istifadəçi\n\n**× Son Səhv:** `{error}`")
        except Exception as e:
            error = str(e)
            f = f + 1
    return await ram.edit(f"**Terminal Bitdi** \n\n• Uğurla `{s}` istifadəçi dəvət olundu \n• Uğursuz `{f}` istifadəçi")
# Köməy
CmdHelp('add').add_command(
   'add', '<qrup username>', 'Linkini yazdığınız qrupdan istifadəçiləri daşıyar 🙂'
).add()
# Support
# BozQurd - add.py


import pygame
import neat
import time
import os
import random
import math
import pickle
pygame.font.init()

#create a game of asteroids that learns using neat.
#The player can rotate, shoot forward, thrust forward and keep that velocity, there is no break either. The player should be able to see in an appropriate amount of directions around themselves (8 maybe?)
    #this might be done by creating a ray type object come out from the player and see if it collides with anything and then return the distance from the player to that collison
#the asteroids should spawn in 3 sizes, small medium and large, when they are shot they break into 2 of the smaller denominations, the small ones just die. They spawn offscreen and move in a random direction and velocity.
#if anything goes off screen they should loop back around
    #this may be hard so maybe just kill anything off screen

#set our screen size and font
WIN_WIDTH = 800
WIN_HEIGHT = 800
STAT_FONT = pygame.font.SysFont("comicsans", 50)
#set game speed, making this number higher will let generations go faster
GAME_SPEED = 1
#constant to convert degrees to radians
D_TO_R = math.pi / 180
#theres a better way to track gens globally
gen = 0

#get the slope of a line
def get_slope(line):
    xdif = line[1][1] - line[0][1]
    ydif = line[1][0] - line[0][0]
    if ydif == 0:
        return 9999
    return xdif / ydif

#get the y intercept of a line given the line
def get_y_int(line):
    return line[0][1] - get_slope(line) * line[0][0]

#check if a number is between two other numbers regardless of sign
def is_between_points(middle, end1, end2):
    if middle < end1 and middle > end2 or middle > end1 and middle < end2:
        return True

#decide if a point is on a line
def is_on_line(point, line):
    if is_between_points(point[0], line[1][0], line[0][0]):
        if is_between_points(point[1], line[1][1], line[0][1]):
            return True
    return False

#given two lines use y=mx+b to find if they intersect
def find_intersection(line1, line2):
    m1 = get_slope(line1)
    m2 = get_slope(line2)
    b1 = get_y_int(line1)
    b2 = get_y_int(line2)
    if m1 == m2:
        return False
    x = (b2 - b1) / (m1-m2)
    y = m1* x + b1
    if is_on_line((x, y), line1) and is_on_line((x, y), line2):
        return x, y
    return False

#get the distance between two points
def get_distance(point1, point2):
        xdif = (point1[0] - point2[0])**2
        ydif = (point1[1] - point2[1])**2
        return int(math.sqrt(xdif + ydif))

class Ship:
    def __init__(self):
        self.x = WIN_WIDTH // 2
        self.y = WIN_HEIGHT // 2
        self.MAX_SPEED = 7
        self.size = 20
        self.rotation = 0
        self.rad_rotation = 0
        self.speed = 0
        self.horizontal_speed = 0
        self.vertical_speed = 0
        self.is_thrust = False

    def thrust(self):
        self.horizontal_speed += math.cos(self.rotation * D_TO_R) / 2
        self.vertical_speed += math.sin(self.rotation * D_TO_R) / 2
        self.stay_under_max_speed()
        self.speed = math.sqrt(self.horizontal_speed**2 + self.vertical_speed**2)
        self.is_thrust = True

    def stay_under_max_speed(self):
        if self.horizontal_speed > self.MAX_SPEED:
            self.horizontal_speed = self.MAX_SPEED
        if self.vertical_speed > self.MAX_SPEED:
            self.vertical_speed = self.MAX_SPEED

    def glide(self):
        if not self.is_thrust and self.horizontal_speed != 0:
            self.horizontal_speed -= self.horizontal_speed * 0.02
        if not self.is_thrust and self.vertical_speed != 0:
            self.vertical_speed -= self.vertical_speed * 0.02

    def stay_on_screen(self):
        if self.x > WIN_WIDTH:
            self.x = 0
        elif self.x < 0:
            self.x = WIN_WIDTH
        if self.y > WIN_HEIGHT:
            self.y = 0
        elif self.y < 0:
            self.y = WIN_HEIGHT

    def rotate_left(self):
        self.rotation -= 8
        self.rad_rotation = math.radians(self.rotation)

    def rotate_right(self):
        self.rotation += 8
        self.rad_rotation = math.radians(self.rotation)

    def move(self):
        self.glide()
        self.x += self.horizontal_speed
        self.y += self.vertical_speed
        self.stay_on_screen()

    def shoot(self):
        return Bullet(self.x, self.y, self.rotation)

    def get_ship_coordinates(self):
        const0 = (self.size * math.sqrt(130) / 12)
        const1 = math.atan(7 / 9)
        coord1 = (int(self.x - const0 * math.cos(const1 + self.rad_rotation)), int(self.y - const0 * math.sin(const1 + self.rad_rotation)))
        coord2 = (int(self.x - const0 * math.cos(const1 - self.rad_rotation)), int(self.y + const0 * math.sin(const1 - self.rad_rotation)))
        coord3 = (int(self.x + self.size * math.cos(self.rad_rotation)), int(self.y + self.size * math.sin(self.rad_rotation)))
        return coord1, coord2, coord3

    def draw(self, win):
        coord1, coord2, coord3 = self.get_ship_coordinates()
        pygame.draw.lines(win, (255,255,255), True, (coord1,coord2, coord3))
        if self.is_thrust:
            self.is_thrust = False
            coord1 = (int(self.x - (self.size+10) * math.cos(self.rad_rotation)), int(self.y - (self.size+10) * math.sin(self.rad_rotation)))
            coord2 = (int(self.x - ((self.size+10) * 0.5 * math.cos(self.rad_rotation + math.pi / 6))), int(self.y - ((self.size+10) * 0.5 * math.sin(self.rad_rotation + math.pi / 6))))
            pygame.draw.line(win, (255,255,255), coord1, coord2)
            coord1 = (int(self.x - (self.size+10) * math.cos(-self.rad_rotation)), int(self.y + (self.size+10) * math.sin(-self.rad_rotation)))
            coord2 = (int(self.x - ((self.size+10) * 0.5 * math.cos(-self.rad_rotation + math.pi / 6))), int(self.y + ((self.size+10) * 0.5 * math.sin(-self.rad_rotation + math.pi / 6))))
            pygame.draw.line(win, (255,255,255), coord1, coord2)

class Bullet:
    def __init__(self, x, y, direction):
        self.x = x
        self.y = y
        self.VEL = 80
        self.direction = direction
        self.life_time = 10
        self.alive = True

    def move(self):
        self.life_time -= 1
        self.x += self.VEL * math.cos(self.direction * D_TO_R)
        self.y += self.VEL * math.sin(self.direction * D_TO_R)
        if self.life_time < 0:
            self.alive = False
        return not self.alive

    def draw(self, win):
        pygame.draw.circle(win, (255,255,255), (int(self.x), int(self.y)), 2)

class Asteroid:
    def __init__(self, x = -1, y = -1, size = -1, direction = -1):
        if size != -1:
            self.size = size
        else:
            self.size = random.randint(0,2)
            if self.size == 0:
                self.size = 20
            elif self.size == 1:
                self.size = 40
            elif self.size == 2:
                self.size = 80
        if x == -1:
            self.x = 0
        else:
            self.x = x
        if y == -1:
            self.y = random.randrange(0, WIN_HEIGHT)
        else:
            self.y = y
        if direction == -1:
            self.direction = random.randrange(0, 360) * D_TO_R
        else:
            self.direction = direction * D_TO_R
        self.speed = random.randrange(3, 7)
        self.rotation = 0
        self.lines = []

        # Make random asteroid sprites
        full_circle = random.uniform(45,55)
        self.vertices = []
        while full_circle < 360:
            self.vertices.append([self.size, full_circle])
            dist = self.size * 0.9
            full_circle += random.uniform(45, 55)

        for v in range(len(self.vertices)):
            if v == len(self.vertices) - 1:
                next_v = self.vertices[0]
            else:
                next_v = self.vertices[v + 1]
            this_v = self.vertices[v]
            line = ((int(self.x + this_v[0] * math.cos(this_v[1] * D_TO_R)), int(self.y + this_v[0] * math.sin(this_v[1] * D_TO_R))),
            (int(self.x + next_v[0] * math.cos(next_v[1] * D_TO_R)), int(self.y + next_v[0] * math.sin(next_v[1] * D_TO_R))))
            self.lines.append(line)

    def move(self):
        self.x += self.speed / 1.5 * math.cos(self.direction)
        self.y += self.speed / 1.5 * math.sin(self.direction)
        self.rotate()
        if self.x > WIN_WIDTH + self.size:
            self.x = -self.size
        elif self.x < -self.size:
            self.x = WIN_WIDTH + self.size
        if self.y > WIN_HEIGHT + self.size:
            self.y = -self.size
        elif self.y < -self.size:
            self.y = WIN_HEIGHT + self.size

    def rotate(self):
        self.rotation += 2

    def draw(self, win):
        for v in range(len(self.vertices)):
            if v == len(self.vertices) - 1:
                next_v = self.vertices[0]
            else:
                next_v = self.vertices[v + 1]
            this_v = self.vertices[v]
            x1 = (self.x + this_v[0] * math.cos(this_v[1] * D_TO_R)) - self.x
            y1 = (self.y + this_v[0] * math.sin(this_v[1] * D_TO_R)) - self.y
            x2 = (self.x + next_v[0] * math.cos(next_v[1] * D_TO_R)) - self.x
            y2 = (self.y + next_v[0] * math.sin(next_v[1] * D_TO_R)) - self.y
            x11 = (x1 * math.cos(self.rotation * D_TO_R) - y1 * math.sin(self.rotation * D_TO_R)) + self.x
            y11 = (y1 * math.cos(self.rotation * D_TO_R) + x1 * math.sin(self.rotation * D_TO_R)) + self.y
            x22 = (x2 * math.cos(self.rotation * D_TO_R) - y2 * math.sin(self.rotation * D_TO_R)) + self.x
            y22 = (y2 * math.cos(self.rotation * D_TO_R) + x2 * math.sin(self.rotation * D_TO_R)) + self.y
            line = ((int(x11), int(y11)), (int(x22), int(y22)))
            self.lines[v] = line
            pygame.draw.line(win, (255,255,255), line[0], line[1])

class Game:
    def __init__(self, win):
        self.ship = Ship()
        self.asteroids = []
        self.bullets = []
        self.distances = []
        self.sight_lines = []
        self.stationary_count = 200
        self.score = 0
        self.shoot_cooldown = 0
        self.win = win
        self.hit_asteroid = False
        self.bullet_missed = False
        self.num_bullets_missed = 0
        for i in range(4):
            self.asteroids.append(Asteroid())
        self.asteroids.append(Asteroid(WIN_WIDTH / 2, WIN_HEIGHT / 4, 40, 90))

    def move(self):
        self.ship.move()
        self.sight_lines = (
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos(self.ship.rotation * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin(self.ship.rotation * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation + 45) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation + 45) * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation - 45) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation - 45) * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation + 90) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation + 90) * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation - 90) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation - 90) * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation + 135) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation + 135) * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation - 135) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation - 135) * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation + 180) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation + 180) * D_TO_R) * WIN_HEIGHT * 2))),
            ((int(self.ship.x), int(self.ship.y)), (int(self.ship.x + math.cos((self.ship.rotation - 180) * D_TO_R) * WIN_WIDTH * 2), int(self.ship.y + math.sin((self.ship.rotation - 180) * D_TO_R) * WIN_HEIGHT * 2)))
        )
        self.distances = self.get_sight()
        self.shoot_cooldown -= 1
        self.hit_asteroid = self.check_collisions(self.win)
        self.bullet_missed = False
        if len(self.asteroids) < 5:
            flag = random.randint(0,1)
            if flag == 0:
                self.attack_player()
            else:
                self.asteroids.append(Asteroid())
        if self.ship.speed != 0:
            self.stationary_count -= 1
        else:
            self.stationary_count -= 2
        if self.stationary_count < 1:
            self.stationary_count = 200
            if len(self.asteroids) < 12:
                self.attack_player()
        for asteroid in self.asteroids:
            asteroid.move()
        for bullet in self.bullets:
            self.bullet_missed = bullet.move()
            if self.bullet_missed:
                self.bullets.remove(bullet)
                break

    def shoot(self):
        if self.shoot_cooldown <= 0:
            self.bullets.append(self.ship.shoot())
            self.shoot_cooldown = 40

    def is_colliding(self, x, y, xTo, yTo, size):
        if x > xTo - size and x < xTo + size and y > yTo - size and y < yTo + size:
            return True
        return False

    def check_collisions(self, win):
        for b in self.bullets:
            for a in self.asteroids:
                if self.is_colliding(b.x, b.y, a.x, a.y, a.size):
                    if a.size != 20:
                        self.asteroids.append(Asteroid(a.x, a.y, a.size / 2, a.direction - random.randrange(5, 20)))
                        self.asteroids.append(Asteroid(a.x, a.y, a.size / 2, a.direction + random.randrange(5, 20)))
                    self.asteroids.remove(a)
                    self.bullets.remove(b)
                    self.score += 1
                    return True
        return False

    def get_sight(self):
        s_lines = self.sight_lines
        distances = []
        for sl in self.sight_lines:
            closest = 10000
            for a in self.asteroids:
                for al in a.lines:
                    coord = find_intersection(sl, al)
                    if coord:
                        dis = get_distance((self.ship.x, self.ship.y), coord)
                        if dis < closest:
                            closest = dis
            distances.append(closest)
        return distances

    def attack_player(self):
        s = self.ship
        for i in range(random.randint(2,4)):
            temp = 0
            while abs(temp) < 200:
                x = self.ship.x + random.randint(-300, 300)
                temp = self.ship.x - x
            temp = 0
            while abs(temp) < 200:
                y = self.ship.y + random.randint(-300, 300)
                temp = self.ship.y - y
            angle = math.atan2(self.ship.x - x, y - self.ship.y) * 180 / math.pi + 270
            self.asteroids.append(Asteroid(x,y, -1, angle))

def draw_window(win, ship, bullets, asteroids, score, gen):
    win.fill((0,0,0))
    for asteroid in asteroids:
        asteroid.draw(win)
    for bullet in bullets:
        bullet.draw(win)
    ship.draw(win)
    text = STAT_FONT.render("Score: " + str(score), 1, (255,255,255))
    win.blit(text, (int(WIN_WIDTH / 2 - text.get_width() / 2), 150))
    text = STAT_FONT.render("Generation: " + str(gen), 1, (255,255,255))
    win.blit(text, (int(WIN_WIDTH / 2 - text.get_width() / 2), 100))
    pygame.display.update()

def neat_main(genomes, config):
    global gen
    gen += 1
    nets = []
    ge = []
    games = []
    best_fitness = 0
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    clock = pygame.time.Clock()

    for _,g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        games.append(Game(win))
        g.fitness = 0
        ge.append(g)
    best_genome = ge[0]

    run = True
    while run:
        clock.tick(30 * GAME_SPEED)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        if len(games) < 1:
            run = False
            break

        for x, game in enumerate(games):
            ship = game.ship
            game.move()

            if x == 0:
                s = getattr(game, 'ship')
                b = game.bullets
                a = game.asteroids
                sc = game.score
                draw_window(win, s, b, a, sc, gen)

            outputs = nets[x].activate((game.distances[0], game.distances[1], game.distances[2], game.distances[3], game.distances[4], game.distances[5], game.distances[6], game.distances[7]))
            if outputs[0] > 0.8:
                ship.rotate_left()
            if outputs[1] > 0.8:
                ship.rotate_right()
            if outputs[2] > 0.8:
                ge[x].fitness -= .009
                ship.thrust()
            if outputs[3] > 0.75:
                game.shoot()

            if game.hit_asteroid:
                ge[x].fitness += 2
            if game.bullet_missed:
                ge[x].fitness -= 1
            ge[x].fitness += 0.01
            for a in game.asteroids:
                if game.is_colliding(ship.x, ship.y, a.x, a.y, a.size):
                    ge[x].fitness -= 5
                    if ge[x].fitness > best_fitness:
                        best_fitness = ge[x].fitness
                        best_genome = ge[x]
                    games.pop(x)
                    nets.pop(x)
                    ge.pop(x)
                    break
    #create or open a pickle file to write to named f and save our linear data in it
    name = "pickles/best_genome_gen_" + str(gen) + ".p"
    pickle.dump(best_genome, open(name, "wb"))

def replay_main(genomes, config):
    global gen
    gen += 1
    nets = []
    ge = []
    games = []
    best_fitness = 0
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    clock = pygame.time.Clock()

    for _,g in genomes:
        net = neat.nn.FeedForwardNetwork.create(g, config)
        nets.append(net)
        games.append(Game(win))
        g.fitness = 0
        ge.append(g)
    best_genome = ge[0]

    run = True
    while run:
        clock.tick(30 * GAME_SPEED)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()

        if len(games) < 1:
            run = False
            break

        for x, game in enumerate(games):
            ship = game.ship
            game.move()

            if x == 0:
                s = getattr(game, 'ship')
                b = game.bullets
                a = game.asteroids
                sc = game.score
                draw_window(win, s, b, a, sc, gen)
            outputs = nets[x].activate((game.distances[0], game.distances[1], game.distances[2], game.distances[3], game.distances[4], game.distances[5], game.distances[6], game.distances[7]))
            if outputs[0] > 0.8:
                ship.rotate_left()
            if outputs[1] > 0.8:
                ship.rotate_right()
            if outputs[2] > 0.8:
                ship.thrust()
                ge[x].fitness -= (0.005 + game.ship.speed * 0.001)
            if outputs[3] > 0.75:
                game.shoot()

            if game.hit_asteroid:
                ge[x].fitness += 2
            if game.bullet_missed:
                ge[x].fitness -= 1
            ge[x].fitness += .01
            for a in game.asteroids:
                if game.is_colliding(ship.x, ship.y, a.x, a.y, a.size):
                    if ge[x].fitness > best_fitness:
                        best_fitness = ge[x].fitness
                        best_genome = ge[x]
                    print(best_fitness)
                    games.pop(x)
                    nets.pop(x)
                    ge.pop(x)
                    break

def player_main():
    win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT))
    clock = pygame.time.Clock()
    global gen
    gen = "Player"
    game = Game(win)

    run = True
    while run:
        clock.tick(30 * GAME_SPEED)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False
                pygame.quit()
                quit()
        #check for user input
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_SPACE:
                    game.shoot()

        pressed = pygame.key.get_pressed()
        if pressed[pygame.K_w]:
            game.ship.thrust()
        if pressed[pygame.K_a]:
            game.ship.rotate_left()
        if pressed[pygame.K_d]:
            game.ship.rotate_right()

        game.move()
        draw_window(win, game.ship, game.bullets, game.asteroids, game.score, gen)

        for a in game.asteroids:
            if game.is_colliding(game.ship.x, game.ship.y, a.x, a.y, a.size):
                run = False
                break

def load_pickles(config_path):
    file_paths = []
    for root, directories, files in os.walk("pickles"):
        for filename in files:
            filepath = os.path.join(root, filename)
            file_paths.append(filepath)
    for path in file_paths:
        replay_genome(config_path, path)

def replay_genome(config_path, pickle_path):
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path)
    with open(pickle_path, "rb") as f:
        genome = pickle.load(f)
    genomes = [(1,genome)]
    replay_main(genomes, config)

def run(config_path):
    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction, neat.DefaultSpeciesSet, neat.DefaultStagnation, config_path)
    p = neat.Population(config)
    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)
    winner = p.run(neat_main,500)

if __name__ == "__main__":
    flag = True
    while flag:
        print("Would you like to...")
        print("Run NEAT (1)")
        print("Replay the best of each last recorded generation? (2)")
        print("Play the game yourself? (3)")
        x = int(input())
        if x == 1 or x == 2 or x == 3:
            flag = False
    if x == 3:
        player_main()
    input
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, "config-feedforward.txt")
    if x == 1:
        run(config_path)
    elif x == 2:
        load_pickles(config_path)


## single number

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

        """
        Algorithm - Hashset
        TO(n), SO(n)
        """
        # sets = set()
        # for i in nums:
        #     if i not in sets:
        #         sets.add(i)
        #     else:
        #         sets.remove(i)
        # x = sets.pop()
        # return x

        """
        Algorithm - Bit Manipulation
        TO(n), SO(1)
        """
        a = 0
        for i in nums:
            a ^= i
        return a


# coding: utf-8

"""
    ThingsBoard REST API

    For instructions how to authorize requests please visit REST API documentation page.  # noqa: E501

    OpenAPI spec version: 2.0
    Contact: info@thingsboard.io
    Generated by: https://github.com/swagger-api/swagger-codegen.git
"""

import pprint
import re  # noqa: F401

import six

class DeviceProfile(object):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """
    """
    Attributes:
      swagger_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    swagger_types = {
        'created_time': 'int',
        'default': 'bool',
        'default_dashboard_id': 'DashboardId',
        'default_queue_name': 'str',
        'default_rule_chain_id': 'RuleChainId',
        'description': 'str',
        'firmware_id': 'OtaPackageId',
        'id': 'DeviceProfileId',
        'image': 'str',
        'name': 'str',
        'profile_data': 'DeviceProfileData',
        'provision_device_key': 'str',
        'provision_type': 'str',
        'software_id': 'OtaPackageId',
        'tenant_id': 'TenantId',
        'transport_type': 'str',
        'type': 'str'
    }

    attribute_map = {
        'created_time': 'createdTime',
        'default': 'default',
        'default_dashboard_id': 'defaultDashboardId',
        'default_queue_name': 'defaultQueueName',
        'default_rule_chain_id': 'defaultRuleChainId',
        'description': 'description',
        'firmware_id': 'firmwareId',
        'id': 'id',
        'image': 'image',
        'name': 'name',
        'profile_data': 'profileData',
        'provision_device_key': 'provisionDeviceKey',
        'provision_type': 'provisionType',
        'software_id': 'softwareId',
        'tenant_id': 'tenantId',
        'transport_type': 'transportType',
        'type': 'type'
    }

    def __init__(self, created_time=None, default=None, default_dashboard_id=None, default_queue_name=None, default_rule_chain_id=None, description=None, firmware_id=None, id=None, image=None, name=None, profile_data=None, provision_device_key=None, provision_type=None, software_id=None, tenant_id=None, transport_type=None, type=None):  # noqa: E501
        """DeviceProfile - a model defined in Swagger"""  # noqa: E501
        self._created_time = None
        self._default = None
        self._default_dashboard_id = None
        self._default_queue_name = None
        self._default_rule_chain_id = None
        self._description = None
        self._firmware_id = None
        self._id = None
        self._image = None
        self._name = None
        self._profile_data = None
        self._provision_device_key = None
        self._provision_type = None
        self._software_id = None
        self._tenant_id = None
        self._transport_type = None
        self._type = None
        self.discriminator = None
        if created_time is not None:
            self.created_time = created_time
        if default is not None:
            self.default = default
        if default_dashboard_id is not None:
            self.default_dashboard_id = default_dashboard_id
        if default_queue_name is not None:
            self.default_queue_name = default_queue_name
        if default_rule_chain_id is not None:
            self.default_rule_chain_id = default_rule_chain_id
        if description is not None:
            self.description = description
        if firmware_id is not None:
            self.firmware_id = firmware_id
        if id is not None:
            self.id = id
        if image is not None:
            self.image = image
        if name is not None:
            self.name = name
        if profile_data is not None:
            self.profile_data = profile_data
        if provision_device_key is not None:
            self.provision_device_key = provision_device_key
        if provision_type is not None:
            self.provision_type = provision_type
        if software_id is not None:
            self.software_id = software_id
        if tenant_id is not None:
            self.tenant_id = tenant_id
        if transport_type is not None:
            self.transport_type = transport_type
        if type is not None:
            self.type = type

    @property
    def created_time(self):
        """Gets the created_time of this DeviceProfile.  # noqa: E501

        :return: The created_time of this DeviceProfile.  # noqa: E501
        :rtype: int
        """
        return self._created_time

    @created_time.setter
    def created_time(self, created_time):
        """Sets the created_time of this DeviceProfile.

        :param created_time: The created_time of this DeviceProfile.  # noqa: E501
        :type: int
        """

        self._created_time = created_time

    @property
    def default(self):
        """Gets the default of this DeviceProfile.  # noqa: E501

        :return: The default of this DeviceProfile.  # noqa: E501
        :rtype: bool
        """
        return self._default

    @default.setter
    def default(self, default):
        """Sets the default of this DeviceProfile.

        :param default: The default of this DeviceProfile.  # noqa: E501
        :type: bool
        """

        self._default = default

    @property
    def default_dashboard_id(self):
        """Gets the default_dashboard_id of this DeviceProfile.  # noqa: E501

        :return: The default_dashboard_id of this DeviceProfile.  # noqa: E501
        :rtype: DashboardId
        """
        return self._default_dashboard_id

    @default_dashboard_id.setter
    def default_dashboard_id(self, default_dashboard_id):
        """Sets the default_dashboard_id of this DeviceProfile.

        :param default_dashboard_id: The default_dashboard_id of this DeviceProfile.  # noqa: E501
        :type: DashboardId
        """

        self._default_dashboard_id = default_dashboard_id

    @property
    def default_queue_name(self):
        """Gets the default_queue_name of this DeviceProfile.  # noqa: E501

        :return: The default_queue_name of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._default_queue_name

    @default_queue_name.setter
    def default_queue_name(self, default_queue_name):
        """Sets the default_queue_name of this DeviceProfile.

        :param default_queue_name: The default_queue_name of this DeviceProfile.  # noqa: E501
        :type: str
        """

        self._default_queue_name = default_queue_name

    @property
    def default_rule_chain_id(self):
        """Gets the default_rule_chain_id of this DeviceProfile.  # noqa: E501

        :return: The default_rule_chain_id of this DeviceProfile.  # noqa: E501
        :rtype: RuleChainId
        """
        return self._default_rule_chain_id

    @default_rule_chain_id.setter
    def default_rule_chain_id(self, default_rule_chain_id):
        """Sets the default_rule_chain_id of this DeviceProfile.

        :param default_rule_chain_id: The default_rule_chain_id of this DeviceProfile.  # noqa: E501
        :type: RuleChainId
        """

        self._default_rule_chain_id = default_rule_chain_id

    @property
    def description(self):
        """Gets the description of this DeviceProfile.  # noqa: E501

        :return: The description of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._description

    @description.setter
    def description(self, description):
        """Sets the description of this DeviceProfile.

        :param description: The description of this DeviceProfile.  # noqa: E501
        :type: str
        """

        self._description = description

    @property
    def firmware_id(self):
        """Gets the firmware_id of this DeviceProfile.  # noqa: E501

        :return: The firmware_id of this DeviceProfile.  # noqa: E501
        :rtype: OtaPackageId
        """
        return self._firmware_id

    @firmware_id.setter
    def firmware_id(self, firmware_id):
        """Sets the firmware_id of this DeviceProfile.

        :param firmware_id: The firmware_id of this DeviceProfile.  # noqa: E501
        :type: OtaPackageId
        """

        self._firmware_id = firmware_id

    @property
    def id(self):
        """Gets the id of this DeviceProfile.  # noqa: E501

        :return: The id of this DeviceProfile.  # noqa: E501
        :rtype: DeviceProfileId
        """
        return self._id

    @id.setter
    def id(self, id):
        """Sets the id of this DeviceProfile.

        :param id: The id of this DeviceProfile.  # noqa: E501
        :type: DeviceProfileId
        """

        self._id = id

    @property
    def image(self):
        """Gets the image of this DeviceProfile.  # noqa: E501

        :return: The image of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._image

    @image.setter
    def image(self, image):
        """Sets the image of this DeviceProfile.

        :param image: The image of this DeviceProfile.  # noqa: E501
        :type: str
        """

        self._image = image

    @property
    def name(self):
        """Gets the name of this DeviceProfile.  # noqa: E501

        :return: The name of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._name

    @name.setter
    def name(self, name):
        """Sets the name of this DeviceProfile.

        :param name: The name of this DeviceProfile.  # noqa: E501
        :type: str
        """

        self._name = name

    @property
    def profile_data(self):
        """Gets the profile_data of this DeviceProfile.  # noqa: E501

        :return: The profile_data of this DeviceProfile.  # noqa: E501
        :rtype: DeviceProfileData
        """
        return self._profile_data

    @profile_data.setter
    def profile_data(self, profile_data):
        """Sets the profile_data of this DeviceProfile.

        :param profile_data: The profile_data of this DeviceProfile.  # noqa: E501
        :type: DeviceProfileData
        """

        self._profile_data = profile_data

    @property
    def provision_device_key(self):
        """Gets the provision_device_key of this DeviceProfile.  # noqa: E501

        :return: The provision_device_key of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._provision_device_key

    @provision_device_key.setter
    def provision_device_key(self, provision_device_key):
        """Sets the provision_device_key of this DeviceProfile.

        :param provision_device_key: The provision_device_key of this DeviceProfile.  # noqa: E501
        :type: str
        """

        self._provision_device_key = provision_device_key

    @property
    def provision_type(self):
        """Gets the provision_type of this DeviceProfile.  # noqa: E501

        :return: The provision_type of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._provision_type

    @provision_type.setter
    def provision_type(self, provision_type):
        """Sets the provision_type of this DeviceProfile.

        :param provision_type: The provision_type of this DeviceProfile.  # noqa: E501
        :type: str
        """
        allowed_values = ["DISABLED", "ALLOW_CREATE_NEW_DEVICES", "CHECK_PRE_PROVISIONED_DEVICES"]  # noqa: E501
        if provision_type not in allowed_values:
            raise ValueError(
                "Invalid value for `provision_type` ({0}), must be one of {1}"  # noqa: E501
                .format(provision_type, allowed_values)
            )

        self._provision_type = provision_type

    @property
    def software_id(self):
        """Gets the software_id of this DeviceProfile.  # noqa: E501

        :return: The software_id of this DeviceProfile.  # noqa: E501
        :rtype: OtaPackageId
        """
        return self._software_id

    @software_id.setter
    def software_id(self, software_id):
        """Sets the software_id of this DeviceProfile.

        :param software_id: The software_id of this DeviceProfile.  # noqa: E501
        :type: OtaPackageId
        """

        self._software_id = software_id

    @property
    def tenant_id(self):
        """Gets the tenant_id of this DeviceProfile.  # noqa: E501

        :return: The tenant_id of this DeviceProfile.  # noqa: E501
        :rtype: TenantId
        """
        return self._tenant_id

    @tenant_id.setter
    def tenant_id(self, tenant_id):
        """Sets the tenant_id of this DeviceProfile.

        :param tenant_id: The tenant_id of this DeviceProfile.  # noqa: E501
        :type: TenantId
        """

        self._tenant_id = tenant_id

    @property
    def transport_type(self):
        """Gets the transport_type of this DeviceProfile.  # noqa: E501

        :return: The transport_type of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._transport_type

    @transport_type.setter
    def transport_type(self, transport_type):
        """Sets the transport_type of this DeviceProfile.

        :param transport_type: The transport_type of this DeviceProfile.  # noqa: E501
        :type: str
        """
        allowed_values = ["DEFAULT", "MQTT", "COAP", "LWM2M", "SNMP"]  # noqa: E501
        if transport_type not in allowed_values:
            raise ValueError(
                "Invalid value for `transport_type` ({0}), must be one of {1}"  # noqa: E501
                .format(transport_type, allowed_values)
            )

        self._transport_type = transport_type

    @property
    def type(self):
        """Gets the type of this DeviceProfile.  # noqa: E501

        :return: The type of this DeviceProfile.  # noqa: E501
        :rtype: str
        """
        return self._type

    @type.setter
    def type(self, type):
        """Sets the type of this DeviceProfile.

        :param type: The type of this DeviceProfile.  # noqa: E501
        :type: str
        """
        allowed_values = ["DEFAULT"]  # noqa: E501
        if type not in allowed_values:
            raise ValueError(
                "Invalid value for `type` ({0}), must be one of {1}"  # noqa: E501
                .format(type, allowed_values)
            )

        self._type = type

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.swagger_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        if issubclass(DeviceProfile, dict):
            for key, value in self.items():
                result[key] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, DeviceProfile):
            return False

        return self.__dict__ == other.__dict__

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        return not self == other


import unittest
from man import Man, LampNotWorkingError
from work_lamp import WorkLamp
from counter_wrapper import CounterWrapper
from broken_lamp import BrokenLamp

class TestMan(unittest.TestCase):

    def test_create(self):
        man = Man(1)
        self.assertIsNotNone(man)

    def test_light_on(self):
        man = Man(1)

        lamp = WorkLamp()
        self.assertFalse(lamp.is_lighted())

        # light on
        man.light_on(lamp)
        self.assertTrue(lamp.is_lighted())

        # already lighted
        man.light_on(lamp)
        self.assertTrue(lamp.is_lighted())

    def test_already_lighted(self):
        man = Man(1)

        lamp = WorkLamp()
        lamp.switch()
        self.assertTrue(lamp.is_lighted())

        man.light_on(lamp)
        self.assertTrue(lamp.is_lighted())

    def test_impatient(self):
        man = Man(0)

        lamp = CounterWrapper(BrokenLamp(10))

        # only 1 attempt
        with self.assertRaises(LampNotWorkingError):
            man.light_on(lamp)

        self.assertEqual(1, lamp.count())

    def test_patient(self):
        man = Man(5)
        lamp = CounterWrapper(BrokenLamp(10))

        # trying
        with self.assertRaises(LampNotWorkingError):
            man.light_on(lamp)

        self.assertEqual(6, lamp.count())

    def test_lucky(self):
        man = Man(5)
        lamp = CounterWrapper(BrokenLamp(3))
        man.light_on(lamp)
        self.assertEqual(3, lamp.count())


import numpy as np
import streamlit as st
from PIL import Image# to read & resize the image
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.applications.xception import preprocess_input

#Classes to predict
classes = [
    'dress',
    'hat',
    'longsleeve',
    'outwear',
    'pants',
    'shirt',
    'shoes',
    'shorts',
    'skirt',
    't-shirt'
]

#loading the model
model = keras.models.load_model("xception_v5_1_10_0.889.h5")

def main():
    st.title("Predicting Clothing Types Project")
    uploaded_file = st.file_uploader("Upload a picture to predict its class", type=['jpg', 'jpeg', 'png'])
    if uploaded_file is not None:
        st.title("Here is the image you've uploded")
        image = Image.open(uploaded_file)
        st.image(image)
        if st.button("Predict Class"):
            result=predict_class(image)
            st.write(result)
        #st.success(result)

def predict_class(image):
    #preprocessing the test picture
    #image sizing
    test_image = image.resize((299,299))
    image_array = np.asarray(test_image)
    X = np.array([image_array])#because the next function expects a list.
    X = preprocess_input(X)

    #predicting
    pred = model.predict(X)
    pre_result = dict(zip(classes, pred[0]))
    max_key = max(pre_result, key=pre_result.get)
    result = "your picture contains {} ".format(max_key)
    return (result)

if __name__=='__main__':
    main()


# Complexity:
# Time: O(N+M): Let N and M be length of list1 and list2
# Space: O(1)

# Definition for singly-linked list.
from typing import Optional

class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        start = list3 = ListNode(0)
        while list1 is not None and list2 is not None:
            if list1.val < list2.val:
                list3.next = list1
                list1 = list1.next
            else:
                list3.next = list2
                list2 = list2.next
            list3 = list3.next
        list3.next = list1 or list2
        return start.next

l1 = ListNode()
l2 = ListNode()

solve = Solution()
print(solve.mergeTwoLists(l1, l2))

# Your input
# [1,2,4] & [1,3,4]
# Output
# [1,1,2,3,4,4]


import requests
import json

class OpenAIClient:
    def __init__(self, api_key: str, model: str, temperature: float = 0.7):
        self.api_key = api_key
        self.model = model
        self.temperature = temperature

    def generate_chat_completion(self, prompt: str) -> str:

        endpoint = "https://api.openai.com/v1/chat/completions"
        headers = {
            "Content-Type": "application/json",
            "Authorization": f"Bearer {self.api_key}"
        }

        payload = {
            "messages": [{"role": "user", "content": prompt}],
            "model": self.model,
            "temperature": self.temperature
        }

        response = requests.post(endpoint, headers=headers, data=json.dumps(payload))

        if response.status_code == 200:
            data = response.json()
            return data['choices'][0]['message']['content']
        else:
            print(response)
            print(response.json())
            return "Error occurred while generating chat completion."


import cv2
import matplotlib.pyplot as plt
import numpy as np
model = cv2.dnn.readNetFromTensorflow('model/frozen_inference_graph.pb', 'model/ssd_mobilenet_v2_coco_2018_03_29.pbtxt')

# load the COCO class names
with open('model/object_detection_classes_coco.txt', 'r') as f:
    class_names = f.read().split('\n')
cap = cv2.VideoCapture(0)

while True:
    COLORS = np.random.uniform(0, 255, size=(len(class_names), 3))

    ret , image = cap.read()
    if not ret :
        break
    image_height, image_width, _ = image.shape

    model.setInput(cv2.dnn.blobFromImage(image, size=(300, 300), swapRB=True, crop=False))
    output = model.forward()

    for detection in output[0,0,:,:]:
        score = float(detection[2])
        if score > 0.6:
            class_id = detection[1]
            class_name = class_names[int(class_id)-1]
            color = COLORS[int(class_id)]

            left = detection[3] * image_width
            top = detection[4] * image_height
            right = detection[5] * image_width
            bottom = detection[6] * image_height

            cv2.rectangle(image, (int(left), int(top)), (int(right), int(bottom)), color, thickness=2)
            cv2.putText(image, class_name, (int(left), int(top - 5)), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)
            print(class_name, round(score*100,2),"%")
    cv2.imshow('image',image)
    if cv2.waitKey(1) & 0xFF == 27:
        break
cv2.destroyAllWindows()