#!/usr/bin/env python

import sys
import os
import os.path
import socket
import re
import Cfg
import helpers

NdaDirectory = None
if 'NDA_TOP' in os.environ:
    NdaDirectory = os.environ['NDA_TOP']
if 'PDKMASTER_TOP' in os.environ:
    PdkMasterTop = os.environ['PDKMASTER_TOP']
    NdaDirectory = PdkMasterTop + '/libs.tech/coriolis/techno'
if not NdaDirectory:
    hostname = socket.gethostname()
    if hostname.startswith('lepka'):
        NdaDirectory = '/dsk/l1/jpc/crypted/soc/techno'
        if not os.path.isdir(NdaDirectory):
            print ('[ERROR] You forgot to mount the NDA '
                   'encrypted directory, stupid!')
    else:
        NdaDirectory = '/users/soft/techno/techno'
helpers.setNdaTopDir( NdaDirectory )

import Cfg
from   Hurricane import Breakpoint, DbU, Library, Net, NetExternalComponents, \
                        Vertical, Pad
import CRL
from   CRL               import AllianceFramework, RoutingLayerGauge
from   Anabatic          import StyleFlags
from   helpers           import overlay, l, u, n
from   node800.helvellyn import techno
from   plugins.alpha.block.block         import Block
from   plugins.alpha.block.configuration import IoPin, GaugeConf
from   plugins.alpha.block.spares        import Spares
from   plugins.alpha.chip.configuration  import ChipConf
from   plugins.alpha.chip.chip           import Chip

#techno.setup()

import Unicorn
import Etesian
import Anabatic
import Katana

af = AllianceFramework.get()

def loadGdsLib ():
    gdsLib = af.getLibrary( 0 )
    print( '  o  Loading GDS library in "{}".'.format( gdsLib.getName() ))
    CRL.Gds.load( gdsLib
                , NdaDirectory + '/PragmatIC/Helvellyn_V1.2.0/gds/std_cells_1.2.gds'
                , CRL.Gds.NoGdsPrefix|CRL.Gds.Layer_0_IsBoundary )
    af.wrapLibrary( gdsLib, 1 )
    hpitch       = 0
    gaugeName    = Cfg.getParamString('anabatic.routingGauge').asString()
    routingGauge = af.getRoutingGauge( gaugeName )
    for layerGauge in routingGauge.getLayerGauges():
        if layerGauge.getType() == RoutingLayerGauge.PinOnly:
            continue
        if layerGauge.getDirection() == RoutingLayerGauge.Horizontal:
            hpitch = layerGauge.getPitch()
            break
    print( '  o  Skrinking V-AB of {}'.format(DbU.getValueString( hpitch )))
    with overlay.UpdateSession():
        for cell in gdsLib.getCells():
            ab = cell.getAbutmentBox()
            if ab.getHeight() < 10*hpitch:
                continue
            ab.inflate( 0, -hpitch )
            cell.setAbutmentBox( ab )
            cell.setTerminalNetlist( True )
            for net in cell.getNets():
                if not net.isExternal():
                    continue
                if net.isPower() or net.getName() == 'vdd!':
                    net.setName( 'pvdd' )
                    net.setType( Net.Type.POWER )
                    net.setGlobal( True )
                    net.setDirection( Net.Direction.IN )
                    continue
                if net.isGround() or net.getName() == 'gnd!':
                    net.setName( 'pvss' )
                    net.setType( Net.Type.GROUND )
                    net.setGlobal( True )
                    net.setDirection( Net.Direction.IN )
                    continue
                if    net.getName() == 'Y' \
                   or net.getName() == 'Q' \
                   or net.getName() == 'Qb':
                    net.setDirection( Net.Direction.OUT )
                else:
                    net.setDirection( Net.Direction.IN )
                toDestroy = []
                for component in NetExternalComponents.get(net):
                    if isinstance(component,Pad):
                        bb  = component.getBoundingBox()
                        pad = Vertical.create( net
                                             , component.getLayer()
                                             , bb.getCenter().getX()
                                             , bb.getWidth()
                                             , bb.getYMin()
                                             , bb.getYMax() )
                        NetExternalComponents.setExternal( pad )
                        toDestroy.append( component )
                for component in toDestroy:
                    component.destroy()
    return gdsLib

def loadLefLib ():
    lefLib = CRL.LefImport.load( NdaDirectory + '/PragmatIC/Helvellyn_V1.2.0/lef_astd/Hei_V1.2.0_tech.lef' )
    lefLib = CRL.LefImport.load( NdaDirectory + '/PragmatIC/Helvellyn_V1.2.0/lef_astd/lib_astd.lef' )
    af.wrapLibrary( lefLib, 1 )
    return lefLib

def scriptMain ( **kw ):
    """The mandatory function to be called by Coriolis CGT/Unicorn."""
    Breakpoint.setStopLevel( 99 )
   #helpers.setTraceLevel( 550 )
    with overlay.CfgCache(priority=Cfg.Parameter.Priority.UserFile) as cfg:
        cfg.misc.catchCore            = False
        cfg.misc.minTraceLevel        = 14500
        cfg.misc.maxTraceLevel        = 15000
        cfg.misc.info                 = False
        cfg.misc.paranoid             = False
        cfg.misc.bug                  = False
        cfg.misc.logMode              = True
        cfg.misc.verboseLevel1        = True
        cfg.misc.verboseLevel2        = True
        cfg.etesian.graphics          = 2
        cfg.etesian.densityVariation  = 0.05
        cfg.etesian.effort            = 2
        cfg.etesian.bloat             = 'channel'
       #cfg.etesian.aspectRatio       = 2.2
        cfg.etesian.aspectRatio       = 1.0
        cfg.etesian.spaceMargin       = 0.20
        cfg.anabatic.netBuilderStyle  = 'VH,2RL'
        cfg.anabatic.routingStyle     = StyleFlags.VH
       #cfg.anabatic.topRoutingLayer  = 'mt2'
        cfg.katana.eventsLimit        = 4000000
        cfg.katana.hTracksReservedMin = 5
        cfg.katana.vTracksReservedMin = 5
       #lg5 = af.getRoutingGauge('StdCellLib').getLayerGauge( 5 )
       #lg5.setType( RoutingLayerGauge.PowerSupply )
        env = af.getEnvironment()
        env.setCLOCK( '^sys_clk$|^ck|^jtag_tck$' )

    hscaling  = 4
    vscaling  = 4
    coreSizeX = 220
    coreSizeY = 220
    rg = af.getRoutingGauge( 'StdCellLib' )
    cg = af.getCellGauge   ( 'LEF.CoreSite' )
    vpitch = rg.getLayerGauge( 1 ).getPitch()
    hpitch = rg.getLayerGauge( 0 ).getPitch()
    sliceHeight = cg.getSliceHeight()

    def hp ( v ): return v*hpitch*hscaling
    def vp ( v ): return v*vpitch*vscaling
    def sh ( v ): return v*sliceHeight

    useLEF = False
    editor = None
    if 'editor' in kw and kw['editor']:
        editor = kw[ 'editor' ]

    if useLEF:
        lefLib = loadLefLib()
        CRL.Blif.add( lefLib )
    else:
        gdsLib = loadGdsLib()
        CRL.Blif.add( gdsLib )
    Breakpoint.stop( 100, '{} library loaded.'.format( 'LEF' if useLEF else 'GDS' ))
   #OR2x1  = gdsLib.getCell( 'OR2x1' )
   #if editor: editor.setCell( OR2x1 )

    cell = CRL.Blif.load( 'ao68000' )
    if editor: editor.setCell( cell )
    Breakpoint.stop( 100, 'BLIF netlist loaded' )
    try:
        ioPadsSpec = [ ]
        ioPinsSpec = [ (IoPin.WEST |IoPin.A_BEGIN, 'ACK_I'    , vp( 10),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'CLK_I'    , vp( 20),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'ERR_I'    , vp( 30),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'reset_n'  , vp( 40),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'RTY_I'    , vp( 50),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'BLK_O'    , vp( 60),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'blocked_o', vp( 70),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'CYC_O'    , vp( 80),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'reset_o'  , vp( 90),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'RMW_O'    , vp(100),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'sgl_o'    , vp(110),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'STB_O'    , vp(120),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'WE_O'     , vp(130),     0 ,  1)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'ipl_i({})', vp(140), vp(10),  3)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'BTE_O({})', vp(170), vp(10),  2)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'CTI_O({})', vp(190), vp(10),  3)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'fc_o({})' , vp(220), vp(10),  3)
                     , (IoPin.WEST |IoPin.A_BEGIN, 'SEL_O({})', vp(250), vp(10),  4)
                     , (IoPin.SOUTH|IoPin.A_BEGIN, 'DAT_I({})', vp( 10), vp(10), 32)
                     , (IoPin.EAST |IoPin.A_BEGIN, 'ADR_O({})', vp( 10), vp(10), range(2,32))
                     , (IoPin.NORTH|IoPin.A_BEGIN, 'DAT_O({})', vp( 10), vp(10), 32)
                     ]
        conf = ChipConf( cell, ioPins=ioPinsSpec, ioPads=ioPadsSpec )
        conf.cfg.etesian.bloat               = 'channel'
        conf.cfg.etesian.densityVariation    = 0.05
        conf.cfg.etesian.aspectRatio         = 1.0
       # etesian.spaceMargin is ignored if the coreSize is directly set.
        conf.cfg.etesian.spaceMargin         = 0.02
        conf.cfg.anabatic.searchHalo         = 2
        conf.cfg.anabatic.globalIterations   = 30
        conf.cfg.anabatic.netBuilderStyle    = 'VH,2RL'
        conf.cfg.anabatic.routingStyle       = StyleFlags.VH
        conf.cfg.katana.hTracksReservedLocal = 7
        conf.cfg.katana.vTracksReservedLocal = 7
        conf.cfg.katana.hTracksReservedMin   = 3
        conf.cfg.katana.vTracksReservedMin   = 4
        conf.cfg.katana.trackFill            = 0
        conf.cfg.katana.runRealignStage      = True
        conf.cfg.katana.dumpMeasures         = False
        conf.cfg.block.spareSide             = sh(7)
       #conf.cfg.chip.minPadSpacing          = u(1.46)
       #conf.cfg.chip.supplyRailWidth        = u(20.0)
       #conf.cfg.chip.supplyRailPitch        = u(40.0)
        conf.editor              = editor
        conf.useSpares           = False
        conf.useClockTree        = False
        conf.useHFNS             = False
        conf.bColumns            = 2
        conf.bRows               = 2
        conf.chipName            = 'chip'
        conf.coreSize            = ( sh(coreSizeX), sh(coreSizeY) )
        conf.chipSize            = ( u(  2020.0), u(  2060.0) )
       #conf.useHTree( 'clk', Spares.HEAVY_LEAF_LOAD )
       #conf.useHTree( 'reset' )
        blockBuilder = Block( conf )
        rvalue = blockBuilder.doPnR()
        blockBuilder.save()
    except Exception as e:
        helpers.io.catch( e )
        rvalue = False
    return cell


'''
-Hard-

*DP*

Given an array A (index starts at 1) consisting of N integers: A1, A2, ..., AN and an integer B.
The integer B denotes that from any place (suppose the index is i) in the array A, you can jump to
any one of the place in the array A indexed i+1, i+2, …, i+B if this place can be jumped to. Also,
if you step on the index i, you have to pay Ai coins. If Ai is -1, it means you can’t jump to the
place indexed i in the array.

Now, you start from the place indexed 1 in the array A, and your aim is to reach the place indexed
N using the minimum coins. You need to return the path of indexes (starting from 1 to N) in the
array you should take to get to the place indexed N using minimum coins.

If there are multiple paths with the same cost, return the lexicographically smallest such path.

If it's not possible to reach the place indexed N then you need to return an empty array.

Example 1:

Input: [1,2,4,-1,2], 2
Output: [1,3,5]

Example 2:

Input: [1,2,4,-1,2], 1
Output: []

Note:

Path Pa1, Pa2, ..., Pan is lexicographically smaller than Pb1, Pb2, ..., Pbm, if and only if
at the first i where Pai and Pbi differ, Pai < Pbi; when no such i exists, then n < m.
A1 >= 0. A2, ..., AN (if exist) will in the range of [-1, 100].
Length of A is in the range of [1, 1000].
B is in the range of [1, 100].

'''

class Solution:
    """
    @param A: a list of integer
    @param B: an integer
    @return: return a list of integer
    """
    def cheapestJump(self, A, B):
        # write your code here
        if A[-1] == -1: return []
        n = len(A)
        res, pos, dp = [], [-1]*n, [float('inf')]*n
        dp[-1] = A[-1]
        for i in range(n-2, -1, -1): # jump from back to front
            if A[i] == -1: continue # can not jump to this position
            for j in range(i+1, min(i+B+1, n)):
                if dp[j] == float('inf'): continue # can not jump from j to i
                if dp[i] > dp[j]+A[i]:
                   dp[i] = dp[j]+A[i] # min coins jumping from end to i
                   pos[i] = j
        if dp[0] == float('inf'): return []
        cur = 0
        while cur != -1:
            res.append(cur+1)
            cur = pos[cur]
        return res

if __name__ == "__main__":
    print(Solution().cheapestJump([1,2,4,-1,2], 2))


# Author:Stew
# Date:12/18/2020
# Description: This contains a class called minimap that creates a minimap

import pygame as pg
from stew_work import *
from main import *
from settings import *

minimap_size = 144

class Minimap(pg.sprite.Sprite):

    def __init__(self, game, x, y):
        self.num_blocks = dungeon.depth
        self.groups = game.all_sprites, game.minimap
        pg.sprite.Sprite.__init__(self, self.groups, Dungeon(14))
        self.x_cor = WIDTH - minimap_size
        self.y_cor = 0
        self.rectangle = pg.Rect(self.x_cor, self.y_cor, minimap_size, minimap_size)
        self.found_rooms = [(dungeon.get_start_room()[0], dungeon.get_start_room()[1])]
        self.color = BLUE

    def draw(self, surface):
        pg.draw.rect(surface,self.color,self.rectangle)


# -*- coding: utf-8 -*-

# Widget para mostrar una columna estándar en Turpial
#
# Author: Wil Alvarez (aka Satanas)
# Jun 25, 2010

import gtk
import logging

from turpial.ui import util as util
from turpial.ui.gtk.errorbox import ErrorBox
from turpial.ui.gtk.statuslist import StatusList
from turpial.ui.gtk.waiting import CairoWaiting

log = logging.getLogger('Gtk:Column')

class GenericColumn(gtk.VBox):
    def __init__(self, mainwin, label=''):
        gtk.VBox.__init__(self, False)

        self.mainwin = mainwin
        self.statuslist = StatusList(mainwin)
        self.waiting = CairoWaiting(mainwin)
        self.walign = gtk.Alignment(xalign=1, yalign=0.5)
        self.walign.add(self.waiting)
        self.errorbox = ErrorBox()
        self.label = gtk.Label(label)
        self.caption = label

        self.connect('expose-event', self.error_show)

    def error_show(self, widget, event):
        self.errorbox.show()

    def update_tweets(self, response):
        count = 0
        if response.type == 'error':
            self.stop_update(True, response.errmsg)
        else:
            statuses = response.items
            if len(statuses) == 0:
                self.statuslist.clear()
                self.stop_update(True, _('No tweets available'))
            else:
                count = self.statuslist.update(statuses)
                self.stop_update()
        self.on_update()
        return count

    def update_user_pic(self, user, pic):
        self.statuslist.update_user_pic(user, pic)

    def update_wrap(self, width):
        self.statuslist.update_wrap(width)

    def start_update(self):
        self.waiting.start()
        self.errorbox.hide()

    def stop_update(self, error=False, msg=''):
        self.waiting.stop(error)
        self.errorbox.show_error(msg, error)

    def clear(self):
        self.statuslist.clear()

    def on_update(self, data=None):
        pass

class StandardColumn(GenericColumn):
    def __init__(self, mainwin, label='', pos=None, viewed=None):
        GenericColumn.__init__(self, mainwin, label)

        self.pos = pos
        self.handler = None
        self.changing_col = False

        model = gtk.ListStore(str, str)
        cell = gtk.CellRendererText()
        self.listcombo = gtk.ComboBox()
        self.listcombo.pack_start(cell, True)
        self.listcombo.add_attribute(cell, 'text', 1)
        self.listcombo.set_model(model)

        self.refresh = gtk.Button()
        self.refresh.set_image(self.mainwin.load_image('action-refresh.png'))
        self.refresh.set_tooltip_text(_('Manual Update'))

        self.mark_all = gtk.Button()
        self.mark_all.set_image(self.mainwin.load_image('action-mark-all.png'))
        self.mark_all.set_tooltip_text(_('Mark all as read'))

        listsbox = gtk.HBox(False)
        listsbox.pack_start(self.mark_all, False, False)
        listsbox.pack_start(self.listcombo, True, True)
        listsbox.pack_start(self.refresh, False, False)
        listsbox.pack_start(self.walign, False, False, 2)

        self.pack_start(listsbox, False, False)
        self.pack_start(self.errorbox, False, False)
        self.pack_start(self.statuslist, True, True)

        self.refresh.connect('clicked', self.__manual_update)
        self.mark_all.connect('clicked', self.__mark_all_as_read)

    def __manual_update(self, widget):
        self.mainwin.manual_update(self.pos)

    def __mark_all_as_read(self, widget):
        self.statuslist.mark_all_as_read()

    def __change_list(self, widget):
        model = self.listcombo.get_model()
        iter = self.listcombo.get_active_iter()
        new_id = model.get_value(iter, 0)
        self.caption = model.get_value(iter, 1)
        self.changing_col = True
        self.label.set_label(self.caption)
        try:
            self.get_parent().set_tab_label(self, self.label)
        except:
            pass
        self.mainwin.request_change_column(self.pos, new_id)

    def fill_combo(self, columns, new_viewed):
        self.viewed = new_viewed[self.pos]

        i = 0
        default = -1
        model = self.listcombo.get_model()
        fixed = ['timeline', 'replies', 'directs','sent']
        for key in fixed:
            model.append([key, columns[key].title])
            if key == self.viewed.id:
                default = i
            i += 1

        for key in sorted(columns.iterkeys()):
            if key in fixed:
                continue
            model.append([key, columns[key].title])
            if key == self.viewed.id:
                default = i
            i += 1

        self.last_index = default
        self.listcombo.set_model(model)
        self.listcombo.set_active(self.last_index)
        iter = self.listcombo.get_active_iter()
        self.caption = model.get_value(iter, 1)
        self.label = gtk.Label(self.caption)
        self.handler = self.listcombo.connect('changed', self.__change_list)

    def set_combo_item(self, reset=False):
        self.listcombo.disconnect(self.handler)
        if reset:
            self.listcombo.set_active(self.last_index)
        else:
            self.last_index = self.listcombo.get_active()

            if self.changing_col:
                model = self.listcombo.get_model()
                iter = self.listcombo.get_active_iter()
                new_id = model.get_value(iter, 0)

                new_config = {'Columns': {}}
                column = 'column%i' % (self.pos + 1)
                new_config['Columns'][column] = new_id
                self.mainwin.save_config(new_config)

        self.changing_col = False
        self.handler = self.listcombo.connect('changed', self.__change_list)

    def start_update(self):
        self.waiting.start()
        self.errorbox.hide()
        self.refresh.set_sensitive(False)
        self.listcombo.set_sensitive(False)
        self.mark_all.set_sensitive(False)

    def stop_update(self, error=False, msg=''):
        if error:
            self.set_combo_item(True)
        else:
            self.set_combo_item()
        self.waiting.stop(error)
        self.errorbox.show_error(msg, error)
        self.refresh.set_sensitive(True)
        self.listcombo.set_sensitive(True)
        self.mark_all.set_sensitive(True)

class SingleColumn(GenericColumn):
    def __init__(self, mainwin, label=''):
        GenericColumn.__init__(self, mainwin, label)

        #self.errorbox = gtk.HBox(False)
        #self.errorbox.pack_start(self.lblerror, False, False, 2)
        #self.errorbox.pack_start(self.walign, False, False, 2)

        self.pack_start(self.errorbox, False, False)
        self.pack_start(self.statuslist, True, True)

class SearchColumn(GenericColumn):
    def __init__(self, mainwin, label=''):
        GenericColumn.__init__(self, mainwin, label)

        self.input_topics = gtk.Entry()
        self.clearbtn = gtk.Button()
        self.clearbtn.set_image(self.mainwin.load_image('action-clear.png'))
        self.clearbtn.set_tooltip_text(_('Clear results'))
        #self.clearbtn.set_relief(gtk.RELIEF_NONE)
        try:
            #self.input_topics.set_property("primary-icon-stock",
            #                               gtk.STOCK_FIND)
            self.input_topics.set_property("secondary-icon-stock",
                                           gtk.STOCK_FIND)
            self.input_topics.connect("icon-press", self.__on_icon_press)
        except:
            pass

        inputbox = gtk.HBox(False)
        inputbox.pack_start(self.input_topics, True, True)
        inputbox.pack_start(self.clearbtn, False, False)
        inputbox.pack_start(self.walign, False, False, 2)

        self.pack_start(inputbox, False, False)
        self.pack_start(self.errorbox, False, False)
        self.pack_start(self.statuslist, True, True)

        self.clearbtn.connect('clicked', self.__clear)
        self.input_topics.connect('activate', self.__search_topic)
        self.input_topics.grab_focus()

    def __on_icon_press(self, widget, pos, e):
        #if pos == 0:
        #    self.__search_topic(widget)
        if pos == 1:
            #widget.set_text('')
            self.__search_topic(widget)

    def __clear(self, widget):
        self.statuslist.clear()
        self.input_topics.grab_focus()

    def __search_topic(self, widget):
        topic = widget.get_text()
        if topic != '':
            self.lock()
            self.mainwin.request_search(topic)
            widget.set_text('')
        else:
            widget.set_text(_('You must write something to search'))
            widget.grab_focus()

    def on_update(self, data=None):
        self.unlock()

    def lock(self):
        self.input_topics.set_sensitive(False)
        self.clearbtn.set_sensitive(False)

    def unlock(self):
        self.input_topics.set_sensitive(True)
        self.clearbtn.set_sensitive(True)


from rl_q_learning_scratch import Q_Learning
import numpy as np

_size = 10
_item_start = (0, 0)
_start_position = (0, 9)
_item_drop_off = (9, 9)

train_q = Q_Learning(_size, _item_start, _start_position, _item_drop_off, True)

# train_q.train_q_learning()

q_table = np.load("C:/Users/sesle/Desktop/Workspace/ReinforcementLearning/Github/Project-2/q_table_500bin.npy")  # loading q_table which is trained before

train_q.evaluate_rl(q_table, True, True)
train_q.evaluate_rl(q_table, True, True)
train_q.evaluate_rl(q_table, True, True)


import re

import setuptools

# from .src.pyaltium import __version__

with open("src/pyaltium/__init__.py") as f:
    txt = f.read()
    r = re.search(r'__version__\s+=\s+"(.*)"', txt)
    __version__ = r.group(1)

with open("README.md", "r", encoding="utf-8") as f:
    long_description = f.read()

setuptools.setup(
    name="PyAltium",
    version=__version__,
    author="Trevor Gross",
    author_email="t.gross35@gmail.com",
    description="A package for reading Altium files",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/pluots/PyAltium",
    project_urls={
        "Bug Tracker": "https://github.com/pluots/PyAltium/issues",
    },
    packages=setuptools.find_packages(where="src"),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    package_dir={"": "src"},
    python_requires=">=3.7",
)


# 200222 13:34
# 데이터 사이언스
# DataFrame 인덱싱
# 10. 방송사 시청률 받아오기 6

import pandas as pd

df = pd.read_csv(r'C:\Users\hayong\Downloads\broadcast.csv', index_col=0)

boolean_df = df['SBS'] < df['TV CHOSUN']
print(df.loc[boolean_df, ['SBS', 'TV CHOSUN']])

# 아이구 잘한다~!
# 찾아서 해내기
# 반복을 통한 숙달
# 이후에는 암기가 자동으로 되어
# 응용, 활용


from LinkedList1 import *

linkedList=LinkedList()
while True:
    print("Single Linked List Menu:")
    print("1. Insert at beginning")
    print("2. Insert at end")
    print("3. Insert at required position")
    print("4. Display")
    print("5.Delete")
    print("6. Exit")
    print("7.To get the size of the linked list")
    n=int(input("Select any one of the option:"))
    if n==1:
        linkedList.insertStart(int(input("Enter the element you want to insert:")))
    elif n==2:
        linkedList.insertEnd(int(input("Enter the element you want to insert:")))
    elif n==3:
        linkedList.insertAtPosition(int(input("Enter the element you want to insert:")),int(input("Enter the position you want to insert:")))
    elif n==4:
        linkedList.traverseList()
    elif n==5:
        linkedList.remove(int(input("Enter the element you want to delete:")))
    elif n==6:
        break
    elif n==7:
        print("The Size of the linked list is {}".format(linkedList.counter))


'''
-Medium-
*Recursion*
*Bit Manipulation*

We build a table of n rows (1-indexed). We start by writing 0 in the 1st row. Now in every
subsequent row, we look at the previous row and replace each occurrence of 0 with 01, and
each occurrence of 1 with 10.

For example, for n = 3, the 1st row is 0, the 2nd row is 01, and the 3rd row is 0110.
Given two integer n and k, return the kth (1-indexed) symbol in the nth row of a table of n rows.

Example 1:

Input: n = 1, k = 1
Output: 0
Explanation: row 1: 0
Example 2:

Input: n = 2, k = 1
Output: 0
Explanation:
row 1: 0
row 2: 01
Example 3:

Input: n = 2, k = 2
Output: 1
Explanation:
row 1: 0
row 2: 01
Example 4:

Input: n = 3, k = 1
Output: 0
Explanation:
row 1: 0
row 2: 01
row 3: 0110

Constraints:

1 <= n <= 30
1 <= k <= 2^(n - 1)

'''

class Solution(object):
    def kthGrammarTLE(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: int
        """
        def helper(i):
            if i == 1: return "0"
            s = helper(i-1)
            t = ''
            for c in s:
                if c == '0': t +='01'
                else: t += '10'
            print(t)
            return t
        s = helper(n)
        return int(s[k-1])

    def kthGrammar(self, n, k):
        """
        :type n: int
        :type k: int
        :rtype: int
        """
        if n == 1: return 0
        if n == 2:
            if k == 1: return 0
            if k == 2: return 1
        d1, d2 = 1 << (n-2), 1 << (n-3)
        if k <= d1:
            return self.kthGrammar(n-1, k)
        elif k <= d1 + d2:
            return self.kthGrammar(n-1, k-d1+d2)
        else:
            return self.kthGrammar(n-1, k-d1-d2)

if __name__ == "__main__":
    print(Solution().kthGrammarTLE(5, 4))
    print(Solution().kthGrammar(5, 4))
    print(Solution().kthGrammar(30, 434991989))


#!/usr/bin/env python3

from multiprocessing import Process, Queue
import socks
import socket
import subprocess
import requests

x = open("/home/kaisok/Documentos/Python/Onion/ListaPrueba", "r", encoding="latin-1")
url = x.readlines()
x.close()
subprocess.run("clear")

puertosAbiertos = []

def torrente(min, max):

    for i in url:
        nombre = i.strip("\n")
        i = i.split(" ")[1].strip("\n")

        for puerto in range(min, max):
            print("\nProbando puerto {}".format(puerto))

            try:

                socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
                s = socks.socksocket()
                s.settimeout(2)
                address = (i, puerto)
                s.connect(address)

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

                q.put(puerto)

                s.close()

            except:

                print("casi")

ListaPuertos=[1000, 1501, 2001, 2501, 3001]
if __name__ == "__main__":

    procs = []
    q = Queue()
    for i in range(4):
        proc = Process(target=torrente, args=(ListaPuertos[i],ListaPuertos[i+1]))
        procs.append(proc)

    for proc in procs:
        proc.start()

    for proc in procs:
        proc.join()

while not q.empty():
    puertosAbiertos.append(q.get())

print(puertosAbiertos)

for i in url:
    nombre = i.strip("\n")
    i = i.split(" ")[1].strip("\n")

    for puerto in puertosAbiertos:

        try:
            socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050, True)
            s = socks.socksocket()
            s.settimeout(2)
            address = (i, puerto)
            s.connect(address)
            a = s.recv(1024).decode()
            s.close()

            if "SSH" in a:
                    print("\n#######################")
                    print("\n" + nombre)
                    print("\nEs SSH")
                    print("\n#######################")

            elif "FTP" in a:
                print("\n#######################")
                print("\n" + nombre)
                print("\nEs FTP")
                print("\n#######################")

        except:

            try:

                print("\n#######################")
                proxies = {'http': 'socks5h://127.0.0.1:9050'}
                data = requests.head("http://{}:{}".format(i, puerto),proxies=proxies).headers
                if data["Server"]:
                    print("\nHTTP SERVER: {}".format(data["Server"]))
                else:
                    print("\nHTTP SERVER")
                print("\n#######################")

            except:

                print("\n#######################")
                print("\nOTRO SERVICIO")
                print("\n#######################")


"""add status to issue

Revision ID: 6d3439e14660
Revises: 04c84d5e2a21
Create Date: 2019-03-22 07:57:32.625406

"""
from alembic import op
import sqlalchemy as sa
from pabu.tools import get_table

# revision identifiers, used by Alembic.
revision = '6d3439e14660'
down_revision = '04c84d5e2a21'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.add_column('issues', sa.Column('status', sa.String(), nullable=True))

    issues = get_table(op.get_bind(), 'issues')
    op.execute(issues.update().values(status = 'todo'))

    op.alter_column('issues', 'status', nullable=False)
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('issues', 'status')
    # ### end Alembic commands ###


#!/usr/bin/env python
# coding: utf-8
# Author: Mihir Singh

# ## import necessary packages n pass unix(source) and hadoop(destination location) as system argument 1,2

from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql import SparkSession
import sys
spark=SparkSession.builder.appName("create_json").enableHiveSupport().getOrCreate()

# ## create a list of database value

mydb=spark.sql("show databases").collect()

db=[]
for mydb in mydb:
    db.append(mydb.databaseName)

# ## the below code takes in database name -- and collect all tables inside it as dbname.table name
mytables=[]
for db in db:
    print("database in use",db)
    spark.sql("use {}".format(db))
    tables=spark.sql("show tables")
    param=tables.select(concat(col("database"),lit("."),col('tableName')).alias("tables")).collect()
    for a in param:
        print("tables",a.tables)
        mytables.append(a.tables)

# ## create dict with key as dbname-tablename and value as 'column_name|datatype'
myschemas1={}
c=0
for b in mytables:
    print(str(b).replace(".","-"))
    try:
        myschemas1[str(b).replace(".","-")]=list(spark.sql("desc {}".format(b)).select(concat(col("col_name"),lit("|"),col("data_type"))).collect())
    except:
        print("Permission error")
        break

# ## import json package to dump dict to json

import json
with open("{}/onprem.json".format(sys.argv[1]), "w") as fp:
    json.dump(myschemas1 , fp)

#with open("{}/cloud.json".format(sys.argv[1]), "w") as fp:
#    json.dump(myschemas2 , fp)

# ## comment uncomment as per environment to upload file to hdfs

# In[10]:
import os
os.system("hadoop fs -put -f {}/onprem.json {}/onprem.json".format(sys.argv[1],sys.argv[2]))
#os.system("hadoop fs -put -f {}/cloud.json {}/cloud.json".format(sys.argv[1],sys.argv[2]))


# 15-Dars
# Sana: 23.08.2021
# Ko`chiruvchi: ALEVcoder

talaba = {
    'ism': 'alijon',
    'familya': 'valiyev',
    'yosh': 17,
    'fakultet': 'informatika',
    'kurs': 2
}

# print(talaba.items())

# for kalit, qiymat  in talaba.items():
#     print(f'Kalit: {kalit.title()}')
#     print(f'Qiymat: {qiymat} \n')

telphonelar = {
    'ali': 'iphone x',
    'vali': 'redmi note 10',
    'alijon': 'redmi note 9s',
    'samandar': 'samsung s21 ultra'
}
# for k, q in telphonelar.items():
#     print(f'{k.title()}ning telephni {q.title()}')

mahsulotlar = {
    'olma' : 10000,
    'banan' : 20000,
    'anor' : 15000,
    'anjir' : 25000,
    'shaftoli' : 17000
}
# print(mahsulotlar.keys())
# print(mahsulotlar.values())

# print("Do`kondagi mahsulotlar")
# for mahsulot in mahsulotlar.keys():
#     print(mahsulot.title())

bozorliklar = {
    'anor',
    'uzum',
    'non',
    'anjir',
    'baliq'
}

# for mahsulot in mahsulotlar:
#     if mahsulot in bozorliklar:
#         print(f"{mahsulot.title()} {mahsulotlar[mahsulot]} so`m")

# for buyum in bozorliklar:
#     if buyum not in mahsulotlar:
#         print(f'Iltimos, do`konga {buyum}ni ham olib keling')

# print('Do`konimizdagi mahsulotlar: ')
# for mahsulot in sorted(mahsulotlar):
#     print(mahsulot.title())

# print(telphonelar.values())

# print('Foydalanuvchilar quyidagi telphonlarni ishlatadi:')
# for tel in telphonelar.values():
#     print(tel.title())

telphonelar = {
    'ali': 'iphone x',
    'vali': 'redmi note 10',
    'alijon': 'redmi note 9s',
    'alijon': 'redmi note 9s',
    'alijon': 'redmi note 9s',
    'samandar': 'samsung s21 ultra'
}

# print('Foydalanuvchilar quyidagi telphonlarni ishlatadi:')
# for tel in set(telphonelar.values()):
#     print(tel.title())

toys = {
    'ball',
    'car',
    'lamp',
    'ball'
}

print(toys)


import json
import structlog
import pika
import config
from multiprocessing import Process
from ServiceManager import ServiceInfo, startService

logger = structlog.get_logger()

def serviceCallback(ch, method, properties, body):
    """Take service off of the queue and start it up in a container"""

    logger.info("serviceCallback", msg="Recieved Message", body=body)
    body = json.loads(body)
    service = ServiceInfo(body)
    log = logger.bind(serviceInfo=service.__dict__)
    log.info("serviceCallback", msg="Starting Service")

    # Reassign service with new ip address
    service = startService(service)

    log.info("serviceCallback", msg="Placing Service on Attack Queue")
    connection = pika.BlockingConnection(pika.ConnectionParameters(config.RABBITMQ_SERVER))
    channel = connection.channel()
    channel.queue_declare(queue='attackQueue', durable=True)
    channel.basic_publish(exchange='',
                          routing_key='attackQueue',
                          body=json.dumps(service.__dict__))

    ch.basic_ack(delivery_tag=method.delivery_tag)
    log.info("serviceCallback", msg="serviceCallback Done")

def serviceWorker():
    """Declare service queue and callback"""
    connection = pika.BlockingConnection(pika.ConnectionParameters(config.RABBITMQ_SERVER))
    channel = connection.channel()
    channel.queue_declare(queue='serviceQueue', durable=True)
    logger.info("serviceWorker", msg="Starting Service Worker", queue="serviceQueue")
    channel.basic_consume(serviceCallback, queue='serviceQueue')
    channel.start_consuming()

def startServiceWorkers(numThreads):
    """Start numThreads service workers"""
    for i in range(numThreads):
        t = Process(target=serviceWorker)
        t.daemon = True
        t.start()


from re import S
import unittest
from datetime import datetime, timedelta
from collections import defaultdict

from classes import *

class Test(unittest.TestCase):
    def test_record_add_phone_happy_flow(self):
        john_record = Record("John")
        john_record.add_phone("1234567890")

        self.assertEqual(john_record.phones[0].get_value(), "1234567890")

    def test_record_add_phone_empty_phone(self):
        john_record = Record("John")
        john_record.add_phone("")

        self.assertEqual(len(john_record.phones), 0)

    def test_record_edit_phone_happy_flow(self):
        john_record = Record("John")
        john_record.add_phone("1234567890")
        john_record.edit_phone("1234567890", "0987654321")

        self.assertEqual(john_record.phones[0].get_value(), "0987654321")

    def test_record_edit_phone_empty_args(self):
        john_record = Record("John")
        john_record.add_phone("1234567890")
        john_record.edit_phone("", "")

        self.assertEqual(john_record.phones[0].get_value(), "1234567890")

    def test_record_find_phone(self):
        john_record = Record("John")
        john_record.add_phone("1234567890")
        happy_flow_search = john_record.find_phone("1234567890")
        wrong_phone_search = john_record.find_phone("")

        self.assertEqual(happy_flow_search.value, "1234567890")
        self.assertEqual(wrong_phone_search, None)

    def test_address_book_add_record(self):
        record_name = "John"
        book = AddressBook()
        john_record = Record(record_name)

        john_record.add_phone("1234567890")
        book.add_record(john_record)
        book.add_record({})

        self.assertEqual(
            len(book.data.values()),
            1,
        )
        self.assertEqual(
            book.data.get(record_name).get_name().get_value(),
            record_name,
        )

    def test_address_book_find_record(self):
        record_name = "Vasyl"
        book = AddressBook()
        vasyl_record = Record(record_name)

        vasyl_record.add_phone("1234567890")
        book.add_record(vasyl_record)

        search_result = book.find(record_name)
        self.assertEqual(
            len(book.data.values()),
            1,
        )
        self.assertEqual(
            search_result.get_name().get_value(),
            record_name,
        )

    def test_address_book_delete_record(self):
        vasyl_record_name = "Vasyl"
        ivan_record_name = "Ivan"
        book = AddressBook()
        vasyl_record = Record(vasyl_record_name)
        ivan_record = Record(ivan_record_name)

        vasyl_record.add_phone("1234567890")
        book.add_record(vasyl_record)
        book.add_record(ivan_record)
        book.delete(vasyl_record_name)

        search_result = book.find(ivan_record_name)
        self.assertEqual(
            len(book.data.values()),
            1,
        )
        self.assertEqual(
            search_result.get_name().get_value(),
            ivan_record_name,
        )


from app.database import SessionLocal

USERS = "users"
USER_TAGS = [USERS]
openapi_tags = [
     {"name": USERS, "description": "CRUD User endpoints"},
]

# Dependency
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

def get_hash(string: str):
    return str(string.encode())


import tensorflow as tf
from esim import args

class Graph:

    def __init__(self):
        self.p = tf.placeholder(dtype=tf.int32, shape=(None, args.seq_length), name='p')
        self.h = tf.placeholder(dtype=tf.int32, shape=(None, args.seq_length), name='h')
        self.y = tf.placeholder(dtype=tf.int32, shape=None, name='y')
        self.keep_prob = tf.placeholder(dtype=tf.float32, name='drop_rate')

        self.embedding = tf.get_variable(dtype=tf.float32, shape=(args.vocab_size, args.char_embedding_size),
                                         name='embedding')

        self.forward()

    def dropout(self, x):
        return tf.nn.dropout(x, keep_prob=self.keep_prob)

    def bilstm(self, x, hidden_size):
        fw_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_size)
        bw_cell = tf.nn.rnn_cell.BasicLSTMCell(hidden_size)

        return tf.nn.bidirectional_dynamic_rnn(fw_cell, bw_cell, x, dtype=tf.float32)

    def forward(self):
        p_embedding = tf.nn.embedding_lookup(self.embedding, self.p)
        h_embedding = tf.nn.embedding_lookup(self.embedding, self.h)

        with tf.variable_scope("lstm_p", reuse=tf.AUTO_REUSE):
            (p_f, p_b), _ = self.bilstm(p_embedding, args.embedding_hidden_size)
        with tf.variable_scope("lstm_p", reuse=tf.AUTO_REUSE):
            (h_f, h_b), _ = self.bilstm(h_embedding, args.embedding_hidden_size)

        p = tf.concat([p_f, p_b], axis=2)
        h = tf.concat([h_f, h_b], axis=2)

        p = self.dropout(p)
        h = self.dropout(h)

        e = tf.matmul(p, tf.transpose(h, perm=[0, 2, 1]))
        a_attention = tf.nn.softmax(e)
        b_attention = tf.transpose(tf.nn.softmax(tf.transpose(e, perm=[0, 2, 1])), perm=[0, 2, 1])

        a = tf.matmul(a_attention, h)
        b = tf.matmul(b_attention, p)

        m_a = tf.concat((a, p, a - p, tf.multiply(a, p)), axis=2)
        m_b = tf.concat((b, h, b - h, tf.multiply(b, h)), axis=2)

        with tf.variable_scope("lstm_a", reuse=tf.AUTO_REUSE):
            (a_f, a_b), _ = self.bilstm(m_a, args.context_hidden_size)
        with tf.variable_scope("lstm_b", reuse=tf.AUTO_REUSE):
            (b_f, b_b), _ = self.bilstm(m_b, args.context_hidden_size)

        a = tf.concat((a_f, a_b), axis=2)
        b = tf.concat((b_f, b_b), axis=2)

        a = self.dropout(a)
        b = self.dropout(b)

        a_avg = tf.reduce_mean(a, axis=2)
        b_avg = tf.reduce_mean(b, axis=2)

        a_max = tf.reduce_max(a, axis=2)
        b_max = tf.reduce_max(b, axis=2)

        v = tf.concat((a_avg, a_max, b_avg, b_max), axis=1)
        v = tf.layers.dense(v, 512, activation='tanh')
        v = self.dropout(v)
        logits = tf.layers.dense(v, 2, activation='tanh')
        self.prob = tf.nn.softmax(logits)
        self.prediction = tf.argmax(logits, axis=1)
        self.train(logits)

    def train(self, logits):
        y = tf.one_hot(self.y, args.class_size)
        loss = tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=logits)
        self.loss = tf.reduce_mean(loss)
        self.train_op = tf.train.AdamOptimizer(args.learning_rate).minimize(self.loss)
        correct_prediction = tf.equal(tf.cast(self.prediction, tf.int32), self.y)
        self.acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))


#cryptopals challenge 27
from os import urandom
from Crypto.Cipher import AES

iv = urandom(16)
s1 = b"comment1=cooking%20MCs;userdata="
s2 = b";comment2=%20like%20a%20pound%20of%20bacon"

xor = lambda b1, b2: bytes(x ^ y for x, y in zip(b1, b2))

def encrypt(plain):
    #create cipher
    cipher = AES.new(iv, AES.MODE_CBC, iv)
    #delete chars - same as c26
    string = plain.translate(str.maketrans({';': '', '=': ''}))
    string = pkcs7(string.encode('ascii'))
    return cipher.encrypt(string)

def decrypt(encrypted):
    cipher = AES.new(iv, AES.MODE_CBC, iv)
    message = cipher.decrypt(encrypted)
    return message[:-message[-1]]

#crypto message syntax
def pkcs7(string):
    pad = 16 - (len(string) % 16)
    return string + bytes(pad * [pad])

def crack_cipher(cipher):
    decrypted = decrypt(cipher)
    #all chars between 32 and 127
    return "a" if all(32<ch<127 for ch in decrypted) else decrypted

plain = "abcdefghijklmnopqrstuvwxyz"
cipher = encrypt(plain)
tmp = cipher[0:16] + bytes(16) + cipher[0:16] + cipher[16:]
cracked = crack_cipher(tmp)

if (iv == xor(cracked[0:16], cracked[32:48])):
    print('True')
    print(iv)
    print(xor(cracked[0:16], cracked[32:48]))
else:
    print('False')


#Author-FernandoFigueiredo
#Description-Creates lofting profiles for a double envoloping worm gear

import adsk.core, adsk.fusion, traceback
import math

def run(context):
    Pi = 3.141592654

    ####################################################
    ## Parameters (distances in cm angles in degrees)
    ####################################################
    pitch = 1.2         #Pitch (cm)
    starts = 1          #Number of starts
    whPteeth = 12       #Nuber of teeth on wheel
    pressAngle =  14.5  #Pressure Angle (deg) 14.5 or 20
    woRes = 36          #Worm Resolution

    redRatio = whPteeth /starts  #reduction ration

    pressAngleRads = pressAngle/180*Pi

    woResAng = 2*Pi/ (woRes)
    whResAng = woResAng / redRatio
    print('OutRotAng =', whResAng * woRes)
    print ('RedRatio:', redRatio)
    print ('woResAng:', woResAng)
    print ('whResAng:', whResAng)
    woLength = 5
    woDp = 1.5 # Worm Pitch Diameter
    toothHeight = 0.5
    woDo = woDp + toothHeight #Worm Out Diameter
    woDr = woDp - toothHeight #Worm Root Diameter
    woDm = 2.5 #Worm Max Diameter
    whDp = whPteeth * pitch / Pi
    whAngPitch = 2 * Pi /(whPteeth)
    WhDo = woDp + whDp - woDr
    WhDi = woDp + whDp - woDo
    cD = (whDp + woDp) /2

    print('WheelTeeth =' , whPteeth)
    print('WheelPitchDiameter =' , whDp)

    ui = None
    try:
        app = adsk.core.Application.get()
        ui = app.userInterface

        #doc = app.documents.add(adsk.core.DocumentTypes.FusionDesignDocumentType)

        design = app.activeProduct

        # Get the root component of the active design.
        rootComp = design.rootComponent

        # Create a new sketch on the xy plane.
        sketches = rootComp.sketches
        xyPlane = rootComp.xYConstructionPlane

        #circlePitch = circles.addByCenterRadius(adsk.core.Point3D.create(cD, 0, 0), whDp/2)

        #oCircle = circles.addByCenterRadius(adsk.core.Point3D.create(cD, 0, 0), WhDo/2)

        for i in range(0, woRes+1):
            sketch = sketches.add(xyPlane)
            #sketch = sketches[0]

            # Draw a rectangle by two points.
            lines = sketch.sketchCurves.sketchLines;
            #wormCenterLine = lines.addByTwoPoints(adsk.core.Point3D.create(0, -woLength/2-20, 0), adsk.core.Point3D.create(0, woLength/2+20, 0))

            # Draw some circles.
            circles = sketch.sketchCurves.sketchCircles
            iCircle = circles.addByCenterRadius(adsk.core.Point3D.create(cD, 0, 0), WhDi/2)

            #oCircle = oCircle.trim (adsk.core.Point3D.create(cD+WhDo/2, 0, 0))
            recLines = lines.addTwoPointRectangle(adsk.core.Point3D.create(0, -woLength/2, 0), adsk.core.Point3D.create(woDm/2, woLength/2, 0))
            geoms2 = adsk.core.ObjectCollection.create()
            geoms2.add(recLines[1])
            geoms2.add(iCircle)

            for j in range(0, int(whPteeth)):
                toothProf1 = lines.addByTwoPoints(adsk.core.Point3D.create(woDo/2*1.2, -pitch/4-(woDo-woDp)*math.tan(pressAngleRads)/2*1.2 , 0), adsk.core.Point3D.create(woDr/2, -pitch/4+(woDp-woDr)/2*math.tan(pressAngleRads), 0))
                toothProf2 = lines.addByTwoPoints(adsk.core.Point3D.create(woDo/2*1.2, +pitch/4+(woDo-woDp)*math.tan(pressAngleRads)/2*1.2 , 0), adsk.core.Point3D.create(woDr/2, +pitch/4-(woDp-woDr)/2*math.tan(pressAngleRads), 0))
                toothProf3 = lines.addByTwoPoints(toothProf1.endSketchPoint, toothProf2.endSketchPoint)

                geoms1 = adsk.core.ObjectCollection.create()
                geoms1.add(toothProf1)
                geoms1.add(toothProf2)
                geoms1.add(toothProf3)
                rotationAxis1 = adsk.core.Vector3D.create(0, 0, 1)
                rotationCenter1 = adsk.core.Point3D.create(cD, 0, 0)
                rotationMatrix1 = adsk.core.Matrix3D.create()
                rotationMatrix1.setToRotation(whResAng *i + whAngPitch *j, rotationAxis1, rotationCenter1)
                sketch.move(geoms1, rotationMatrix1)
                geoms2.add(toothProf1)
                geoms2.add(toothProf2)

            ##geoms.add(oCircle)

            #print(i)

            rotationAxis2 = adsk.core.Vector3D.create(0, 1, 0)
            rotationCenter2 = adsk.core.Point3D.create(0, 0, 0)
            rotationMatrix2 = adsk.core.Matrix3D.create()
            rotationMatrix2.setToRotation(woResAng * i, rotationAxis2, rotationCenter2)

            sketch.move(geoms2, rotationMatrix2)
            #sketch.move(toothProf2, rotationMatrix2)
            #sketch.move(iCircle, rotationMatrix2)
            #sketch.move(recLines, rotationMatrix2)

    except:
        if ui:
            ui.messageBox('Failed:\n{}'.format(traceback.format_exc()))


import asyncio

from day36.tel import send_msg_t

class NotificationManager:
    def __init__(self, data: dict):
        self.dic = data
        self.string = self.format_not(self.dic)

    def format_not(self, flight_info):
        notf = (
            f"Flight from {flight_info['cityFrom']} ðŸ›« to {flight_info['cityTo']} ðŸ›¬ "
            f"on {flight_info['utc_departure'].replace('T','')[:10]} âŒš costs"
            f" {flight_info['price']} ðŸ’°"
        )
        return notf

    async def send_notification(self, notfication):
        await send_msg_t([notfication])


from asyncio import Handle
from re import match
from create import check_answer

"""
This fuction checks if the time is in the correct format.
Ex.: 12.98 (seconds), 01:23.98 (minutes) or 02:34:45.67(hours)
"""
def check_time(time:str) -> bool:

	if len(time) == 5:
		answer = bool(match("[0-5][0-9][.][0-9][0-9]",time))

	elif len(time) == 8:
		answer = bool(match("[0-5][0-9][:][0-5][0-9][.][0-9][0-9]",time))

	elif len(time) == 11:
		answer = bool(match("[0-9][0-9][:][0-5][0-9][:][0-5][0-9][.][0-9][0-9]",time))

	else: answer = False

	return answer

"""
Function responsible to update the dictionary "times_info"
Just like "check_distance" in "new_practice", "check_time" is being used here to be sure the time's format is correct
The steps in this one are:
-> Get the event which time will be recorded
-> Loop with "check_time" as condition to guarantee the correct format
-> Creates a list with the times of the event and put them in order (fastest to slowest)
-> Repeat until the user stops
"""
def new_time(times_info:dict):
	new_op = input("\nDo you want to record a new time?[Yes/No]\n")
	control = check_answer(new_op)

	while(control):
		event = input("\nWhich event is going to be recorded?\n")
		valid_time = False
		while(not valid_time):
			time = input("\nWhat is the time?\n")
			valid_time = check_time(time)
			if not valid_time:
				print("\nNot the correct format\n")

		all_times = times_info.get(event, [])
		all_times.append(time)

		times_info[event] = all_times
		times_info[event].sort(key = lambda time: (len(time), time))

		new_op = input("\nDo you want to record a new time?[Yes/No]\n")
		control = check_answer(new_op)

"""
It writes the information in "times_info" at the file
"""
def write_times_info(handle:Handle, times_info:dict):
	handle.write("\nTimes:\n\n")

	for event, times in times_info.items():
		handle.write("->"+event+":\n")
		count = 1

		for i in times:
			sentence ="("+str(count)+") "+i+"\n"
			handle.write(sentence)
			count += 1

		handle.write("\n")


from random import choice

class Randomwalk():
    """创建一个随机游走类"""
    def __init__(self,num_points=5000):
        """初始化属性"""
        self.num_points=num_points
        self.x_values=[0]
        self.y_values=[0]
    def walk(self):
        """点随机游走"""
        #随机游走循环
        while(len(self.x_values)<=self.num_points):
            #设置x坐游走的距离
            x_direction=choice([-1,1])
            x_distance=choice([0,1,2,3,4])
            x_step=x_direction*x_distance
            #设置y坐标游走的距离
            y_direction=choice([-1,1])
            y_distance=choice([0,1,2,3,4])
            y_step=y_direction*y_distance
            #计算下一步散点的坐标
            next_x=self.x_values[-1]+x_step
            next_y=self.y_values[-1]+y_step
            #将下一次的坐标添加到列表中
            self.x_values.append(next_x)
            self.y_values.append(next_y)


import numpy as np

from data_partitions.triplet_partition import TripletPartition
from data_sets.generics import TripletDataset

class Balanced(TripletDataset):
    def __init__(self, data: TripletPartition):
        super().__init__(data)
        self.positive_fine = data.positive_fine
        self.positive_coarse = data.positive_coarse
        self.negative_fine = data.negative_fine
        self.negative_coarse = data.negative_coarse

        self.reselect_coarse()

    def epoch_handler(self):
        self.reselect_coarse()

    def reselect_coarse(self):
        # clear out selected negatives
        self.triplets = []

        # select random subset of positive coarse grain examples equal in size to positive fine grain examples
        positive_indices = np.random.choice(np.arange(len(self.positive_coarse)), len(self.positive_fine))
        [self.triplets.append(self.positive_coarse[i]) for i in positive_indices]

        # select random subset of negative coarse grain examples equal in size to negative fine grain examples
        negative_indices = np.random.choice(np.arange(len(self.negative_coarse)), len(self.negative_fine))
        [self.triplets.append(self.negative_coarse[i]) for i in negative_indices]

        # add in all the fine grain examples
        [self.triplets.append(e) for e in self.positive_fine]
        [self.triplets.append(e) for e in self.negative_fine]

        np.random.shuffle(self.triplets)


import discord

# Credentials:
token = "Bot Secret Token"
owner_id = "Admin Discord ID"

# Proxy setup:
class Proxy:
    def __init__(self):
        self.endpoint = None

proxy = Proxy()

# Start client:
client = discord.Client()

# --------------------------------------------------------------------------- #
# On Message:
# --------------------------------------------------------------------------- #
@client.event
async def on_message(message):
    # Ignore self and bot messages:
    if message.author == client.user or message.author.bot:
        return

    # Update endpoint channel:
    if str(message.channel.type) != "private" and message.content.startswith("!spawn"):
        if proxy.endpoint == None:
            proxy.endpoint = message.channel
            await message.add_reaction("\u2611")
        else:
            print("{0} tried to spawn your proxy at [{1} | {2}]".format(message.author.name, message.guild, message.channel))

    # Command Center:
    if str(message.channel.type) == "private" and str(message.author.id) == owner_id:
        if message.content.startswith("!say"):
            tmp = message.content.split("!say ")[-1]
            await proxy.endpoint.trigger_typing()
            await proxy.endpoint.send(tmp)

# --------------------------------------------------------------------------- #
# Run
# --------------------------------------------------------------------------- #
client.run(token)


#!/opt/software/occigen/tools/python/2.7.12/intel/17.0/bin/python

from scipy.ndimage import gaussian_filter
import numpy as np
import sys
#import tensorflow as tf
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import time
import logging
import os
import argparse
import matplotlib.pyplot as plt

DATAPATH='/scratch/cnt0028/ias1717/SHARED/RD12_data/dmc/MISS03/DATA/PBR_JMD'
OUTNAME='545_FSL'
OUTNAME='857_FSL'

boloref=[sys.argv[1]]
TFLEARN=DATAPATH+'/'+'FSL_545_INITMODEL'

dostep=int(sys.argv[2])
ostep=dostep
TFLEARN=DATAPATH+'/'+'FSL_%s_S%d_INITMODEL'%(boloref[0],ostep)
print(TFLEARN)

do857=True
doDef=False
docor=False
dovar=False
doadd=False
doplot=False

if len(sys.argv)>3:
    doplot=True

lamptab=[27.5,2.0,20.0,18.0]

if sys.argv[1]=='857-1':
    lamp=27.5
    positivity=1.0
    #======================================================================
    #=
    #=    REGLAGE THRESHOLD 857-1
    #=
    #======================================================================
    thresh=0.0007
if sys.argv[1]=='857-2':
    positivity=1.0
    lamp=2.0
    thresh=0.02
if sys.argv[1]=='857-3':
    positivity=-1.0
    lamp=20.0
    thresh=0.0012
if sys.argv[1]=='857-4':
    positivity=1.0
    lamp=8.0
    thresh=0.002

if do857==False:
    res=np.load(DATAPATH+'/INITCODE_%s_ALL.npy'%(OUTNAME))
    nx,ny,nz=res.shape
    res=np.append(np.load(DATAPATH+'/INITCODE_%s_ALL.npy'%(OUTNAME)),np.load(DATAPATH+'/INITCODE1_%s_ALL.npy'%(OUTNAME))).reshape(2*nx,ny,nz)
    hres=np.append(np.load(DATAPATH+'/INITCODE_%s_HALL.npy'%(OUTNAME)),np.load(DATAPATH+'/INITCODE1_%s_HALL.npy'%(OUTNAME))).reshape(2*nx,ny,nz)
else:
    #res=np.load(DATAPATH+'/INITCODE_%s_ALL.npy'%(OUTNAME))[0:4,:,:]
    #hres=np.load(DATAPATH+'/INITCODE_%s_HALL.npy'%(OUTNAME))[0:4,:,:]
    if dostep>0:
        ires=np.load(DATAPATH+'/ERRCODE_%s_%s_ALL.npy'%(OUTNAME,sys.argv[1]))
        ihres=np.load(DATAPATH+'/ERRCODE_%s_%s_HALL.npy'%(OUTNAME,sys.argv[1]))

        nx,ny,nz=ires.shape
        bolo=['857-1','857-2','857-3','857-4']
        tmp=np.load('TMPFSL.npy')
        res=np.zeros([5,ny,nz])
        hres=np.zeros([5,ny,nz])
        res[0,:,:]=ires[0,:,:]
        hres[0,:,:]=ihres[0,:,:]
        if doplot==True:
            tmp=np.load('TMPFSL.npy')
            plt.subplot(1,5,1)
            plt.imshow(tmp[0,:,:]+tmp[1,:,:]+tmp[2,:,:]+tmp[3,:,:],cmap='jet')

        for i in range(4):
            res2=np.load(DATAPATH+'/ERRCODE_%s_%s_ALL.npy'%(OUTNAME,bolo[i]))
            hres2=np.load(DATAPATH+'/ERRCODE_%s_%s_HALL.npy'%(OUTNAME,bolo[i]))
            if dostep==1:
                mm=np.load('/export/home1/jmdeloui/DATA4SROLL4/VECT/%s_offsets_PROD_REP6_RD12_545GHz_DATA_CNN2D_TL_FSL_1_-32_DECOD_0.npy'%(bolo[i])).reshape(1024,512)
            else:
                mm=np.load('/export/home1/jmdeloui/DATA4SROLL4/VECT/%s_offsets_PROD_REP6_RD12_545GHz_DATA_CNN2D_TL_FSL_S%d_1_-32_DECOD_0.npy'%(bolo[i],dostep-1)).reshape(1024,512)

            aa=((mm*res2[0,:,:])*(hres2[0,:,:]>0)*(hres[0,:,:]>0)).sum()/((mm*mm)*(hres2[0,:,:]>0)*(hres[0,:,:]>0)).sum()
            print(aa)
            aa=1E-3
            template=2*((i!=2)-0.5)*(mm*aa-res2[0,:,:])
            template*=(abs(template)>0.01) #>0.01*abs(template).max())
            res[i+1,:,:]=(ires[0,:,:]+positivity*template)*(hres2[0,:,:]>0)*(hres[0,:,:]>0)
            hres[i+1,:,:]=ihres[0,:,:]*(hres2[0,:,:]>0)*(hres[0,:,:]>0)
            if doplot==True:
                plt.subplot(1,5,2+i)
                plt.imshow((res[i+1,:,:]-ires[0,:,:])*(hres2[0,:,:]>0)*(hres[0,:,:]>0),cmap='jet')
        if doplot==True:
            plt.show()
            exit(0)

    else:
        #======================================================================
        #=    ON NE PASSE QU'ICI
        #=    ON NE PASSE QU'ICI
        #=    ON NE PASSE QU'ICI
        #======================================================================
        res=np.load(DATAPATH+'/ERRCODE_%s_%s_ALL.npy'%(OUTNAME,sys.argv[1]))
        hres=np.load(DATAPATH+'/ERRCODE_%s_%s_HALL.npy'%(OUTNAME,sys.argv[1]))
        nx,ny,nz=res.shape

        if dostep<0:
            res=np.load(DATAPATH+'/ERRCODE_%s_%s_ALL.npy'%(OUTNAME,'857-2'))
            hres=np.load(DATAPATH+'/ERRCODE_%s_%s_HALL.npy'%(OUTNAME,'857-2'))
            nx,ny,nz=res.shape

            tmp=np.zeros([3,ny,nz])
            htmp=np.zeros([3,ny,nz])
            thresh=0.001
            for i in range(3):
                if i>=1:
                    ii=i+1
                else:
                    ii=i
                print(lamptab[ii])
                tmp[i,:,:]=(res[1+i,:,:])*(abs(res[0,:,:])>thresh)/lamptab[ii]
                htmp[i,:,:]=hres[1+i,:,:]
                plt.subplot(1,3,1+i)
                #=================================================================================================
                # SUPPRIME LES STRUCTURES NON LIEES AU FSL DANS LE MODEL 3-2
                if i==1:
                    vv=1E-3
                    oo=4E-5
                    ww=(np.repeat(np.exp(-vv*(np.arange(ny)-480)**2),nz)*np.tile(np.exp(-oo*(np.arange(nz)-50)**2),ny)).reshape(ny,nz)
                    ww+=(np.repeat(np.exp(-vv*(np.arange(ny)-30)**2),nz)*np.tile(np.exp(-oo*(np.arange(nz)-50)**2),ny)).reshape(ny,nz)
                    ww+=(np.repeat(np.exp(-vv*(np.arange(ny)-930)**2),nz)*np.tile(np.exp(-oo*(np.arange(nz)-50)**2),ny)).reshape(ny,nz)
                    ww+=(np.repeat(np.exp(-vv*(np.arange(ny)-670)**2),nz)*np.tile(np.exp(-oo*(np.arange(nz)-460)**2),ny)).reshape(ny,nz)
                    ww+=(np.repeat(np.exp(-vv*(np.arange(ny)-220)**2),nz)*np.tile(np.exp(-oo*(np.arange(nz)-460)**2),ny)).reshape(ny,nz)
                    tmp[i,:,:]=(1-ww)*tmp[1,:,:]

                plt.imshow(tmp[i,:,:],cmap='jet')
                plt.ylabel('res%d'%(i))
            plt.show()

            print('save the result')
            np.save('TMPFSL2.npy',tmp)
            np.save('TMPFSL2H.npy',htmp)
            exit(0)

        tmp=np.load('TMPFSL2.npy')
        htmp=np.load('TMPFSL2H.npy')
        for i in range(3):
            res[1+i,:,:]=res[0,:,:]+tmp[i,:,:]
            hres[1+i,:,:]=hres[0,:,:]*(htmp[i,:,:]>0)
        dobolo2=False
        if dobolo2==True:
            #============================================================================
            # ONLY LEARN DIFF WITH BOLOMETER 2
            #============================================================================
            if sys.argv[1]=='857-1':
                for k in range(3):
                    res[1+k:,:]=res[0,:,:]+tmp[0,:,:]*(3*k-1.0)
                    hres[1+k,:,:]=hres[0,:,:]*(htmp[0,:,:]>0)
            if sys.argv[1]=='857-2':
                nx,ny,nz=res.shape
                for k in range(3):
                    res[1+k,:,:]=res[0,:,:]+np.random.randn(ny,nz)*0.1*res[0,:,:].std()
            if sys.argv[1]=='857-3':
                for k in range(3):
                    res[1+k,:,:]=res[0,:,:]+tmp[1,:,:]*(3*k-1.0)
                    hres[1+k,:,:]=hres[0,:,:]*(htmp[1,:,:]>0)
            if sys.argv[1]=='857-4':
                for k in range(3):
                    res[1+k,:,:]=res[0,:,:]-tmp[2,:,:]*(3*k-1.0)
                    hres[1+k,:,:]=hres[0,:,:]*(htmp[2,:,:]>0)

        if doplot==True:
            plt.subplot(1,4,1)
            plt.imshow(res[0,:,:],cmap='jet',vmin=-0.1*res[0,:,:].max(),vmax=res[0,:,:].max())
            for i in range(3):
                plt.subplot(1,4,2+i)
                plt.imshow(res[1+i,:,:]-res[0,:,:],cmap='jet',vmin=-0.1*res[0,:,:].max(),vmax=0.1*res[0,:,:].max())
            plt.show()
            exit(0)

    res=res.astype('float32')
    hres=hres.astype('float32')

nx,ny,nz=res.shape

if doadd==True:
    temp=np.load(DATAPATH+'/ERRCODE_%s_ALL.npy'%(OUTNAME))
    htemp=np.load(DATAPATH+'/ERRCODE_%s_HALL.npy'%(OUTNAME))
    ncorr,ny,nz=temp.shape
    tmp  = np.zeros([(nx+ncorr*2),ny,nz])
    htmp = np.zeros([(nx+ncorr*2),ny,nz])

    for i in range(nx):
        tmp[i,:,:]=res[i,:,:]
        htmp[i,:,:]=hres[i,:,:]

    ttt=[0,2,3]

    for j in range(ncorr):
        tmp[nx+2*j,:,:]    = res[ttt[j],:,:]+temp[j,:,:]/8.0
        htmp[nx+2*j,:,:]   = hres[ttt[j],:,:]
        tmp[nx+2*j+1,:,:]  = res[ttt[j],:,:]-temp[j,:,:]/8.0
        htmp[nx+2*j+1,:,:] = hres[ttt[j],:,:]

    res=tmp.astype('float32')
    hres=htmp.astype('float32')

print(res.shape)
nx,ny,nz=res.shape
for i in range(nx-1):
    res[i+1,:,:]=res[i+1,:,:]/res[i+1,:,:].std()*res[i,:,:].std()

nd,ny,nx=res.shape

if dovar==True:
    nharm=1
    tmp=np.zeros([(1+4*nharm)*nd,ny,nx])
    htmp=np.zeros([(1+4*nharm)*nd,ny,nx])
    amp=0.2

    x = np.arange(nx)
    y = np.arange(ny)
    xx, yy = np.meshgrid(x, y)

    for i in range(nd):

        tmp[i*(1+4*nharm),:,:]=res[i,:,:]
        htmp[i*(1+4*nharm),:,:]=hres[i,:,:]
        plt.subplot(nd,1+4*nharm,1+i*(1+4*nharm))
        plt.imshow(tmp[i*(1+4*nharm),:,:],cmap='jet')
        for j in range(nharm):
            tmp[i*(1+4*nharm)+1+4*j,:,:]=res[i,:,:]*(1+amp*np.sin(xx/nx*2*np.pi*(1+j)))
            htmp[i*(1+4*nharm)+1+4*j,:,:]=hres[i,:,:]
            plt.subplot(nd,1+4*nharm,2+4*j+i*(1+4*nharm))
            plt.imshow(tmp[i*(1+4*nharm)+1+4*j,:,:],cmap='jet')
            tmp[i*(1+4*nharm)+1+4*j+1,:,:]=res[i,:,:]*(1-amp*np.sin(xx/nx*2*np.pi*(1+j)))
            htmp[i*(1+4*nharm)+1+4*j+1,:,:]=hres[i,:,:]
            plt.subplot(nd,1+4*nharm,3+4*j+i*(1+4*nharm))
            plt.imshow(tmp[i*(1+4*nharm)+1+4*j+1,:,:],cmap='jet')
            tmp[i*(1+4*nharm)+1+4*j+2,:,:]=res[i,:,:]*(1+amp*np.sin(yy/ny*2*np.pi*(1+j)))
            htmp[i*(1+4*nharm)+1+4*j+2,:,:]=hres[i,:,:]
            plt.subplot(nd,1+4*nharm,4+4*j+i*(1+4*nharm))
            plt.imshow(tmp[i*(1+4*nharm)+1+4*j+2,:,:],cmap='jet')
            tmp[i*(1+4*nharm)+1+4*j+3,:,:]=res[i,:,:]*(1-amp*np.sin(yy/ny*2*np.pi*(1+j)))
            htmp[i*(1+4*nharm)+1+4*j+3,:,:]=hres[i,:,:]
            plt.subplot(nd,1+4*nharm,5+4*j+i*(1+4*nharm))
            plt.imshow(tmp[i*(1+4*nharm)+1+4*j+3,:,:],cmap='jet')
    plt.show()
    res=tmp.astype('float32')
    hres=htmp.astype('float32')

nd,ny,nx=res.shape

if docor==True:
    ntest=4

    x0=341
    y0a=343
    y0b=793

    x1=90
    y1a=386
    y1b=835

    sx=0.0006
    sy=0.03

    tmp=np.zeros([(1+2*ntest)*nd,ny,nx])
    htmp=np.zeros([(1+2*ntest)*nd,ny,nx])

    x = np.arange(nx)
    y = np.arange(ny)
    xx, yy = np.meshgrid(x, y)
    for i in range(nd):
        dx=30*np.random.randn(ntest)
        dy=30*np.random.randn(ntest)

        tmp[i*(1+2*ntest),:,:]=res[i,:,:]
        htmp[i*(1+2*ntest),:,:]=hres[i,:,:]
        plt.subplot(nd,1+2*ntest,1+i*(1+2*ntest))
        plt.imshow(tmp[i*(1+2*ntest),:,:],cmap='jet')
        for j in range(ntest):
            tmp[i*(1+2*ntest)+1+2*j,:,:]=res[i,:,:]+0.01*(np.exp(-(sx*(xx-x0+dx[j])**2+sy*(yy-y0a+dy[j])**2))+np.exp(-(sx*(xx-x0+dx[j])**2+sy*(yy-y0b+dy[j])**2)))
            htmp[i*(1+2*ntest)+1+2*j,:,:]=hres[i,:,:]
            plt.subplot(nd,1+2*ntest,2+2*j+i*(1+2*ntest))
            plt.imshow(tmp[i*(1+2*ntest)+1+2*j,:,:],cmap='jet')
            tmp[i*(1+2*ntest)+1+2*j+1,:,:]=res[i,:,:]+0.01*(np.exp(-(sx*(xx-x1+dx[j])**2+sy*(yy-y1a+dy[j])**2))+np.exp(-(sx*(xx-x1+dx[j])**2+sy*(yy-y1b+dy[j])**2)))
            htmp[i*(1+2*ntest)+1+2*j+1,:,:]=hres[i,:,:]
            plt.subplot(nd,1+2*ntest,3+2*j+i*(1+2*ntest))
            plt.imshow(tmp[i*(1+2*ntest)+1+2*j+1,:,:],cmap='jet')
    plt.show()
    res=tmp.astype('float32')
    hres=htmp.astype('float32')

import scipy.special as sp

def calcshift(nx,sig=128.0,phase=0.0,amp=0.5):
    xx=np.ones([nx])+np.exp(-0.5*((np.arange(nx)-phase)/sig)**2)
    xx=np.cumsum(xx)
    xx-=xx.min()
    xx=nx*xx/xx.max()
    return(xx)

nd,ny,nx=res.shape
if doDef==True:
    tmp=np.zeros([3*nd,ny,nx])
    htmp=np.zeros([3*nd,ny,nx])

    import scipy.interpolate as interpolate

    x = np.arange(nx)
    y = np.arange(ny)
    xx, yy = np.meshgrid(x, y)
    for i in range(nd):
        f = interpolate.interp2d(x, y, res[i,:,:], kind='cubic')
        fh = interpolate.interp2d(x, y, hres[i,:,:], kind='cubic')
        tmp[i*3,:,:]=res[i,:,:]
        htmp[i*3,:,:]=hres[i,:,:]
        tmp[i*3+1,:,:]=f(calcshift(nx,phase=nx/4),y)
        htmp[i*3+1,:,:]=fh(calcshift(nx,phase=nx/4),y)
        tmp[i*3+2,:,:]=f(calcshift(nx,phase=3*nx/4),y)
        htmp[i*3+2,:,:]=fh(calcshift(nx,phase=3*nx/4),y)

    res=tmp.astype('float32')
    hres=htmp.astype('float32')

nx,ny,nz=res.shape
for i in range(nx-1):
    res[i+1,:,:]=res[i+1,:,:]/res[i+1,:,:].max()*res[i,:,:].max()

#================================================================================
#
#    MULTIPLY BY 1000 TO MAKE IT AT THE GOOD LEVEL (x1000)
#
#================================================================================

res=res*1000.
XNHIDDEN=2
YNHIDDEN=XNHIDDEN
NCOMP=16
SCALE=4
NHIDDEN=XNHIDDEN*YNHIDDEN*NCOMP
DEEPNESS=2*NCOMP
EVAL_FREQUENCY = 100
KERNELSZ = 7
SEED = 1234
DORELU = True
LEARNING_RATE= 0.03
DECAY_RATE=0.995
NUM_EPOCHS= 10000
BATCHSZ=nx
DOFULLYCONNECTED = True

if DOFULLYCONNECTED==False:
    NTOTHIDDEN=NHIDDEN//(XNHIDDEN*YNHIDDEN)
    NUM_DCONV_CHAN =[ NHIDDEN//(XNHIDDEN*YNHIDDEN), DEEPNESS, DEEPNESS, 1]
else:
    NTOTHIDDEN=1
    NUM_DCONV_CHAN =[ DEEPNESS, DEEPNESS, DEEPNESS, 1]
NDCONV=len(NUM_DCONV_CHAN)-1
NMAT,XIMAGE_SIZE,YIMAGE_SIZE=res.shape

if DOFULLYCONNECTED:
    fc2_weights = tf.Variable(0.1*np.random.randn(NTOTHIDDEN, XIMAGE_SIZE // (SCALE**NDCONV) * YIMAGE_SIZE // (SCALE**NDCONV) * NUM_DCONV_CHAN[0]).astype('float32'))
    fc2_biases = tf.Variable(0.1*np.random.randn(XIMAGE_SIZE // (SCALE**NDCONV) * YIMAGE_SIZE // (SCALE**NDCONV) * NUM_DCONV_CHAN[0]).astype('float32'))

dconv_weights={}
dconv_biases={}
nw=0
for i in range(NDCONV):
    dconv_weights[i] = tf.Variable(0.1*np.random.randn(KERNELSZ, KERNELSZ, NUM_DCONV_CHAN[i+1], NUM_DCONV_CHAN[i]).astype('float32'))
    dconv_biases[i] = tf.Variable(0.1*np.random.randn(NUM_DCONV_CHAN[i+1]).astype('float32'))

params = tf.Variable(np.zeros([NMAT,NTOTHIDDEN],dtype='float32'))

train_data = tf.placeholder(tf.float32,shape=(BATCHSZ,XIMAGE_SIZE,YIMAGE_SIZE,1))
hdata=tf.constant(hres.reshape(BATCHSZ,XIMAGE_SIZE,YIMAGE_SIZE,1))
run_param  = tf.placeholder(tf.float32,shape=(1,NTOTHIDDEN))

def lrelu(x, alpha=0.3):
  #return tf.nn.relu(x)
  return tf.maximum(x, tf.multiply(x, alpha))

def wdecod(parameter):
    # convert into image/bias
    #hidden = tf.matmul(parameter, fc1_weights) + fc1_biases
    #if DORELU==True:
    #    hidden = lrelu(hidden)
    print('NPAR PER IMAGE',int((parameter.get_shape().as_list())[1]))
    if DOFULLYCONNECTED==False:
        hidden = parameter
    else:
        hidden = tf.matmul(parameter, fc2_weights) + fc2_biases
        if DORELU==True:
            hidden = lrelu(hidden)
    #hidden = lrelu(hidden)
    NTIME=int((parameter.get_shape().as_list())[0])

    relu = tf.reshape(hidden,[NTIME, XIMAGE_SIZE // (SCALE**NDCONV) , YIMAGE_SIZE // (SCALE**NDCONV) , NUM_DCONV_CHAN[0]])
    #
    ## deconvolve : First layer
    # DeConvolution kernel
    for i in range(NDCONV):
        conv = tf.nn.conv2d_transpose(relu,dconv_weights[i],strides=[1, SCALE, SCALE, 1],padding='SAME',
                                      output_shape=[NTIME,XIMAGE_SIZE // (SCALE**(NDCONV-1-i)),YIMAGE_SIZE // (SCALE**(NDCONV-1-i)),
                                                    NUM_DCONV_CHAN[i+1]],name='dconv_%d'%(i))
        tmp=tf.nn.bias_add(conv, dconv_biases[i])
        print(tmp.get_shape().as_list(),dconv_weights[i].get_shape().as_list())

        if DORELU==True:
            if i!=NDCONV-1:
                relu = lrelu(tmp)
            else:
                relu = lrelu(tmp,alpha=0)
        else:
            relu=tmp

    relu=relu/100

    return relu

def model(parameter):

    modpar=wdecod(parameter)
    return modpar

lpar = params
logits = model(lpar)

synthe = model(run_param)

loss=tf.reduce_sum(hdata*tf.square((logits-train_data)))

numbatch = tf.Variable(0, dtype=tf.float32)

# Decay once per epoch, using an exponential schedule starting at 0.01.
learning_rate = tf.train.exponential_decay(
        LEARNING_RATE,       # Base learning rate.
        numbatch,            # Current index into the dataset.
        10,                  # Decay step.
        DECAY_RATE,          # Decay rate.
        staircase=True)

optimizer=tf.train.AdamOptimizer(learning_rate,0.9).minimize(loss,
                                                                           global_step=numbatch)
# Create a local session to run the training.
start_time = time.time()
print('Initialized 1')

import matplotlib.pyplot as plt

loss_log=np.zeros([NUM_EPOCHS//EVAL_FREQUENCY])

minloss=1E30
with tf.Session() as sess:
    # Run all the initializers to prepare the trainable parameters.
    tf.global_variables_initializer().run()
    print('Initialized 2')
    # Loop through training steps.

    for step in range(NUM_EPOCHS):

        feed_dict = {train_data: res.reshape(BATCHSZ,XIMAGE_SIZE,YIMAGE_SIZE,1)}

        sess.run(optimizer, feed_dict=feed_dict)
        # print some extra information once reach the evaluation frequency
        if step % EVAL_FREQUENCY == 0:
            # fetch some extra nodes' data
            l, lr = sess.run([loss, learning_rate],feed_dict=feed_dict)
            loss_log[step//EVAL_FREQUENCY]=l

            elapsed_time = time.time() - start_time
            start_time = time.time()

            print('Step %d[%5.2f], Mloss[par of sigma]: %7.4f, lrate: %8.5f DURATION %4.2f' % (step,step*BATCHSZ/(1.0*NMAT),np.sqrt(l/(BATCHSZ*XIMAGE_SIZE*YIMAGE_SIZE)), lr,elapsed_time))

    lf,lb =sess.run([fc2_weights,fc2_biases])
    np.save('%s_%d_fc2w.npy'%(TFLEARN,0),lf)
    np.save('%s_%d_fc2b.npy'%(TFLEARN,0),lb)

    for i in range(NDCONV):
        lw,lb =sess.run([dconv_weights[i],dconv_biases[i]])
        np.save('%s_%d_w_%d.npy'%(TFLEARN,0,i),lw)
        np.save('%s_%d_b_%d.npy'%(TFLEARN,0,i),lb)

    predictions,par=sess.run([logits,lpar], feed_dict=feed_dict)
    np.save('%s_DECODREBUILD.npy'%(TFLEARN),predictions.reshape(NMAT,XIMAGE_SIZE,YIMAGE_SIZE))
    alldata=predictions
    allparams=par
    for i in range(BATCHSZ):
        np.save('%s_%d_param.npy'%(TFLEARN,i),par[i,:].reshape(1,NTOTHIDDEN))
        minloss=l
        np.save('%s_step.npy'%(TFLEARN),ostep)
        print('MIN SAVE',l)
    print(allparams)


from generator import Generator
from convex_hull import ConvexHull
from point import Point
from matplotlib.lines import Line2D
import matplotlib.pyplot as plt

# test generator
def test_generator(points=100):
    g = Generator()
    a = g.next_batch(points)
    g.show()

# test calculate polar angle
def test_calc_polar_angle(points=50):
    from utils import calc_polar_angle
    g = Generator()
    a = g.next_batch(points)
    X = Point(50,50)
    P = Point(75,75)
    s_pa = calc_polar_angle(X, P, a)
    print(s_pa)
    f = plt.figure('Test Polar Angle')
    p1 = plt.scatter([p.X for p in a],
                     [p.Y for p in a],
                     marker = '.',
                     color = 'r',
                     s = 1)
    for i in range(len(a)):
        plt.annotate("{:.1f}".format(s_pa[i]), [a[i].X,a[i].Y])
    plt.plot([50,100],[50,100], color='g', linewidth=2)
    f.show()

# test convex hull
def test_convex_hull(stratery='graham-scan', points=10000):
    g = Generator()
    a = g.next_batch(points)
    c = ConvexHull(a, stratery)
    time = c.start()
    print('Escape time ' + str(time))
    c.show()

#test_convex_hull('divide-conqure', 10000)
#test_convex_hull(points=1000)

# test insert sort
def test_insert_sort(points=10000):
    from utils import insert_sort
    from datetime import datetime
    import numpy.random as rand
    s = rand.randint(1,100000000,points).tolist()
    start = datetime.now()
    insert_sort(s)
    end = datetime.now()
    print ('insert sort escape time: ' + str(end-start))
    start = datetime.now()
    sorted(s)
    end = datetime.now()
    print ('sorted escape time: ' + str(end-start))

# test linear select
def test_linear_select(points=10000000):
    from utils import linear_select
    import numpy.random as rand
    import numpy as np
    from datetime import datetime
    s = rand.randint(1,100000000,points).tolist()
    k = 3
    print ('len(s) = ' + str(len(s)) + ' k = ' + str(k))
    start = datetime.now()
    res = linear_select(s, k)
    end = datetime.now()
    print(' linear select time: ' + str(end-start))
    start = datetime.now()
    s = sorted(s)
    end = datetime.now()
    print(' sort time: ' + str(end-start))
    start = datetime.now()
    m = np.median(s)
    end = datetime.now()
    print(' median time: ' + str(end-start))

# test in triangle
def test_in_triangle(points=1000):
    g = Generator()
    a = g.next_batch(points)
    triangle = [Point(10,10), Point(60,20), Point(100,80)]
    in_ = list()
    out_ = list()
    for p in a:
        if p.in_triangle(triangle): in_.append(p)
        else: out_.append(p)
    f = plt.figure('Test Triangle')
    plt.plot([triangle[0].X, triangle[1].X],
         [triangle[0].Y, triangle[1].Y], linewidth=1, color='g')
    plt.plot([triangle[1].X, triangle[2].X],
         [triangle[1].Y, triangle[2].Y], linewidth=1, color='g')
    plt.plot([triangle[2].X, triangle[0].X],
         [triangle[2].Y, triangle[0].Y], linewidth=1, color='g')
    p1 = plt.scatter([p.X for p in in_],
                 [p.Y for p in in_],
                 marker = 'o',
                 color = 'r',
                 s = 1)
    p2 = plt.scatter([p.X for p in out_],
                 [p.Y for p in out_],
                 marker = 'x',
                 color = 'b',
                 s = 1)
    f.show()


from __future__ import annotations
from abc import ABC, abstractmethod
import pygame

# abstract class for ui elements
class UIElement(ABC):
    elements: list[UIElement] = []  # list of all ui elements

    # update all elements
    @staticmethod
    def update_all() -> None:
        for element in UIElement.elements:
            if element._parent:
                continue
            element.__update()

    # initialize an element with a target surface, position, and dimension
    def __init__(
        self,
        screen: pygame.Surface,
        x: int,
        y: int,
        width: int,
        height: int,
        background_color: str = None,
    ) -> None:
        self._screen = screen
        self.x = x
        self.y = y
        self.__width = width
        self.__height = height
        self.background_color = background_color

        self._surface = pygame.Surface((self.__width, self.__height))
        self._rect = pygame.Rect(0, 0, self.__width, self.__height)
        self._children: list[UIElement] = []
        self._parent = None

        self.visible = True
        UIElement.elements.append(self)

    @property
    def width(self) -> int:
        return self.__width

    @width.setter
    def width(self, value: int) -> None:
        self.__width = value
        self._surface = pygame.Surface((self.__width, self.__height))
        self._rect = pygame.Rect(
            self._rect.x, self._rect.y, self.__width, self.__height
        )

    @property
    def height(self) -> int:
        return self.__height

    @height.setter
    def height(self, value: int) -> None:
        self.__height = value
        self._surface = pygame.Surface((self.__width, self.__height))
        self._rect = pygame.Rect(
            self._rect.x, self._rect.y, self.__width, self.__height
        )

    # get the rect in world space
    @property
    def world_rect(self) -> pygame.Rect:
        x, y = self.x, self.y
        if self._parent:
            parent_rect = self._parent.world_rect
            x += parent_rect.x
            y += parent_rect.y
        return pygame.Rect(x, y, self.__width, self.__height)

    @property
    def parent(self) -> UIElement:
        return self._parent

    @parent.setter
    def parent(self, value: UIElement) -> None:
        # if parent exists, remove it
        if self._parent:
            self._parent._children.remove(self)

        # set the new parent and add this to its child list
        self._parent = value
        if value:
            value._children.append(self)
            value._on_child_added()

    # get the active area in world space
    def get_active_area(self) -> pygame.Rect:
        area = self.world_rect
        if self._parent:
            area = area.clip(self._parent.get_active_area())
        return area

    # delete this element and all its children
    def delete(self) -> None:
        self.delete_all_children()
        self.background_color = None
        self._surface = None
        self._rect = None
        self.parent = None
        self.visible = False
        UIElement.elements.remove(self)

    # delete all children
    def delete_all_children(self) -> None:
        while self._children:
            self._children[-1].delete()

    # update the element and its children once per frame
    def __update(self) -> None:
        # if background color is not None, fill the surface
        if self.background_color:
            self._surface.fill(self.background_color)

        self._on_update()
        for child in self._children:
            child.__update()
        self.__draw()

    # draw the element to the screen
    def __draw(self) -> None:
        if not self.visible:
            return

        # draw on the screen
        surface = self._screen

        # if parent exists, draw on the parent's surface
        if self._parent:
            surface = self._parent._surface
        surface.blit(self._surface, (self.x, self.y), self._rect)

    # called on update
    @abstractmethod
    def _on_update(self) -> None:
        pass

    # called when a new child is added
    def _on_child_added(self) -> None:
        pass


from django.urls import path

from . import views

app_name = 'links'
urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('vote/', views.VoteView.as_view(), name='vote'),
    path('votes/', views.vote, name='votes'),
    path('result/', views.ResultView.as_view(), name='result'),
]


from collections import OrderedDict

import numpy as np
import pandas as pd
import yaml
from abc import ABC

# отладочный код yaml
config_yaml = """
protocol:
  - !fields
    order_id:
      type: Na
      min_val: Na
      max_val: Na
    stat_order_created_ts:
      - type: Na
      - min_val: Na
      - max_val: Na
    stat_order_processed_user_id:
      - type: Na
      - min_val: Na
      - max_val: Na

"""

class AbstractDataProtocol(yaml.YAMLObject):
    """
    Абстрактный класс
    Обработчик YAML
    """

    @classmethod
    def from_yaml(cls, _loader, _node):
        _parser = cls.Parse()
        config = _loader.construct_mapping(_node)
        _parser.config.update(config)

        return _parser

    @classmethod
    def get_parser(cls):
        return cls.Parser()

    class Parse(ABC):
        pass

class GraderDataProtocol(AbstractDataProtocol):
    """
    Обработчик yaml файла с протоколом
    Экземпляр этого  класса создается и  инициализируется loader'ом модуля yaml
    В возвращаемом обьекте загружены все поля протокола и доступны методы их обработки
    см. методы этого класса

    """
    yaml_tag = u"!fields"

    class Parse:
        def __init__(self):
            self.config = OrderedDict()

        def some_method(self):
            print("some method")

        def get_parser(self):
            return self.Parse

        def num(self, series: pd.Series):
            return pd.to_numeric(series)

        def ts(self, series: pd.Series):
            return pd.to_datetime(series, infer_datetime_format=True)

        def str(self, series: pd.Series):
            name = series.name
            if series.name == "order_client_sex":
                pass
            return series.astype(str)

        def Na(self, series: pd.Series):
            return None

if __name__ == "__main__":

    path_to_yaml = "protocol.yaml"

    #with open(path_to_yaml, "r") as protocol:
    #    parser = yaml.load(protocol, Loader=yaml.FullLoader)["protocol"][0]

    parser = yaml.load(config_yaml, Loader=yaml.FullLoader)["protocol"][0]
    print("parser\n")
    print(parser.some_method())
    print(parser.config)
    print(f"\nparser\n")


def solution(board):
    answer = -1
    ansL = []
    vis= [[False] * len(board) for _ in range(len(board))]
    def dfs(x,y,depth,visited):
        vis[x][y] = True
        dir = [(-1,0),(0,-1),(1,0),(0,1)]
        for k in range(4):
            dx,dy = dir[k]
            if len(board) > dx+ x >= 0 and len(board) > dy+ y >= 0:
                if board[dx+ x][dy+ y] == board[x][y] and visited[dx+ x][dy+ y] == False:
                    dfs(dx+ x,dy+ y,depth+1,visited)
                    visited[dx+ x][dy+ y] = False
        ansL.append(depth)
    for i in range(len(board)):
        for j in range(len(board)):
            dfs(i,j,1,vis)
            vis = [[False] * len(board) for _ in range(len(board))]
    answer = max(ansL)
    if answer == 1:
        return -1
    else:
        return answer

## 재밋게도 배열을 넣으면 그 상태가 저장돼서 나오네 ??

print(solution([[3, 2, 3, 2], [2, 1, 1, 2], [1, 1, 2, 1], [4, 1, 1, 1]]))


#!/anaconda/bin/python

import argparse
import os
import re
from gen_file import *

topic_header = "
\n
{}:
\n
\n"
topic_close = "
\n
\n"
link_template = "
{}
\n"

def extract_topic(File):
    topic = ""
    for c in File[6:]:
        if c == "/":
            break
        topic += c
    return topic

topic_map = {}
pattern = re.compile(".tex")
for dirpath, dirs, files in os.walk("notes/"):
    for filename in files:
        fname = os.path.join(dirpath,filename)
        if pattern.search(fname):
            gen_file(File=fname, link=filename)
            topic = extract_topic(fname)
            if topic not in topic_map:
                topic_map[topic] = []
            topic_map[topic].append((fname.replace(".tex", ".html"), filename.replace(".tex", ".html")))

start_flag = re.compile("append here")
with open("notes/notes.html", 'w+') as note:
    with open("notes/template.html", 'r+') as temp:
        for line in temp:
            note.write(line)
            if start_flag.search(line):
                for key, value in topic_map.items():
                    note.write(topic_header.format(key))
                    for pair in value:
                        file_name, link = pair
                        file_name = file_name[6:]
                        link = link.replace("_", " ").rstrip(".html")
                        note.write(link_template.format(file_name, link))
                    note.write(topic_close)


import numpy as np
from agent import *

class World:
    def __init__(self, height, width, length):
        self.height = height
        self.width = width
        self.length = length
        self.num_floors = 3
        self.num_rows = 8                                # length
        self.num_cols = 8                                # width
        self.agents = []                                   # list of agent object

    #the functuon get list of agents position(start & end), end add them to world
    def add_agents(self,agents_pos):

        self.agents = agents_pos
        if agents_pos:
            for agent_id, (start_x,start_y, start_z, goal_x,goal_y, goal_z) in enumerate(agents_pos):
                # check the validation of the position
                if self.is_valid_pos((start_x,start_y, start_z)) and self.is_valid_pos((goal_x,goal_y, goal_z)):
                    self.agents[agent_id] = Agent(agent_id + 1, (start_x, start_y, start_z),(goal_x, goal_y, goal_z))
                else:
                    raise Exception('Failure! invalid position of agent')
                    return False

    #get position of agent in world, and return if the position is valid
    def is_valid_pos(self, agent_pos):
        x,y,z = agent_pos
        if x < 0 or x > self.num_cols - 1 or y < 0 or y > self.num_rows - 1 or z < 0 or z > self.num_floors -1:
            return False
        else:
            return True

    # returns a list with the numbers 1 to number of agents.
    def get_agents(self):
        return self.agents


from ejson import loads
from eventlib.core import process_external, import_event_modules
from eventlib.util import redis_connection

def listen_for_events():
    """Pubsub event listener

    Listen for events in the pubsub bus and calls the process function
    when somebody comes to play.
    """
    import_event_modules()
    conn = redis_connection.get_connection()
    pubsub = conn.pubsub()
    pubsub.subscribe("eventlib")
    for message in pubsub.listen():
        if message['type'] != 'message':
            continue
        data = loads(message["data"])
        if 'name' in data:
            event_name = data.pop('name')
            process_external(event_name, data)


import os, pygame

C_BLACK = pygame.Color('black')
C_GREEN_TEXT = pygame.Color(84, 255, 159)
C_BLUE = pygame.Color(31, 174, 233)
sky = pygame.Color(127, 199, 255)
XLenWin = 800
YLenWin = 450
XMario = 32
YMario = 64
FrameRate = 10
EventFps = 1
FPS = 50
clock = pygame.time.Clock()
EventMarioRun = 2
MarioFrameRate = 128
right = 'r'
left = 'left'

screen = pygame.display.set_mode((XLenWin, YLenWin))
lvl = 1

def load_image(name, ColorKey=None):
    fullname = os.path.join('pictures', name)
    image = pygame.image.load(fullname)
    if ColorKey is not None:
        if ColorKey == -1:
            ColorKey = image.get_at((0, 0))
        image = image.convert()
        image.set_colorkey(ColorKey)
    else:
        image = image.convert_alpha()
    return image

def format_size(ListWithImg):
    for _ in range(len(ListWithImg)):
        ListWithImg[_] = pygame.transform.scale(ListWithImg[_], (XMario, YMario))
    return ListWithImg

def reformat_coords(x, y):
    return x*32, y*32

def process_coords(yw, ww, hw, xm, ym, i):
    i += 1
    n = -1
    if ym >= yw and ym <= yw + hw:
        xw = 15
        for _ in range(i):
            if xm >= xw and xm <= xw + ww:
                if _ == i - 1:
                    n = 0
                else:
                    n = _ + 1
            xw += ww + 15
    return n


def solution(s):
    answer = 0
    numbers = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']

    for i in range(10):
        s = s.replace(numbers[i], str(i))   # 0 부터 10 까지 각 문자열을 index와 매칭시킨 numbers라는 리스트로 replace를 실행.
    answer = int(s)
    return answer

# replace()의 blackbox를 밝혀보자.


import pygame, sys
from time import sleep

pygame.init()
clock = pygame.time.Clock()

screen_width = 1400
screen_height = 800

font = pygame.font.SysFont(None, 50)

ping1 = pygame.mixer.Sound("D:\Personal Projects\pygame-pong\\assets\Ping1.wav")
ping2 = pygame.mixer.Sound("D:\Personal Projects\pygame-pong\\assets\Ping2.wav")
ping3 = pygame.mixer.Sound("D:\Personal Projects\pygame-pong\\assets\Ping3.wav")
ping4 = pygame.mixer.Sound("D:\Personal Projects\pygame-pong\\assets\Ping4.wav")
goal = pygame.mixer.Sound("D:\Personal Projects\pygame-pong\\assets\Goal.wav")

field_img = pygame.image.load('D:\Personal Projects\pygame-pong\\assets\\field.png')
field_img = pygame.transform.scale(field_img, (screen_width, screen_height))
screen = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Pong')

pygame.display.set_icon(pygame.image.load('D:\Personal Projects\pygame-pong\\assets\icon.png'))

ball = pygame.Rect(screen_width/2-15,screen_height/2-15,30,30)
player = pygame.Rect(screen_width-20,screen_height/2-70,10,120)
opponent = pygame.Rect(10, screen_height/2-70,10,120)

player_score, opponent_score = 0,0
player_spd = 0
opponent_spd = 7
ball_dx, ball_dy = 7,7

state = 'play'
pa_b = pygame.rect.Rect((0,0,0,0))
def player_animation():
    global state
    if state == 'pause' or state == 'gameover': return
    if player.top <= 0:
        player.top = 0
    if player.bottom >= screen_height:
        player.bottom = screen_height
    player.y += player_spd

def opponent_animation():
    global state
    if state == 'pause' or state == 'gameover': return
    if opponent.top <= 0:
        opponent.top = 0
    if opponent.bottom >= screen_height:
        opponent.bottom = screen_height
    if opponent.top < ball.y:
        opponent.top += opponent_spd
    if opponent.top >= ball.y:
        opponent.top -= opponent_spd

def reset_ball(direction):
    ball.x = (screen_width-ball.width)/2
    ball.y = (screen_height-ball.height)/2
    player.top = (screen_height/2)
    opponent.top = (screen_height/2)
    return 5*direction,5*direction

def ball_animation(ball_dx, ball_dy):
    global player_score, opponent_score, state
    if state == 'pause' or state == 'gameover':
        return ball_dx, ball_dy
    ball.x += ball_dx
    ball.y += ball_dy
    if ball.colliderect(player):
        ping1.play()
        ball_dx *= -1.5
        return ball_dx, ball_dy
    if ball.colliderect(opponent):
        ping2.play()
        ball_dx *= -1.5
        return ball_dx, ball_dy
    if ball.top <= 0:
        ping3.play()
        ball_dy *= -1.15
    if ball.bottom >= screen_height:
        ping4.play()
        ball_dy *= -1.15
    if ball.left <= 0:
        player_score += 1
        if player_score >= 5:
            state = 'gameover'
            return 3,3
        ball_dx, ball_dy = reset_ball(1)
        state = 'goal'
        goal.play()
    if ball.right >= screen_width:
        opponent_score += 1
        if opponent_score >= 5:
            state = 'gameover'
            return 0,0
        ball_dx, ball_dy = reset_ball(-1)
        state = 'goal'
        goal.play()
    ball_dx = min(ball_dx, 200)
    return ball_dx, ball_dy

def draw_shapes():
    global state, pa_b
    screen.blit(field_img,(0,0),)
    pygame.draw.aaline(screen, (255,255,255), (screen_width/2,0), (screen_width/2,screen_height))
    screen.blit(font.render(str(opponent_score),True, (0,0,255)), (20, 20))
    screen.blit(font.render(str(player_score),True, (255,0,0)), (screen_width-40, 20))
    if state == 'play':
        pygame.draw.ellipse(screen,(255,255,255),ball)
        pygame.draw.rect(screen,(255,255,255),player)
        pygame.draw.rect(screen,(0,0,0),opponent)
    if state == 'pause':
        pygame.draw.ellipse(screen,(255,255,255),ball)
        pygame.draw.rect(screen,(255,255,255),player)
        pygame.draw.rect(screen,(0,0,0),opponent)
        screen.blit(font.render(str("PAUSE!"),True, (255,0,255)), (screen_width/2 - 62, screen_height/2 - 15))
    if state == 'goal':
        screen.blit(font.render(str("GOAL!"),True, (255,0,255)), (screen_width/2 - 50, screen_height/2))
        pygame.display.flip()
        sleep(.2)
        state = 'play'
    if state == 'gameover':
        screen.blit(font.render(str("GAME OVER!"),True, (255,0,255)), (screen_width/2 - 100, screen_height/2-100))
        pa_b = screen.blit(font.render(str("PLAY AGAIN?"),True, (255,0,255)), (screen_width/2 - 100, screen_height/2))

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_DOWN:
                player_spd = 7
            if event.key == pygame.K_UP:
                player_spd = -7
            if event.key == pygame.K_SPACE:
                if state == 'play':
                    state = 'pause'
                elif state == 'pause':
                    state = 'play'
            # Easy gameover state for testing
            # if event.key == pygame.K_w:
            #     state = 'gameover'
            if event.key == pygame.K_ESCAPE:
                pygame.quit()
                sys.exit()

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            pos = pygame.mouse.get_pos()
            if pa_b.collidepoint(pos):
                player_score,opponent_score = 0,0
                state = 'play'
                reset_ball(-1)
        if event.type == pygame.KEYUP:
            if event.key in (pygame.K_UP, pygame.K_DOWN):
                player_spd = 0

    ball_dx, ball_dy = ball_animation(ball_dx, ball_dy)
    player_animation()
    opponent_animation()

    draw_shapes()
    pygame.display.flip()
    clock.tick(144)


def jobGetDemand(self,):
    """ Look through the jobs table and get the demand - minimum and maximum
    number of workers requested, if new workers are to be allocated, if there
    are any untended dead workers, for all running jobs.

    Parameters:
    ----------------------------------------------------------------
    retval:      list of ClientJobsDAO._jobs.jobDemandNamedTuple nametuples
                  containing the demand - min and max workers,
                  allocate_new_workers, untended_dead_workers, num_failed_workers
                  for each running (STATUS_RUNNING) job. Empty list when there
                  isn't any demand.

    """
    rows = self._getMatchingRowsWithRetries(
      self._jobs, dict(status=self.STATUS_RUNNING),
      [self._jobs.pubToDBNameDict[f]
       for f in self._jobs.jobDemandNamedTuple._fields])

    return [self._jobs.jobDemandNamedTuple._make(r) for r in rows]


import os
from PIL import Image
from datetime import datetime

def gif_creat(directory_files):

    directory_files.sort(key=lambda x: int(x.split(".")[0]))
    frame_list = []

    for frame_number in directory_files:
        frame = Image.open(os.path.join('homer', frame_number))
        frame_list.append(frame)

    gif_name = F'gif_{datetime.now().strftime("%d_%m_%Y_%H_%M_%S")}.gif'

    frame_list[0].save(
        f'gif_save/{gif_name}',
        save_all=True,
        append_images=frame_list[1:],
        optimize=True,
        duration=100,
        loop=0
    )

    return gif_name


#!/usr/bin/env python3

import io
import json
import socket
import yaml

hosts = ('drive.google.com', 'mail.google.com', 'google.com')
filename = 'hosts_state.json'

try:
    f = open(filename)
    data = json.load(f)
    f.close()

except FileNotFoundError:
    data = []
    for one_host in hosts:
        data.append ({one_host: '0.0.0.0'})

data_out = []
for [[host, addr]] in [ x.items() for x in data]:
    new_addr = socket.gethostbyname(host)
    if addr != new_addr:
        print('ERROR  {} IP mismatch: {} {}.'.format(host, addr, new_addr))
        # [ERROR] <URL сервиса> IP mismatch: <старый IP> <Новый IP>.
    data_out.append({host: new_addr})

with open(filename, "w") as outfile:
    json.dump(data_out, outfile)
    print ('Store json')

with io.open('hosts_state.yaml', 'w', encoding='utf8') as outfile:
    yaml.dump(data_out, outfile,default_flow_style=False, allow_unicode=True)
    print ('Store yaml')


import os

os.system('cls')

# ver 1
for n in range(1, 1000):
    b = bin(n)[2:]  # 1. Строится двоичная запись числа N
    cnt = b.count('1')
    if cnt % 2 == 0:
        b += '0'
        b = '10' + b[2:]
    else:
        b += '1'
        b = '11' + b[2:]
    r = int(b, 2)
    if r > 40:
        print(n)
        break

# ver 2
# n = 1
# while True:
#     pass
#     pass
#     if r > 40:
#         print(n)
#         break
#     n += 1