# Design/Program : Mehmet Berat Şenel ( mehmetberat.com )
import pygame
import random

pygame.init()

my_font = pygame.font.SysFont('Arial Bold', 30)

gameDisplay = pygame.display.set_mode((1280,720))
pygame.display.set_caption('SpaceShip (beta v1)')
programIcon = pygame.image.load('.icon/spaceship.png')
width = gameDisplay.get_width()
height = gameDisplay.get_height()

pygame.display.set_icon(programIcon)

clock = pygame.time.Clock()

crashed = False
shipa=pygame.image.load('.img/ship1.png')
shipb=pygame.image.load('.img/ship2.png')
monstera=pygame.image.load('.img/monstera.png')
monsterb=pygame.image.load('.img/monsterb.png')
bg=pygame.image.load('.img/background.png')
blltimg=pygame.image.load('.img/lazer.png')
mainbg=pygame.image.load(".img/mainbg.png")
overbg=pygame.image.load(".img/overbg.png")

LaserSound=pygame.mixer.Sound(".sound/laser.wav")
GameMusic=pygame.mixer.Sound(".sound/Kubbi - Digestive biscuit.wav")
MainMusic=pygame.mixer.Sound(".sound/c152 - Night Mission.wav")
BombSound=pygame.mixer.Sound(".sound/Bomb.wav")
CreditMusic=pygame.mixer.Sound(".sound/man-is-he-mega-glbml-22045.wav")

lightlist=list()
bullets=list()
monsters=list()
shipx=10
shipy=300
counter=0
up=False
down=False
left=False
right_=False
score=0
play=2
GameMusicPlay=0
MainMusicPlay=0
CreditMusicPlay=0
level=0
speed=-4

def GameOver():
    global GameMusicPlay,MainMusicPlay,CreditMusicPlay,play,crashed
    if CreditMusicPlay==0:
        GameMusicPlay=0
        MainMusicPlay=0
        CreditMusicPlay=1
        pygame.mixer.stop()
        pygame.mixer.Sound.play(CreditMusic)
    mouse = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        if event.type == pygame.MOUSEBUTTONDOWN:
              if 550 <= mouse[0] <= 730 and 600 <= mouse[1] <= 620:
                play=2
    gameDisplay.blit(overbg,(0,0))
    my_font = pygame.font.SysFont('Arial Bold', 70)
    text_surface = my_font.render('Score : '+str(score), True, (178, 238, 0))
    text_surface1 = my_font.render('Level  : '+str(level), True, (178, 238, 0))
    my_font1 = pygame.font.SysFont('Arial Bold', 30)
    text_surface6 = my_font1.render('< BACK TO MENU >', True, (178, 238, 0))
    gameDisplay.blit(text_surface, (500,10+300))
    gameDisplay.blit(text_surface1, (500,100+300))
    gameDisplay.blit(text_surface6, (550,300+300))

def credit():
    global GameMusicPlay,MainMusicPlay,CreditMusicPlay,play,crashed
    if CreditMusicPlay==0:
        GameMusicPlay=0
        MainMusicPlay=0
        CreditMusicPlay=1
        pygame.mixer.stop()
        pygame.mixer.Sound.play(CreditMusic)
    mouse = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        if event.type == pygame.MOUSEBUTTONDOWN:
              if 550 <= mouse[0] <= 730 and 600 <= mouse[1] <= 620:
                play=2
    gameDisplay.fill((22,22,22))
    text_surface = my_font.render('Programmer / Game Designer', True, (178, 238, 0))
    text_surface1 = my_font.render('* Mehmet Berat ŞENEL ( mehmetberat.com )', True, (178, 238, 0))
    text_surface2 = my_font.render('Sounds', True, (178, 238, 0))
    text_surface3 = my_font.render('* c152 - Night Mission Synthwave', True, (178, 238, 0))
    text_surface4 = my_font.render('* Kubbi - Digestive biscuit', True, (178, 238, 0))
    text_surface5 = my_font.render('* Man is He Mega - GLBML by GeoffreyBurch', True, (178, 238, 0))
    text_surface6 = my_font.render('< BACK TO MENU >', True, (178, 238, 0))
    gameDisplay.blit(text_surface, (400,10+200))
    gameDisplay.blit(text_surface1, (450,60+200))
    gameDisplay.blit(text_surface2, (400,110+200))
    gameDisplay.blit(text_surface3, (450,160+200))
    gameDisplay.blit(text_surface4, (450,210+200))
    gameDisplay.blit(text_surface5, (450,260+200))
    gameDisplay.blit(text_surface6, (550,300+300))

def MainMenu():
    global GameMusicPlay,MainMusicPlay,my_font,play,mainbg,CreditMusicPlay,crashed,lightlist,bullets,monsters,shipx,shipy,counter,score,level,speed,up,down,left,right_
    lightlist=list()
    bullets=list()
    monsters=list()
    shipx=10
    shipy=300
    counter=0
    score=0
    level=0
    speed=-4
    up=False
    down=False
    left=False
    right_=False
    if MainMusicPlay==0:
        GameMusicPlay=0
        MainMusicPlay=1
        CreditMusicPlay=0
        pygame.mixer.stop()
        pygame.mixer.Sound.play(MainMusic)
    mouse = pygame.mouse.get_pos()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        if event.type == pygame.MOUSEBUTTONDOWN:
              if width/2-90 <= mouse[0] <= width/2+50 and height/2-50 <= mouse[1] <= height/2+30:
                play=0
        if event.type == pygame.MOUSEBUTTONDOWN:
              if width/2-150 <= mouse[0] <= width/2+120 and height/2+50 <= mouse[1] <= height/2+100:
                play=1
    gameDisplay.fill((0,0,0))
    gameDisplay.blit(mainbg,(0,0))

def Game():
    global crashed,up,down,left,right_,GameMusicPlay,MainMusicPlay,CreditMusicPlay
    if GameMusicPlay==0:
        GameMusicPlay=1
        MainMusicPlay=0
        CreditMusicPlay=0
        pygame.mixer.stop()
        pygame.mixer.Sound.play(GameMusic)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            crashed = True
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                up=True
            elif event.key == pygame.K_LEFT:
                left=True
            elif event.key == pygame.K_DOWN:
                down=True
            elif event.key == pygame.K_RIGHT:
                right_=True
            elif event.key== pygame.K_x:
                if level>=5:
                    bullets.append((shipx+68,shipy+15))
                    bullets.append((shipx+68,shipy+70))
                else:
                    bullets.append((shipx+68,shipy+40))
                pygame.mixer.Sound.play(LaserSound)
        if event.type==pygame.KEYUP:
            if event.key == pygame.K_UP:
                up=False
            elif event.key == pygame.K_LEFT:
                left=False
            elif event.key == pygame.K_DOWN:
                down=False
            elif event.key == pygame.K_RIGHT:
                right_=False

    gameDisplay.fill((0,0,0))
    BGControl()
    ship(shipx,shipy)
    Mnstrcrt()
    bullet()
    text_surface = my_font.render('Score : '+str(score), True, (178, 238, 0))
    text_surface1 = my_font.render('Level : '+str(level), True, (178, 238, 0))
    gameDisplay.blit(text_surface, (10,10))
    gameDisplay.blit(text_surface1, (10,50))

def BGCreater():
    rdcount=1
    for i in range(rdcount):
        rdx=random.randint(1,10000)
        rdy=random.randint(1,720)
        lightlist.append((rdx+1280,rdy))

def BGControl():
    for i in range(len(lightlist)):
        gameDisplay.blit(bg,lightlist[i])
        lightlist[i]=(lightlist[i][0]-3,lightlist[i][1])
    BGCreater()

def bullet():
    global speed,score
    for i in range(len(bullets)):
        try:
            gameDisplay.blit(blltimg,bullets[i])
            bullets[i]=(bullets[i][0]+10+level,bullets[i][1])
            for cords in monsters:
                if bullets[i][1] in list(range(cords[1],cords[1]+100)) and cords[0]<bullets[i][0]:
                    pygame.mixer.Sound.play(BombSound)
                    bullets.remove(bullets[i])
                    monsters.remove(cords)
                    score+=level
                    speed=-level*0.5-3
        except:
            pass

def monster(x,y):
    global counter,speed
    if counter<4:
        gameDisplay.blit(monstera,(x,y))
    else:
        gameDisplay.blit(monsterb,(x,y))

def Mnstrcrt():
    global play
    MonsterControl()
    for i in range(len(monsters)):
        if monsters[i][0]<0:
            play=3
        monster(monsters[i][0],monsters[i][1])
        monsters[i]=(monsters[i][0]+speed,monsters[i][1])

def MonsterControl():
    global level
    if len(monsters)==0:
        level+=1
        for i in range(random.randint(level+2,level+5)):
            monsters.append((random.randint(10,500)+1280,random.randint(20,700)))

def ship(x,y):
    global counter,up,down,left,right_,shipx,shipy
    if counter<4:
        gameDisplay.blit(shipa,(x,y))
        counter+=1
    elif counter==9:
        gameDisplay.blit(shipb,(x,y))
        counter=0
    else:
        gameDisplay.blit(shipb,(x,y))
        counter+=1
    if up:
        shipy-=level+5
    if down:
        shipy+=level+5
    if left:
        shipx-=level+5
    if right_:
        shipx+=level+5

while not crashed:

    if play==0:
        Game()
    elif play==1:
        credit()
    elif play==2:
        MainMenu()
    else:
        GameOver()

    pygame.display.update()
    clock.tick(60)


from aqml.cheminfo.core import *

from rdkit import Chem
from rdkit.Chem.Draw import IPythonConsole
from rdkit.Chem import Draw

from openeye import oechem
from aqml.cheminfo.oechem.oechem import *

from IPython.display import SVG, display, HTML
from rdkit.Chem import AllChem as Chem
from rdkit.Chem.Draw import rdMolDraw2D
from rdkit.Chem.Draw import DrawingOptions

from rdkit.Chem import rdDepictor
from rdkit.Chem.Draw import rdMolDraw2D

import tempfile as tpf

import imolecule as imol

#DrawingOptions.atomLabelFontSize = 105
#DrawingOptions.dotsPerAngstrom = 2000
#DrawingOptions.bondLineWidth = 3.0

T,F = True,False

class draw_rdkit(object):

    def __init__(self): #, objs, istereo=False, woH=True, wo3d=False):
        #self.objs = objs
        #self.istereo = istereo
        #self.woH = woH
        #self.wo3d = wo3d
        #self.wo3d = wo3d
        return

    @staticmethod # @classmethod
    def str2mol(objs, istereo=False, woH=True, wo3d=False):
        mols = []
        labs = []
        if not isinstance(objs, (list,tuple)): objs=[objs]
        for obj in objs:
            if type(obj) is str:
                if os.path.exists(obj):
                    mol = Chem.MolFromMolFile(obj, removeHs=woH)
                    if wo3d:
                        string = Chem.MolToSmiles(mol, isomericSmiles=istereo)
                        mol = Chem.MolFromSmiles(string)
                else:
                    mol = Chem.MolFromSmiles(obj)
                labs.append( obj )
            elif type(obj) is Chem.rdchem.Mol:
                mol = obj
                labs.append( Chem.MolToSmiles(mol) )
            else:
                raise Exception('#ERROR: input not supported')
            mols.append(mol)
        return mols, labs

    @staticmethod # @classmethod
    def viewm0(strings, size=(200,200)):
        return Draw.MolsToImage(draw_rdkit.str2mol(strings), includeAtomNumbers=True, subImgSize=size)

    @staticmethod # @classmethod
    def viewm(string,molSize=(450,150),woH=True,wo3d=False,kekulize=True,atsh=[],bsh=[],colors=[]):
        """
        vars
        atsh : atoms to be highlighted (list)
        bsh: bonds to be highlighted (list)
        woH: without H atoms displayed
        wo3d: without 3d coordinates embeded
        """
        mol = draw_rdkit.str2mol(string,woH=woH,wo3d=wo3d)[0][0]
        mc = Chem.Mol(mol.ToBinary())
        if kekulize:
            try:
                Chem.Kekulize(mc)
            except:
                mc = Chem.Mol(mol.ToBinary())
        if not mc.GetNumConformers():
            rdDepictor.Compute2DCoords(mc)
        drawer = rdMolDraw2D.MolDraw2DSVG(molSize[0],molSize[1])

        opts = drawer.drawOptions()
        for i in range(mol.GetNumAtoms()):
            opts.atomLabels[i] = mol.GetAtomWithIdx(i).GetSymbol()+str(i)

        opts.legendFontSize=16

        _colors={ (1,0,0), (0,1,0), (0,0,1), (1,0,1)}

        if len(colors) > 0:
            drawer.DrawMolecule(mc,highlightAtoms=atsh,highlightBonds=bsh,highlightAtomColors=colors)
        else:
            drawer.DrawMolecule(mc,highlightAtoms=atsh,highlightBonds=bsh)

        drawer.FinishDrawing()
        svg = drawer.GetDrawingText()
        # It seems that the svg renderer used doesn't quite hit the spec.
        # Here are some fixes to make it work in the notebook, although I think
        # the underlying issue needs to be resolved at the generation step
        return SVG( svg.replace('svg:','') )

    @staticmethod # @classmethod
    def viewms(objs,wo3d=F,nmr=8,molSize=(100,80),wlgd=T,wlgd_text='smiles', labels=None, \
               wia=T,woH=T,kekulize=T,atsh=[],bsh=[],colors=[],filename=None):
        """
        vars
        atsh : atoms to be highlighted (list)
        """
        mols, strings = draw_rdkit.str2mol(objs,woH=woH)
        mcs = []
        _labels = []
        nat = 0
        nm = len(mols)
        smis = []
        for mol in mols:
            labels_i = [ chemical_symbols[ai.GetAtomicNum()]+'%d'%(ai.GetIdx()+1) for ai in mol.GetAtoms() ]
            nat += len(labels_i)
            _labels += labels_i
            mc = Chem.Mol(mol.ToBinary())
            if kekulize:
                try:
                    Chem.Kekulize(mc)
                except:
                    mc = Chem.Mol(mol.ToBinary())
            c2d = F
            if mc.GetNumConformers():
                if wo3d:
                    c2d = T
            else:
                c2d = T
            if c2d: rdDepictor.Compute2DCoords(mc)
            smis.append( Chem.MolToSmiles(mc) )
            mcs.append(mc)
        #print('labels=',labels)

        molsPerRow = nmr #5
        subImgSize= molSize

        nRows = len(mols) // molsPerRow
        if len(mols) % molsPerRow:
            nRows += 1
        fsize = (molsPerRow * subImgSize[0], nRows * subImgSize[1])

        dw, dh = 0, 0
        drawer = rdMolDraw2D.MolDraw2DSVG(fsize[0]+dw,fsize[1]+dh, subImgSize[0], subImgSize[1])

        opts = drawer.drawOptions()
        ## [bad news] opts seems to be able to accept only the first `na1 labels (where na1=len(mols[0]))
        #for i in range(nat):
        #    opts.atomLabels[i] = labels[i]

        if labels:
            labs = labels
        else:
            if wlgd_text in ['id']:
                labs = [ str(i+1) for i in range(nm) ] #rows*cols) ]
            elif wlgd_text in ['smiles',]:
                labs = smis
            elif wlgd_text in ['file','filename']:
                assert len(fs) > 1, '#ERROR: input objs are not files!!'
                labs = [ fi.split('/')[-1] for fi in fs ]
            else:
                raise Exception('invalid `wlgd_text')

        drawer.DrawMolecules(mcs, legends=labs)

        drawer.FinishDrawing()
        svg = drawer.GetDrawingText()
        # It seems that the svg renderer used doesn't quite hit the spec.
        # Here are some fixes to make it work in the notebook, although I think
        # the underlying issue needs to be resolved at the generation step

        if filename is not None:
            open(filename+'.svg','w').write(svg)
            try:
                import cairosvg
                cairosvg.svg2pdf(url='%s.svg'%filename, write_to='%s.pdf'%filename)
            except:
                raise Exception('#ERROR: svg to pdf failed, as cairosvg seems to be not installed?')
        return SVG( svg.replace('svg:','') )

class draw_oechem(object):

    def __init__(self): #, objs, istereo=False, woH=True, wo3d=False):
        #self.objs = objs
        #self.istereo = istereo
        #self.woH = woH
        #self.wo3d = wo3d
        return

    @staticmethod # @classmethod
    def str2mol(objs, istereo=False, woH=True, wo3d=False):
        mols = []
        smis = []
        fs = []
        if type(objs) is str: objs=[objs]
        for obj in objs:
            if type(obj) is str:
                if os.path.exists(obj):
                    fs.append(fs)
                    mol = sdf2oem(obj) #Chem.MolFromMolFile(obj, removeHs=woH)
                    #print('++mol=',mol)
                    #assert iok, '#ERROR: sdf2oem() failed??'
                    smi = oem2can(mol) # Chem.MolToSmiles(mol, isomericSmiles=istereo)
                    if wo3d:
                        iok, mol = smi2oem(smi)
                        assert iok, '#ERROR: smi2oem() failed?'
                else:
                    smi = obj
                    iok, mol = smi2oem(obj)
                    assert iok, '#ERROR: smi2oem() failed?'

            elif type(obj) is oechem.OEGraphMol:
                mol = obj
                smi = oem2can(mol)
            else:
                raise Exception('#ERROR: input not supported')
            mols.append(mol)
            smis.append( obj )
        return mols, smis, fs

    @staticmethod # @classmethod
    def viewms(objs, nmr=8, molSize=[100,80], woH=T, wo3d=F, wlgd_text='smiles',\
               wlgd=T, wia=F, filename=None, tdir='/tmp/'):

        """
        vars
        ====================
        nmr: num of mol per row
        woH: without Hydrogens displayed, T/F
        wo3d: without 3d coordinates? T/F
        wlgd: with legend displayed? T/F
        wlgd_text: 'smiles' or 'idx'
        wia: with idx of atom shown? T/F
        """
        mols, smis, fs = draw_oechem.str2mol(objs,woH=woH,wo3d=wo3d)
        nm = len(mols)
        cols = nmr #4 if nm < nmr else nmr # num mol per row
        rows = int(nm/cols) if nm%cols==0 else int(nm/cols)+1

        image = oedepict.OEImage(cols*molSize[0], rows*molSize[1])

        grid = oedepict.OEImageGrid(image, rows, cols)

        opts = oedepict.OE2DMolDisplayOptions(grid.GetCellWidth(), \
                           grid.GetCellHeight(), oedepict.OEScale_AutoScale)

        if wlgd_text in ['id']:
            labs = [ str(i+1) for i in range(nm) ] #rows*cols) ]
        elif wlgd_text in ['smiles',]:
            labs = smis
        elif wlgd_text in ['file','filename']:
            assert len(fs) > 1, '#ERROR: input objs are not files!!'
            labs = [ fi.split('/')[-1] for fi in fs ]
        else:
            raise Exception('invalid `wlgd_text')

        for i in range(nm):
            mol = mols[i]
            #print('mol=',mol)
            oedepict.OEPrepareDepiction(mol)

            irow, icol = int(i/cols)+1, i%cols+1
            cell = grid.GetCell(irow,icol)

            if wlgd:
                mol.SetTitle(labs[i])

            opts.SetAtomVisibilityFunctor(oechem.OEIsTrueAtom())  # explicitly set the default

            font = oedepict.OEFont()
            font.SetSize(16)
            font.SetStyle(oedepict.OEFontStyle_Normal) #_Bold)
            font.SetColor(oechem.OEDarkGreen)
            opts.SetAtomPropLabelFont(font)

            if wia:
                opts.SetAtomPropertyFunctor(oedepict.OEDisplayAtomIdx())

            opts.SetAtomLabelFont(font)
            #opts.SetAtomLabelFontScale(1.5)

            opts.SetAtomPropLabelFont(font) # atom idx
            opts.SetAtomPropLabelFontScale(2) # atom idx

            opts.SetTitleLocation(oedepict.OETitleLocation_Bottom)
            opts.SetTitleHeight(10.0)

            disp = oedepict.OE2DMolDisplay(mol, opts)
            clearbackground = True
            oedepict.OERenderMolecule(cell, disp, not clearbackground)

        save = F # save as pdf
        if filename is not None:
            tf = filename+'.svg'
            save = T
        else:
            tf = tpf.NamedTemporaryFile(dir=tdir).name + '.svg'
        oedepict.OEWriteImage(tf, image)

        if save:
            try:
                import cairosvg
                cairosvg.svg2pdf(url='%s.svg'%filename, write_to='%s.pdf'%filename)
            except:
                raise Exception('#ERROR: svg to pdf failed, as cairosvg seems to be not installed?')

        return SVG(tf)

class draw_imol(object):
    """
    draw 3d molecule by imolecule
    """

    def __init__(self):
        return

    @staticmethod
    def html(ms,fmt,size=(240,240),nmr=6):
        renders = (imol.draw(m,fmt,size=size,display_html=False) for m in ms)
        columns = ('
{}
'.format(r) for r in renders)
        return HTML('
{}
'.format("".join(columns)))

    @staticmethod
    def viewms(objs,molSize=(160,160),nmr=6):

        if not isinstance(objs, (tuple,list)):
            objs = [objs]

        # convert to a file format recognizable by imolecule, i.e., sdf
        ms = []
        for obj in objs:
            typ = type(obj)
            if typ is Chem.rdchem.Mol:
                ms.append( Chem.MolToMolBlock(obj) )
            elif typ is str: #oechem.OEGraphMol:
                if os.path.exists(obj):
                    assert obj[-3:] in ['sdf','mol'], '#ERROR: file format not supported'
                    ms.append( ''.join(open(obj).readlines()) )
                else:
                    print(' ** assume smiles string ')
                    ms.append( Chem.MolToMolBlock( Chem.MolFromSmiles(obj) ) )
        if len(ms) == 1:
            return [ imol.draw(ms[0],'sdf',size=molSize) ]
        else:
            return draw_imol.html(ms,'sdf',size=molSize,nmr=nmr)
            #raise Exception('not know what to do next!')

import ase
import ase.io as aio
from ase.visualize import view
from tempfile import NamedTemporaryFile as ntf

class draw_ase(object):

    def __init__(self):
        return

    @staticmethod
    def viewms(obj):
        """ return the html representation the atoms object as string """
        renders = []
        ms = []
        if isinstance(obj, ase.Atoms):
            ms.append(obj)
        elif isinstance(obj, (tuple,list)):
            for oi in obj:
                ms.append( aio.read(f) )
        else:
            raise Exception('##')
        for atoms in ms:
            with ntf('r+', suffix='.html') as fo:
                atoms.write(fo.name, format='html')
                fo.seek(0)
                renders.append( fo.read() )
        columns = ('
{}
'.format(r) for r in renders)
        return HTML('
{}
'.format("".join(columns)))


# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# **************************************************************************/

"""
:info:
    Interface class for collecting and storing necessary parameters from ROS parameter server.

"""

import sys
import rospy
import socket
from franka_core_msgs.msg import JointLimits

def _log_networking_error():
    print ("Failed to connect to the ROS parameter server!\n"
           "Please check to make sure your ROS networking is "
           "properly configured:\n")
    sys.exit()

class RobotParams(object):
    """
    Interface class for essential ROS parameters on the Franka Emika Panda robot.
    """

    def __init__(self):

        if self._robot_in_simulation():
            self._in_sim = True
            self._ns = "/panda_simulator"
            rospy.loginfo("Robot control running in Simulation Mode!")
            self._robot_ip="sim"
        else:
            self._ns = "/franka_ros_interface"
            self._in_sim = False
            self._robot_ip = self.get_robot_ip()

        self._robot_name = self.get_robot_name()

    def get_base_namespace(self):
        return self._ns

    def _robot_in_simulation(self):
        sim = False
        try:
            sim = rospy.get_param("/SIMULATOR_")
        except KeyError:
            sim = False
        except (socket.error, socket.gaierror):
            _log_networking_error()

        return sim

    def get_neutral_pose(self):
        """
        Get neutral pose joint positions from parameter server
        (/robot_config/neutral_pose)

        :return: Joint positions of the robot as defined in parameter server.
        :rtype: [type]
        """
        try:
            neutral_pose = rospy.get_param("/robot_config/neutral_pose")
        except KeyError:
            rospy.logerr("RobotParam: robot_ip cannot detect neutral joint pos."
                         " under param /franka_control/neutral_pose")
        except (socket.error, socket.gaierror):
            _log_networking_error()

        return neutral_pose

    def get_robot_ip(self):
        robot_ip = None
        try:
            robot_ip = rospy.get_param("/franka_control/robot_ip")
        except KeyError:
            try:
                robot_ip = rospy.get_param("/robot_config/robot_ip")
            except KeyError:
                rospy.logerr("RobotParam: robot_ip cannot detect robot ip."
                             " under param /robot_ip")
        except (socket.error, socket.gaierror):
            _log_networking_error()

        return robot_ip

    def get_joint_names(self):
        """
        Return the names of the joints for the robot from ROS parameter
        server (/robot_config/joint_names).

        :rtype: [str]
        :return: ordered list of joint names from proximal to distal
                 (i.e. shoulder to wrist). joint names for limb
        """
        joint_names = list()
        try:
            joint_names = rospy.get_param("/robot_config/joint_names")
        except KeyError:
            rospy.logerr("RobotParam: get_joint_names cannot detect joint_names for arm")
        except (socket.error, socket.gaierror):
            _log_networking_error()
        return joint_names

    def get_gripper_joint_names(self):
        """
        Return the names of the joints for the gripper from ROS
        parameter server (/gripper_config/joint_names).

        :rtype: [str]
        :return: ordered list of joint names
        """

        joint_names = list()
        try:
            joint_names = rospy.get_param("/gripper_config/joint_names")
        except KeyError:
            rospy.loginfo("RobotParam: get_gripper_joint_names cannot detect joint_names for gripper.")
            return None
        except (socket.error, socket.gaierror):
            _log_networking_error()
        return joint_names

    def get_robot_name(self):
        """
        Return the name of class of robot from ROS parameter server.
        (/robot_config/arm_id)

        :rtype: str
        :return: name of the robot
        """
        robot_name = None
        try:
            robot_name = rospy.get_param("/robot_config/arm_id")
        except KeyError:
            rospy.logerr("RobotParam: get_robot_name cannot detect robot name"
                         " under param /robot_config/arm_id")
        except (socket.error, socket.gaierror):
            _log_networking_error()
        return robot_name

    def get_joint_limits(self):
        """
        Get joint limits as defined in ROS parameter server
        (/robot_config/joint_config/joint_velocity_limit)

        :return: Joint limits for each joints
        :rtype: franka_core_msgs.msg.JointLimits
        """

        lims = JointLimits()
        lims.joint_names = self.get_joint_names()

        try:
            vel_lim = rospy.get_param("/robot_config/joint_config/joint_velocity_limit")
        except KeyError:
            rospy.logerr("RobotParam: get_joint_limits cannot detect robot joint velocity limits"
                         " under param /robot_config/joint_config/joint_velocity_limit")
        except (socket.error, socket.gaierror):
            _log_networking_error()

        try:
            pos_min_lim = rospy.get_param("/robot_config/joint_config/joint_position_limit/lower")
        except KeyError:
            rospy.logerr("RobotParam: get_joint_limits cannot detect robot joint position lower limits"
                         " under param /robot_config/joint_config/joint_position_limit/lower")
        except (socket.error, socket.gaierror):
            _log_networking_error()

        try:
            pos_max_lim = rospy.get_param("/robot_config/joint_config/joint_position_limit/upper")
        except KeyError:
            rospy.logerr("RobotParam: get_joint_limits cannot detect robot joint position upper limits"
                         " under param /robot_config/joint_config/joint_position_limit/upper")
        except (socket.error, socket.gaierror):
            _log_networking_error()

        try:
            eff_lim = rospy.get_param("/robot_config/joint_config/joint_effort_limit")
        except KeyError:
            rospy.logerr("RobotParam: get_joint_limits cannot detect robot joint torque limits"
                         " under param /robot_config/joint_config/joint_effort_limit")
        except (socket.error, socket.gaierror):
            _log_networking_error()

        try:
            acc_lim = rospy.get_param("/robot_config/joint_config/joint_acceleration_limit")
        except KeyError:
            rospy.logerr("RobotParam: get_joint_limits cannot detect robot joint acceleration limits"
                         " under param /robot_config/joint_config/joint_acceleration_limit")
        except (socket.error, socket.gaierror):
            _log_networking_error()

        for i in range(len(lims.joint_names)):
            lims.position_upper.append(pos_max_lim[lims.joint_names[i]])
            lims.position_lower.append(pos_min_lim[lims.joint_names[i]])
            lims.velocity.append(vel_lim[lims.joint_names[i]])
            lims.accel.append(acc_lim[lims.joint_names[i]])
            lims.effort.append(eff_lim[lims.joint_names[i]])

        return lims

if __name__ == '__main__':

    rp = RobotParams()
    # print rp.__dict__
    print(rp.get_robot_ip())
    print(rp.get_robot_name())
    print(rp.get_joint_names())


import requests
from bs4 import BeautifulSoup
import schedule
import time
import re

def scrape_website():
    url = 'https://www.topstocktips.com/tipbn'
    response = requests.get(url)
    soup = BeautifulSoup(response.content, 'html.parser')

    # Get the page title
    title = soup.title.text
    print(f"Page title: {title}")

    # Get the compensation message
    compensation_element = soup.find('span', text=re.compile('We have been compensated up to'))
    if compensation_element is not None:
        compensation_text = compensation_element.text
        print(f"Compensation message: {compensation_text}")

schedule.every().minute.do(scrape_website)

while True:
    schedule.run_pending()
    time.sleep(1)


from bisect import bisect
from enum import Enum
from hashlib import md5
from typing import List, Dict, Optional

# Default amount of replicas per node
RING_REPLICAS = 16
NODE_ID = 'node_id'
NODE_WGT = 'weight'
NODE_VN = 'v_nodes'

def _default_hash_fn(key) -> int:
    return int(md5(str(key).encode("utf-8")).hexdigest(), 16)

class RingObjectType(Enum):
    OBJ = 1
    ID = 2

class RingHash:
    """
    The basic idea is that each server is mapped to a point on
    a circle (You can think of the circle as all integers 0 ..2³²-1.)
    with a hash function. To lookup the server for a given key, you hash
    the key and find that point on the circle.
    Then you scan forward until you find the first hash value for any server.
    In practice, each server appears multiple times on the circle. \
    These extra points are called “virtual nodes”, or “vnodes”  or replicas.

    Node look up take O(log(n)) time.
    ring hash should be used if number of nodes quite stable, in other case
    highest random weight (HRW) hashing preferable
    """

    def __init__(self, nodes=None, replicas_cnt=None, hash_fn=None):
        """
        create ring hash structure

        :param nodes: list is nodes ids/ configurations
        :param replicas_cnt: number of replicas/vNodes of each node
        :param hash_fn: a hash function

        Examples:
        >>> from hashing.ring_hash_v2 import RingHash
        >>> ring = RingHash([3, 6, 9], 1)
        >>> node1 = ring.get(3)
        >>> node2 = ring.get(100)
        """
        self._keys = []
        self._nodes = {}
        self._ring = {}

        if hash_fn and not hasattr(hash_fn, "__call__"):
            raise TypeError("hash_fn should be a callable function")
        self._hash_fn = hash_fn or _default_hash_fn
        self._default_replicas = replicas_cnt or RING_REPLICAS

        self.add(nodes)

    def _get_hash(self, node_name: str, w: int) -> int:
        key = f"{node_name}-{w}"
        return self._hash_fn(key)

    def _create_node(self, node) -> Dict[str, any]:
        if isinstance(node, str) or isinstance(node, int):
            node = {NODE_ID: node}
        elif not isinstance(node, dict):
            raise ValueError(
                f"node should be a string or a dict got {type(node)}"
            )
        if NODE_ID not in node:
            raise ValueError(
                f"'{NODE_ID}' property should be present in dict"
            )
        if NODE_WGT not in node:
            node[NODE_WGT] = 1
        elif not isinstance(node[NODE_WGT], int) or node[NODE_WGT] < 1:
            raise ValueError(
                f"node weight '{node[NODE_WGT]}' should be int and be grate than 0"
            )
        if NODE_VN not in node:
            node[NODE_VN] = self._default_replicas
        elif not isinstance(node[NODE_VN], int) or node[NODE_VN] < 1:
            raise ValueError(
                f"node replicas count '{node[NODE_VN]}' should be int and be grate than 0"
            )
        return node

    def _add_nodes(self, nodes: List[Dict[str, any]]):
        """add nodes into the ring"""
        _nodes = []
        for node in nodes:
            _node = self._create_node(node)
            if _node[NODE_ID] in self._nodes:
                raise ValueError(
                    f"node with the name {_node[NODE_ID]} already had been added"
                )
            _nodes.append(_node)

        for node in _nodes:
            node_id = node[NODE_ID]
            self._nodes[node_id] = node
            for w in range(0, node[NODE_VN] * node[NODE_WGT]):
                _hash = self._get_hash(node_id, w)
                self._ring[_hash] = node_id
        self._keys = sorted(self._ring.keys())

    def _get_node_id(self, node_id: str) -> str:
        """return node Id for given key"""
        _hash = self._hash_fn(node_id)
        inx = bisect(self._keys, _hash)
        if inx == len(self._keys):
            inx = 0
        return self._ring[self._keys[inx]]

    def remove(self, node_id: str) -> Dict[str, any]:
        """remove node from the ring"""
        if node_id not in self._nodes:
            raise ValueError(
                f"node with id '{node_id}' not found"
            )
        node: Dict[str, any] = self._nodes.pop(node_id)
        for w in range(0, node[NODE_VN] * node[NODE_WGT]):
            _hash = self._get_hash(node_id, w)
            del self._ring[_hash]
        self._keys = sorted(self._ring.keys())
        return node

    def get(self, key: Optional[str, int], res_type: Optional[RingObjectType] = None):
        """getting node for given key"""
        node_id = self._get_node_id(key)
        if res_type is None:
            res_type = RingObjectType.ID
        if res_type == RingObjectType.ID:
            return node_id
        node = self._nodes[node_id]
        return node

    def add(self, nodes):
        """add node(s) to ring hash"""
        if nodes is None:
            return
        if not isinstance(nodes, list):
            nodes = [nodes]
        self._add_nodes(nodes)

    def __str__(self):
        return f"ring_hash [len={len(self._nodes)}]"

    def __len__(self):
        """size of ring hash"""
        return len(self._nodes)


"""
### downloads.py

- This library was designed to download sample codes
"""
import cli
import filesystem as fs
import requests
import shutil
import time
from exceptions import exception as ex
from filesystem import wrapper as wr
from pathlib import Path
from zipfile import ZipFile

samples_folder = f'{fs.CURRENT_LOCATION}/Samples'

DICT_SAMPLES = {
    0:["GetInfo", "https://github.com/hbisneto/GetInfo/archive/refs/heads/main.zip"],
    1:["JoKenPo", "https://github.com/hbisneto/JoKenPo/archive/refs/heads/main.zip"],
    2:["MyTimeline", "https://github.com/hbisneto/MyTimeline/archive/refs/heads/main.zip"],
    3:["JupyterBridge", "https://github.com/hbisneto/JupyterBridge/archive/refs/heads/main.zip"]
}

def download_samples():
    cli.make_menu("DOWNLOAD SAMPLE CODE", separator_style=">")
    for i in DICT_SAMPLES:
        print(f'[{i+1}] - {DICT_SAMPLES[i][0]}')
    print('[0] - << Go Back')
    print()

    opt = int(input("[?]: Type the option number: "))
    cli.separator(style="<")

    if opt > len(DICT_SAMPLES):
        ex.throw.invalid_option()
        return

    if opt == 0:
        return

    # Get information to download
    app_name = DICT_SAMPLES[opt-1][0]
    app_url = DICT_SAMPLES[opt-1][1]

    # Verify if Samples folder exists
    wr.create_directory(f'{samples_folder}/{app_name}', create_subdirs=True)
    download_sample_item(app_name, app_url)

def download_sample_item(appname, url):
    cli.make_menu(f"DOWNLOADING: {appname}...", new_line = True)
    print("[Status]: Starting Download...")
    print('[Status]: Verifying repository to download...')

    try:
        FROM = f'{fs.CURRENT_LOCATION}/main.zip'
        TO = f'{samples_folder}/{appname}/{appname}.zip'

        ServerResponse = requests.get(url, stream = True)
        FileName = url.split("/")[-1]
        with open(FileName, 'wb') as f:
            for Chunk in ServerResponse.iter_content(chunk_size = 1024):
                if Chunk:
                    f.write(Chunk)
        print(f'[Status]: "{appname}" download 100% completed!')
        print(f'[Status]: Verifying "{appname}"...')
        print(f'[Done]: "{appname}" download process complete!')
    except:
        print("[ERROR]: Could't connect to the server!")
        print(f'[Process]: Cleaning cache...')
        time.sleep(3)
        shutil.rmtree(f'{samples_folder}/{appname}/')
        shutil.rmtree
        print("[Process]: Cache cleaned!")

    try:
        Path(FROM).rename(TO)
        cli.separator()
    except:
        return

    cli.make_menu(f"EXTRACTING: {appname}...", new_line = True)
    with ZipFile(TO, 'r') as zipObj:
        zipObj.extractall(f'{samples_folder}/{appname}/')
    print(f'[Done]: "{appname}" extraction process complete!')
    cli.separator()


from discgolfspider.items import CreateDiscItem
from discgolfspider.helpers.retailer_id import create_retailer_id

import scrapy

class FrisbeebutikkenSpider(scrapy.Spider):
    name = "frisbeebutikken"
    allowed_domains = ["frisbeebutikken.no"]
    start_urls = ["https://frisbeebutikken.no/categories/golfdisker/sort-by/1/?page=1"]

    def parse(self, response):
        for product in response.css(".product-box"):
            disc = CreateDiscItem()

            try:
                disc["name"] = product.css(".title::text").get()
                disc["image"] = product.css(".image img::attr(src)").get()

                brand = product.css(".manufacturer-box img::attr(alt)").get()
                url = product.css(".product_box_title_row a::attr(href)").get()
                disc["url"] = url
                disc["spider_name"] = self.name
                disc["brand"] = brand
                disc["retailer"] = "frisbeebutikken.no"
                disc["retailer_id"] = create_retailer_id(brand, url)
                disc["in_stock"] = int(product.css(".product::attr(data-quantity)").get()) > 0
                disc["speed"] = disc["glide"] = disc["turn"] = disc["fade"] = None

                price = -9999
                sale_price: str = product.css(".has-special-price > span::text").get()
                regular_price: str = product.css(".price::text").get()

                if sale_price:
                    price = self.price_to_int(sale_price)
                else:
                    price = self.price_to_int(regular_price)

                disc["price"] = price

                yield disc
            except Exception as e:
                self.logger.error(f"Error parsing disc: {disc['name']}({disc['url']})")
                self.logger.error(e)

        next_page = response.css(".paginator_link_next::attr(href)").get()

        if next_page is not None:
            yield response.follow(next_page, callback=self.parse)

    def price_to_int(self, price: str) -> int:
        try:
            price_number = price.strip().split(",")[0]
            return int(price_number)
        except Exception as e:
            raise ValueError(f"Could not parse price: {e}")


####
# python calc_gcc.py genome.fa annotation.gtf <gene|exon>
####
from pyfaidx import Fasta
import sys
from Bio.SeqUtils import GC
genome_file=sys.argv[1]
annotation_file=sys.argv[2]
# genome_file='/mnt/lab_data/montgomery/shared/genomes/hg19/hg19.fa'
# annotation_file='/srv/persistent/bliu2/shared/annotation/gtex/gencode.v19.genes.v6p.hg19.gtf'

genome = Fasta(genome_file)

if sys.argv[3]=='gene':
	with open(annotation_file,'r') as f:
		for line in f:
			if "##" in line: continue
			split_line=line.strip().split('\t')
			if split_line[2]=='gene':
				chrom=split_line[0]
				start=int(split_line[3])-1
				end=int(split_line[4])
				gene_id=split_line[8].split(';')[0].replace('gene_id ','').replace('"','')
				gcc=GC(genome[chrom][start:end].seq)
				sys.stdout.write("%s\t%s\n"%(gene_id,gcc))

elif sys.argv[3]=='exon':
	with open(annotation_file,'r') as f:
		for line in f:
			if "##" in line: continue

			split_line=line.strip().split('\t')
			if split_line[2]=='gene':
				gene_id=split_line[8].split(';')[0].replace('gene_id ','').replace('"','')
				try:
					gcc=GC(seq)
					sys.stdout.write("%s\t%s\n"%(gene_id_bak,gcc))
				except NameError:
					pass

				# initialize:
				seq=""
				gene_id_bak=gene_id

			if split_line[2]=='exon':
				chrom=split_line[0]
				start=int(split_line[3])-1
				end=int(split_line[4])
				seq+=genome[chrom][start:end].seq
		gcc=GC(seq)
		sys.stdout.write("%s\t%s\n"%(gene_id,gcc))

else:
	sys.stderr.write('3rd option must be either gene or exon')


from github import Github
import datetime
import csv
from collections import OrderedDict
from shutil import copy2
import os
from tqdm import tqdm
import argparse
from aux_functions import display_StatTheGit

# Command-line input setup
parser = argparse.ArgumentParser(
    description="StatTheGit - Maintain GitHub repository stats for more than 14 days"
)
parser.add_argument(
    "--git_token_file",
    type=str,
    default="access_token.txt",
    help="GitHub token to your profile",
)
parser.add_argument(
    "--username", type=str, default="hag007", help="GitHub Username",
)
parser.add_argument(
    "--namespace", type=str, default="Shamir-Lab", help="GitHub Namespace",
)
parser.add_argument(
    "--repo_names",
    type=str,
    default='all', # ['EMP', 'DOMINO', 'SCAPP', 'MONET', 'MSP_UHS', 'PRODIGY', 'EMP-benchmark',  'Logrank-Inaccuracies', 'Multi-Omics-Cancer-Benchmark','PlasClass', 'Recycler', 'NEMO','CT-FOCS', 'DOCKS','Karyotype-reconstruction','SPRINT', 'Sorting-Cancer-Karyotypes', 'FOCS', 'ADEPTUS-2.0','GENEPARK', 'Faucet', 'BARCODE']
    nargs="+",
    help="Name of repositories seperated by space. Leave it empty and all the repositories will be serviced",
)

if __name__ == "__main__":
    # Parse the command line
    display_StatTheGit()
    args = parser.parse_args()
    g = Github(open(args.git_token_file).read().strip())
    repo_names = []
    # Check the repositories
    if "all" not in args.repo_names:
        # repo_names.append(args.repo_names)
        repo_names = args.repo_names
        print(repo_names)
    else:
        for repo in g.get_user().get_repos():
            repo_full_name = repo._full_name.value
            if args.namespace == repo_full_name.split("/")[0]:
                repo_name = repo_full_name.split("/")[1]
                repo_names.append(repo_name)

    for repo_n in tqdm(repo_names):
        # Process each repository
        repo_str = args.namespace + "/" + repo_n
        print("Processing: ", repo_n)
        repo = g.get_repo(repo_str)

        # Get repository clones statistics
        clone_stat = repo.get_clones_traffic()
        clone_stat = clone_stat["clones"]

        # Get repository views statistics
        traffic_stat = repo.get_views_traffic()
        print(traffic_stat)
        traffic_stat = traffic_stat["views"]

        # Get repository commits statistics
        commit_stat = repo.get_commits()
        commits=[a.raw_data['commit']['author']['date'].split('T')[0].split(' ')[0] for a in list(commit_stat)]
        earliest_commit_date=commits[0]

        # Get URL
        repo_url = repo.html_url

        # The stats fetched from GitHub packaged has date missing where the clones/views are zero.
        # The following lines appends missing dates and orders them.

        if len(clone_stat) > 0 or True:
            print(clone_stat)
            print(traffic_stat)
            # Find the earliest date between the views and clones
            if len(traffic_stat) > 0:
                earliest_exposure_date=traffic_stat[0].timestamp.date()
                if len(clone_stat) > 0 and traffic_stat[0].timestamp.date() > clone_stat[0].timestamp.date():
                    earliest_exposure_date = clone_stat[0].timestamp.date()

            else:
                earliest_exposure_date=datetime.datetime.strptime("1970-01-01", '%Y-%m-%d').date()
            date_array = []
            clone_array = {}
            traffic_array = {}

            # Generate array of dates under consideration
            for d in range(14):
                latest_date = str(earliest_exposure_date + datetime.timedelta(days=d))
                # Assign zeros to clone and views statistics
                clone_array[latest_date] = 0
                traffic_array[latest_date] = 0

            # Populate the clone statistics for the available date.
            # For unavailable dates, the stat is already initialized to zero
            for c in clone_stat:
                clone_array[str(c.timestamp.date())] = c.uniques

            for v in traffic_stat:
                traffic_array[str(v.timestamp.date())] = v.uniques

            # Create the folder of username if it doesn't exists
            path_to_folder = "repo_stats/" + args.username
            if not os.path.exists(path_to_folder):
                os.makedirs(path_to_folder)

            exposure_csv_str = os.path.join("repo_stats", repo_str.split("/")[0], "exposure", repo_str.split("/")[1] + ".txt")
            exposure_csv_str_temp = os.path.join("repo_stats", repo_str.split("/")[0], "exposure", repo_str.split("/")[1] + "_temp.txt")
            commits_csv_str = os.path.join("repo_stats", repo_str.split("/")[0], "commits", repo_str.split("/")[1] + ".txt")
            commits_csv_str_temp = os.path.join("repo_stats", repo_str.split("/")[0], "commits", repo_str.split("/")[1] + "_temp.txt")
            url_csv_str = os.path.join("repo_stats", repo_str.split("/")[0], "urls", repo_str.split("/")[1] + ".txt")

            # Save the stat file as another temp file.
            if os.path.exists(exposure_csv_str):
                s = copy2(exposure_csv_str, exposure_csv_str_temp)
            if os.path.exists(commits_csv_str):
                s = copy2(commits_csv_str, commits_csv_str_temp)

            # Create CSV file.
            try:
                os.makedirs(os.path.dirname(exposure_csv_str))
            except:
                pass
            try:
                os.makedirs(os.path.dirname(commits_csv_str))
            except:
                pass
            try:
                os.makedirs(os.path.dirname(url_csv_str))
            except:
                pass

            exposure_csv_file = open(exposure_csv_str, "w")
            exposure_writer = csv.writer(exposure_csv_file)
            commits_csv_file = open(commits_csv_str, "w")
            commits_writer = csv.writer(commits_csv_file)

            # Define header of the CSV file
            exposure_writer.writerow(["Date", "Clones", "Traffic"])
            commits_writer.writerow(["Commits"])

            clone_array = OrderedDict(sorted(clone_array.items(), key=lambda t: t[0]))
            traffic_array = OrderedDict(sorted(traffic_array.items(), key=lambda t: t[0]))

            if os.path.exists(exposure_csv_str_temp):
                # copyfile(csv_str, csv_str_temp)
                cc = 1
                with open(exposure_csv_str_temp) as exposure_csv_file:
                    csv_reader = csv.reader(exposure_csv_file, delimiter=",")
                    line_count = 0
                    for row in csv_reader:
                        if line_count > 0:
                            datetime_obj = datetime.datetime.strptime(
                                row[0], "%Y-%m-%d"
                            ).date()
                            compare_date = datetime.datetime.strptime(
                                str(earliest_exposure_date), "%Y-%m-%d"
                            ).date()

                            if datetime_obj < compare_date or compare_date < datetime.datetime.strptime("1970-01-30", "%Y-%m-%d").date():
                                exposure_writer.writerow([row[0], row[1], row[2]])
                            else:
                                break
                        line_count += 1

            if os.path.exists(commits_csv_str_temp):
                # copyfile(csv_str, csv_str_temp)
                cc = 1
                with open(commits_csv_str_temp) as commits_csv_file:
                    csv_reader = csv.reader(commits_csv_file, delimiter=",")
                    line_count = 0
                    for row in csv_reader:
                        if line_count > 0:
                            datetime_obj = datetime.datetime.strptime(
                                row[0], "%Y-%m-%d"
                            ).date()
                            compare_date = datetime.datetime.strptime(
                                str(earliest_commit_date), "%Y-%m-%d"
                            ).date()

                            if datetime_obj < compare_date or compare_date < datetime.datetime.strptime("1970-01-30", "%Y-%m-%d").date():
                                commits_writer.writerow([row[0]])
                            else:
                                break
                        line_count += 1

            compare_date = datetime.datetime.strptime(str(earliest_exposure_date), "%Y-%m-%d").date()
            first_date= datetime.datetime.strptime("1970-01-30", "%Y-%m-%d").date()
            if compare_date>first_date or not os.path.exists(exposure_csv_str_temp):
                for (key_clone, value_clone), (key_traffic, value_traffic) in zip(
                    clone_array.items(), traffic_array.items()
                ):
                    exposure_writer.writerow([key_clone, value_clone, value_traffic])

                exposure_csv_file.close()

            for commit in commits:
                commits_writer.writerow([commit])

            commits_csv_file.close()

            exposure_csv_file = open(exposure_csv_str_temp, "w")
            exposure_writer = csv.writer(exposure_csv_file)
            exposure_writer.writerow(["Date", "Clones", "Traffic"])
            with open(exposure_csv_str) as exposure_csv_file:
                csv_reader = csv.reader(exposure_csv_file, delimiter=",")
                for row in csv_reader:
                    exposure_writer.writerow([row[0], row[1], row[2]])
            exposure_csv_file.close()

            commits_csv_file = open(commits_csv_str_temp, "w")
            commits_writer = csv.writer(commits_csv_file)
            commits_writer.writerow(["Commits"])
            with open(commits_csv_str) as commits_csv_file:
                csv_reader = csv.reader(commits_csv_file, delimiter=",")
                for row in csv_reader:
                    commits_writer.writerow([row[0]])
            commits_csv_file.close()

            url_csv_file = open(url_csv_str, "w")
            url_writer = csv.writer(url_csv_file)
            with open(url_csv_str) as url_csv_file:
                    url_writer.writerow(["URL"])
                    url_writer.writerow([repo_url])
            url_csv_file.close()

            # Remove temp file.
            os.remove(exposure_csv_str_temp)
            os.remove(commits_csv_str_temp)


import os
import argparse
from model import *
import torch
import torch.optim as optim
from torch.utils.data import DataLoader
import json
import time
from datasets import Datasets, TestKodakDataset
from Meter import AverageMeter
from pytorch_msssim import ms_ssim

torch.backends.cudnn.enabled = True
gpu_num = torch.cuda.device_count()
cur_lr = base_lr = 1e-4
print_freq = 100
cal_step = 50
batch_size = 16
tot_epoch = 1000000
tot_step = 1800000
decay_interval = 1500000
lr_decay = 0.1
image_size = 256
logger = logging.getLogger("ImageCompression")
global_step = 0
save_model_freq = 100000
test_step = 10000
parser = argparse.ArgumentParser(description='Pytorch reimplement for variational image compression with a scale hyperprior')

parser.add_argument('-n', '--name', default='compress_base', help='experiment name')
parser.add_argument('-p', '--pretrain', default='', help='load pretrain model')
parser.add_argument('--seed', default=234, type=int, help='seed for random functions, and network initialization')
parser.add_argument('--train', dest='train', default='/home/dataset/coco2017', help='the path of training dataset')
parser.add_argument('--val', dest='val', default='/home/dataset/Kodak', help='the path of validation dataset')
parser.add_argument("--lmbda",dest="lmbda",type=float,default=0.013,help="Bit-rate distortion parameter (default: %(default)s)",)
parser.add_argument("--metrics",type=str,default="mse",help="Optimized for (default: %(default)s)",)

def adjust_learning_rate(optimizer, global_step):
    global cur_lr
    if global_step < decay_interval:
        lr = base_lr
    else:
        lr = base_lr * lr_decay
    cur_lr = lr
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

def train(epoch, global_step):
    logger.info("Epoch {} begin".format(epoch))
    net.train()
    global optimizer
    elapsed, losses, psnrs, bpps, bpp_features, bpp_zs, mse_losses = [AverageMeter(print_freq) for _ in range(7)]

    for batch_idx, input in enumerate(train_loader):
        start_time = time.time()
        global_step += 1
        clipped_recon_image, mse_loss,ms_ssim_loss, bpp_feature, bpp_z, bpp = net(input)

        distribution_loss = bpp
        if args.metrics=='mse':
            rd_loss = args.lmbda * 255 * 255 * mse_loss + distribution_loss
        elif args.metrics=='ms-ssim':
            rd_loss = args.lmbda * ms_ssim_loss + distribution_loss

        optimizer.zero_grad()
        rd_loss.backward()

        def clip_gradient(optimizer, grad_clip):
            for group in optimizer.param_groups:
                for param in group["params"]:
                    if param.grad is not None:
                        param.grad.data.clamp_(-grad_clip, grad_clip)

        clip_gradient(optimizer, 5)
        optimizer.step()

        if (global_step % cal_step) == 0:
            if mse_loss.item() > 0:
                psnr = 10 * (torch.log(1 * 1 / mse_loss) / np.log(10))
                psnrs.update(psnr.item())
            else:
                psnrs.update(100)

            elapsed.update(time.time() - start_time)
            losses.update(rd_loss.item())
            bpps.update(bpp.item())
            bpp_features.update(bpp_feature.item())
            bpp_zs.update(bpp_z.item())
            mse_losses.update(mse_loss.item())

        if (global_step % print_freq) == 0:
            process = global_step / tot_step * 100.0
            log = (' | '.join([
                f'Step [{global_step}/{tot_step}={process:.2f}%]',
                f'Epoch {epoch}',
                f'Time {elapsed.val:.3f} ({elapsed.avg:.3f})',
                f'Lr {cur_lr}',
                f'Total Loss {losses.val:.3f} ({losses.avg:.3f})',
                f'PSNR {psnrs.val:.3f} ({psnrs.avg:.3f})',
                f'Bpp {bpps.val:.5f} ({bpps.avg:.5f})',
                f'Bpp_feature {bpp_features.val:.5f} ({bpp_features.avg:.5f})',
                f'Bpp_z {bpp_zs.val:.5f} ({bpp_zs.avg:.5f})',
                f'MSE {mse_losses.val:.5f} ({mse_losses.avg:.5f})',
            ]))
            logger.info(log)

        if (global_step % save_model_freq) == 0:
            save_model(model, global_step, save_path)
        if (global_step % test_step) == 0:
            testKodak(global_step)
            net.train()
        if global_step >= tot_step:
            save_model(model, global_step, save_path)
            logger.info("训练结束")
            sys.exit(0)

    return global_step

def testKodak(step):
    with torch.no_grad():
        net.eval()
        sumBpp = 0
        sumPsnr = 0
        sumMsssim = 0
        sumMsssimDB = 0
        cnt = 0
        for batch_idx, input in enumerate(test_loader):
            clipped_recon_image, mse_loss, ms_ssim_loss, bpp_feature, bpp_z, bpp = net(input)
            mse_loss, bpp_feature, bpp_z, bpp = torch.mean(mse_loss), torch.mean(bpp_feature), torch.mean(bpp_z), torch.mean(bpp)

            mse_loss = torch.mean((clipped_recon_image.cpu() - input.cpu()).pow(2))

            psnr = 10 * (torch.log(1. / mse_loss) / np.log(10))
            sumBpp += bpp
            sumPsnr += psnr
            msssim = ms_ssim(clipped_recon_image.cpu().detach(), input, data_range=1.0,size_average=True)
            msssimDB = -10 * (torch.log(1-msssim) / np.log(10))
            sumMsssimDB += msssimDB
            sumMsssim += msssim
            logger.info("Bpp:{:.6f}, PSNR:{:.6f}, MS-SSIM:{:.6f}, MS-SSIM-DB:{:.6f}".format(bpp, psnr, msssim, msssimDB))
            cnt += 1

        logger.info("Test on Kodak dataset: model-{}".format(step))
        sumBpp /= cnt
        sumPsnr /= cnt
        sumMsssim /= cnt
        sumMsssimDB /= cnt
        logger.info("Dataset Average result---Bpp:{:.6f}, PSNR:{:.6f}, MS-SSIM:{:.6f}, MS-SSIM-DB:{:.6f}".format(sumBpp, sumPsnr, sumMsssim, sumMsssimDB))

if __name__ == "__main__":
    args = parser.parse_args()
    torch.manual_seed(seed=args.seed)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s] %(message)s')
    formatter = logging.Formatter('[%(asctime)s][%(filename)s][L%(lineno)d][%(levelname)s] %(message)s')
    stdhandler = logging.StreamHandler()
    stdhandler.setLevel(logging.INFO)
    stdhandler.setFormatter(formatter)
    logger.addHandler(stdhandler)
    save_path = os.path.join('checkpoints', args.name+'_'+args.metrics+'_'+str(args.lmbda))
    if args.name != '':
        os.makedirs(save_path, exist_ok=True)
        filehandler = logging.FileHandler(os.path.join(save_path, 'log.txt'))
        filehandler.setLevel(logging.INFO)
        filehandler.setFormatter(formatter)
        logger.addHandler(filehandler)
    logger.setLevel(logging.INFO)
    logger.info("image compression training")

    model = ImageCompressor()
    if args.pretrain != '':
        logger.info("loading model:{}".format(args.pretrain))
        global_step = load_model(model, args.pretrain)

    net = torch.nn.DataParallel(model.cuda(), device_ids=[0])
    logger.info(net)

    parameters = net.parameters()
    global test_loader
    test_dataset = TestKodakDataset(data_dir=args.val)
    test_loader = DataLoader(dataset=test_dataset, shuffle=False, batch_size=1, pin_memory=True, num_workers=1)
    optimizer = optim.Adam(parameters, lr=base_lr)
    global train_loader
    train_data_dir = args.train
    train_dataset = Datasets(train_data_dir, image_size)
    train_loader = DataLoader(dataset=train_dataset,
                              batch_size=batch_size,
                              shuffle=True,
                              pin_memory=True,
                              num_workers=2)
    steps_epoch = global_step // (len(train_dataset) // (batch_size))
    save_model(model, global_step, save_path)
    for epoch in range(steps_epoch, tot_epoch):
        adjust_learning_rate(optimizer, global_step)
        global_step = train(epoch, global_step)


"""
clustering_utils.py: utilitary functions for the clustering.py module.
"""

import numpy as np
from enum import IntEnum
from .utils import find_in_sequence

class Link(IntEnum):
    """
    Represents state of coreferring links.
    Must be negative integers to not interfere with the clustering process.
    """
    NO_ANTECEDENT   = -1
    PROCESSED       = -2

def cluster_labels_to_entity_clusters(cluster_labels):
    """
    @cluster_labels is the second return from the affinity_matrix computation,
     and cluster_labels[mention_idx] = mention's cluster
    """
    clusters = dict()
    for idx, label in enumerate(cluster_labels):
        if label not in clusters:
            clusters[label] = list()
        clusters[label].append(idx)

    return [clusters[key] for key in clusters.keys()]

def coreference_links_to_entity_clusters(links):
    """
    Transforms the given array of coreference links into a set of entities (mention clusters).
    Each entity/cluster is represented by the mentions' indices.
    """
    clusters = []
    for i in range(len(links) - 1, -1, -1):
        new_cluster = set()
        j = i

        while True:
            antecedent = links[j]
            links[j] = Link.PROCESSED
            new_cluster.add(j)

            # end of coreference link
            if antecedent == Link.NO_ANTECEDENT:
                clusters.append(new_cluster)
                break
            # linking to previously processed cluster
            elif antecedent == Link.PROCESSED:
                previous_cluster_idx = find_in_sequence(lambda s: j in s, clusters)
                clusters[previous_cluster_idx].update(new_cluster)
                break

            j = antecedent

    return clusters

def generate_affinity_matrix(document, mention_pair_predictions):
    """
    Generates an affinity/similarity matrix from the given mention-pair scores.
    @returns affinity_matrix[m1_idx, m2_idx] = affinity_score
    """
    num_mentions = len(document.mentions)
    affinity_matrix = np.ndarray(shape=(num_mentions, num_mentions), dtype=np.float32)
    affinity_matrix.fill(0)

    for idx in range(len(mention_pair_predictions)):
        i1, i2 = document.pairwise_combinations[idx]
        affinity_matrix[i1,i2] = mention_pair_predictions[idx]
        affinity_matrix[i2,i1] = mention_pair_predictions[idx]

    return affinity_matrix


import requests
import pytest

# class Test_search():
# 加推公司
def test_recommendCompany():
    url = "http://192.168.101.102/api/search/app/company/recommendCompany"
    res = requests.get(url)
    print(res.json())
    code = res.json()['code']
    try:
        assert code == 0
        print("成功")
    except:
        print("失败")


##Created by Kevin Chau
##interface class for the NAND gate
def NAND(a,b): ##Define the NAND Gate
    if(a == True and b == True):
        return int(False)
    else:
        return int(True)
def NANDrunner():
    ##Defines the method that will simulate the NAND Gate
    ##2 user inputs (1 or 0), one output of a NAND b
    ##run NANDrunner.py for simulation
    a = bool(int(input("Enter 1 or 0: "), 2))
    b = bool(int(input("Enter 1 or 0: "), 2))
    if (a == 1 or b == 1):
        x = False
    else:
        x = True
    print("a = ", int(a), " b = ", int(b))
    print("a NAND b = ", NAND(a, b))


from slack_today_i_did.type_aware import json

def makes_state_change(f):
    def wrapper(self, *args, **kwargs):
        f(self, *args, **kwargs)
        self.needs_save = True
    return wrapper

def saves_state(f):
    def wrapper(self, *args, **kwargs):
        f(self, *args, **kwargs)
        self.needs_save = False
    return wrapper

class CommandHistory(object):

    @saves_state
    def __init__(self):
        self.history = {}

    @makes_state_change
    def add_command(self, channel, command, args):
        if channel not in self.history:
            self.history[channel] = []

        self.history[channel].append({'action': command, 'args': args})

    def last_command(self, channel):
        if channel not in self.history:
            return None
        return self.history[channel][-1]

    def __eq__(self, other):
        if not isinstance(other, self.__class__):
            return False

        for channel in self.history:
            if channel not in other.history:
                return False

            if self.history[channel] != other.history[channel]:
                return False

        return True

    @saves_state
    def load_from_file(self, known_tokens, known_types, filename: str) -> None:
        """ Load command history from a file """
        try:
            with open(filename) as f:
                as_json = json.load(f, known_types=known_types)
        except FileNotFoundError:
            return
        except:
            # sometimes bad things happen to good people
            return

        for (channel, commands) in as_json['channels'].items():
            for command_entry in commands:
                command_entry = self._command_entry_from_json(known_tokens, command_entry)
                self.add_command(channel, command_entry['action'], command_entry['args'])

    @saves_state
    def save_to_file(self, filename: str) -> None:
        """ save command history to a file """
        channels = {
            'channels': {
                channel: [self._command_entry_to_json(command) for command in commands]
                for (channel, commands) in self.history.items()
            }
        }

        # if we can't save it, exit early
        try:
            channel_json = json.dumps(channels)
            with open(filename, 'w') as f:
                f.write(channel_json)
        except:
            return None

        self.needs_save = False

    def _command_entry_to_json(self, command_entry):
        action = command_entry['action'].__name__

        return {
            'action': action,
            'args': command_entry['args']
        }

    def _no_longer_exists(self, *args, **kwargs) -> str:
        return 'this thing no longer exists!'

    def _command_entry_from_json(self, known_tokens, json):
        return {
            'action': known_tokens.get(json['action'], self._no_longer_exists),
            'args': json['args']
        }


# -*- coding: gb18030 -*-

import csstatus
import csconst
import csdefine
import random
from Spell_Item import Spell_Item
from bwdebug import *
import BigWorld
import Math

class Spell_PlantTree( Spell_Item ):
	"""
	种植果树
	"""
	def __init__( self ):
		"""
		"""
		Spell_Item.__init__( self )
		self.p1 = ""
		self.p2 = ""
		self.p3 = ""
		self.p4 = ""
		self.p5 = ""

	def init( self, dict ):
		"""
		读取技能配置
		@param dict: 配置数据
		@type  dict: python dict
		"""
		Spell_Item.init( self, dict )
		self.p1 = str( dict[ "param1" ] )					# 果树的模型编号
		self.p2 = int( dict[ "param2" ] )      				# 果树种子的ID
		if dict[ "param3" ]:
			self.p3 = str( dict[ "param3" ] )				# 果树种植位置限制
		if dict[ "param4" ]:
			self.p4 = float( dict[ "param4" ] )				# 果树种植范围限制
		if dict[ "param5" ]:
			self.p5 = str( dict[ "param5" ] ).split(";")	# 果树种植地图限制

	def useableCheck( self, caster, target ):
		"""
		virtual method.
		校验技能是否可以使用。
		return: SkillDefine::SKILL_*;默认返回SKILL_UNKNOW
		注：此接口是旧版中的validUse()

		@param target: 施展对象
		@type  target: 一个包装过的对象entity 被包装对象可能是 (位置，entity, item)详细请看SkillTargetObjImpl.py
		@return:           INT，see also csdefine.SKILL_*
		@rtype:            INT
		"""
		if caster.hasFlag( csdefine.ROLE_FLAG_SAFE_AREA ):
			return csstatus.FRUIT_PLANT_NOT_AREA

		if len( caster.entitiesInRangeExt( csconst.FRUIT_PLANT_DISTANCE, "FruitTree", caster.position ) ):
			return csstatus.FRUIT_PLANT_NEED_FAR

		if self.p5:
			if caster.getCurrentSpaceData( csconst.SPACE_SPACEDATA_KEY ) not in self.p5:
				return csstatus.FRUIT_PLANT_WRONG_MAP

		if self.p3:
			posData = self.p3.split("|")
			posDatas = []
			for i in posData:
				j = eval(i)
				posDatas.append( j )
			canPlantTree = False
			for k in posDatas:
				if caster.position.distTo( k ) <= self.p4: canPlantTree = True
			if canPlantTree == False:
				return csstatus.FRUIT_PLANT_WRONG_POS
			else: return csstatus.SKILL_GO_ON

		if caster.state == csdefine.ENTITY_STATE_FIGHT:
			return csstatus.FRUIT_PLANT_WRONG
		return csstatus.SKILL_GO_ON

	def receive( self, caster, receiver ):
		"""
		virtual method.
		法术到达要做的事情
		这是对自己使用的物品技能，因此receiver肯定是real entity
		"""
		position = Math.Vector3( receiver.position )
		param = { "modelNumber" : self.p1, "fruitseedID" : self.p2, "planterDBID" : receiver.databaseID, "planterName" : receiver.getName() }
		receiver.createEntityNearPlanes( "FruitTree", position, ( 0, 0, 0 ), param )


#%matplotlib inline
import matplotlib.pylab as plt
import os
import glob
import numpy as np
import math
from data_augmentation_h5py import *
import cnn_utils
import ipt_utils
import natsort
import time
import random
import tensorflow as tf
from keras.callbacks import ModelCheckpoint, EarlyStopping

os.environ["CUDA_VISIBLE_DEVICES"] = "0"
physical_devices = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(physical_devices[0], True)

'''

# -----------------------------------------------------
# IF COMBINING HEALTHY AND UNHEALTHY BRAIN
# DATASETS INTO ONE DIRECTORY WITHOUT CREATING
# A VALIDATION DIRECTORY
# -----------------------------------------------------
imgs_list = glob.glob("c:/users/fungs/bmen501/Data/Training_Orig/*.nii.gz")
masks_list = glob.glob("c:/users/fungs/bmen501/Data/Training_STAPLE/*.nii.gz")

# shuffle the images and masks
combined_list = list(zip(imgs_list, masks_list))
random.shuffle(combined_list)
imgs_list_shuf, masks_list_shuf = zip(*combined_list)

# percentage of data used for validation
val_perc = 0.25

# number of brains in validation set
val = math.ceil(val_perc*len(imgs_list))

# train and validation split
img_train = imgs_list_shuf[:-val]
mask_train = masks_list_shuf[:-val]
img_val = imgs_list_shuf[-val:]
mask_val = masks_list_shuf[-val:]

'''

# -----------------------------------------------------
# IF SPLITTING BOTH HEALTHY AND UNHEALTHY BRAINS
# INTO TRAINING AND VALIDATION DIRECTORIES
# -----------------------------------------------------
# loading all the filenames
# h5py images
img_train = glob.glob("c:/users/fungs/bmen501/Data/Train-hdf5/Image/*.h5")
mask_train = glob.glob("c:/users/fungs/bmen501/Data/Train-hdf5/Mask/*.h5")
img_val = glob.glob("c:/users/fungs/bmen501/Data/Val-hdf5/Image/*.h5")
mask_val = glob.glob("c:/users/fungs/bmen501/Data/Val-hdf5/Mask/*.h5")

# nifti images
# img_train = glob.glob("c:/users/fungs/bmen501/Data/Train/Image/*.nii.gz")
# mask_train = glob.glob("c:/users/fungs/bmen501/Data/Train/Mask/*.nii.gz")
# img_val = glob.glob("c:/users/fungs/bmen501/Data/Val/Image/*.nii.gz")
# mask_val = glob.glob("c:/users/fungs/bmen501/Data/Val/Mask/*.nii.gz")

# -----------------------------------------------------

# sort the sets
img_train = natsort.natsorted(img_train)
mask_train = natsort.natsorted(mask_train)
img_val = natsort.natsorted(img_val)
mask_val = natsort.natsorted(mask_val)

print(img_train[268])
print(mask_train[268])

# training set data generator
train_dg = DataGeneratorH5PY2D(img_train, mask_train, (96,96), (30,30), 36,
                 rot = 30, shift_x = 15, shift_y = 10,
                 scale = 0.6, shear = 15, flip_x = True, flip_y = True, shuffle = True)

# validation set data generator
val_dg = DataGeneratorH5PY2D(img_val, mask_val, (96,96), (30,30), 9,
                  rot = 30, shift_x = 15, shift_y = 10,
                  scale = 0.6, shear = 15, flip_x = True, flip_y = True, shuffle = True)

# t  =time.time()
# X,Y = train_dg.__getitem__(10)
# t = time.time() -t
# print(t)

# string used to save models after each epoch
model_name = "./Network/unet_data_best_15pat.hdf5"

# early stopping callback to shut down training after
# 10 epochs with no improvement
earlyStopping = EarlyStopping(monitor='val_dice_coef', patience=15, verbose=0, mode='max')

# checkpoint callback to save model  along the epochs
checkpoint = ModelCheckpoint(model_name, mode = 'max', monitor='val_dice_coef',verbose=0,
                             save_best_only=False, save_weights_only = True)

# create model
model = cnn_utils.get_unet_mod(patch_size = (96,96), nchannels = 1, learning_rate = 1e-4,
                                learning_decay = 5e-9)

hist = model.fit(train_dg, epochs=500, verbose = 1, validation_data = (val_dg),
                    callbacks = [checkpoint, earlyStopping], max_queue_size = 20, workers = 12)

# saving training history
np.save("./network/dice_15pat.npy",np.array(hist.history['dice_coef']))
np.save("./network/val_dice_15pat.npy",np.array(hist.history['val_dice_coef']))

# plotting the dice coefficient
dice = np.array(hist.history['dice_coef'])
val_dice = np.array(hist.history['val_dice_coef'])
loss = np.array(hist.history['loss'])
val_loss = np.array(hist.history['val_loss'])
print (val_loss.argmin())
plt.figure(figsize = (4,4/1.5),facecolor = "w",dpi = 450)
plt.plot(dice,'x-', markersize = 4,label = "Train")
plt.plot(val_dice,'+-',markersize = 4,label = "Validation")
plt.legend()
plt.grid()
plt.xlim(0,500)
plt.ylim(0.90,1.0)
plt.xlabel("Epoch")
plt.ylabel("Dice coefficient")
plt.show()


import sys
sys.setrecursionlimit(10**6)

n = int(input())
adj = [[] for _ in range(n + 1)]
for _ in range(n-1):
	u, v = [int(x) for x in input().split()]
	adj[u].append(v)
	adj[v].append(u)

i=0
while i<len(adj):
	adj[i] =  sorted(adj[i])
	i+=1

component_index = [-1 for _ in range(n + 1)]
def dfs(u, c):
	print(u)
	component_index[u] = c
	for v in adj[u]:
		if component_index[v] == -1:
			dfs(v, c)
			print(u)

dfs(1,1)

# root = 1
# visited = [False for x in range(n+1)]
# parent= [-1 for x in range(n+1)]
# stack = []
# stack.append(root)
# parent[root] = None
# cycle=False
# while (len(stack)):
	# s = stack[-1]
	# print(stack.pop())
	# visited[s] = True
	# for node in adj[s]:
		# if (not visited[node]):
			# stack.append(node)
			# parent[node] = s
		# elif parent[s]!=node:
			# cycle=True
		# else:
			# #check if all adj nodes are visited
			# allVisited=True
			# for node in adj[s]:
				# if (not visited[node]):
					# allVisited=False

			# if allVisited:
				# stack.append(parent[s])
				# for node in adj[s]:
					# if (not visited[node]):
						# if node in stack:
							# stack.remove(node)

Progvar/AP CSCI 21 2022/Week 5/ABC213D.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug  2 19:15:12 2019

@author: augusto
"""

import os
import pickle

import torch

import qrs_detector

import numpy as np
from scipy import signal

import matplotlib.pyplot as plt

def generate_artificial_signals(sample_freq, signal_freq, stop_time = 10):
    """
    Genera cuadrada triangualar y senoidal a la frecuencia de sampleo deseada.

    Parameters
    ----------
    sample_freq : int
        Frecuencia de sampleo deseada.
    signal_freq : int
        Frecuencia de la señal deseada.
    stop_time : int
        Largo del vector en segundos.

    Returns
    ----------
    data : dict
        Diccionario con los campos "sine" "square" y "triang".
    """

    # Vector temporal
    t = np.linspace(0, 1, stop_time * sample_freq)

    # Generacion de señales
    data = {}

    data['sine'] = np.sin(t * 2 * np.pi * signal_freq)
    data['triang'] = signal.sawtooth(t * 2 * np.pi * signal_freq, 0.5)
    data['square'] = signal.square(t * 2 * np.pi * signal_freq)

    return data

if __name__ == "__main__":
    slice_samples = 24

    # Ruta y nombre del modelo guardado
    ia_file_path = "/home/augusto/Desktop/GIBIO/Algoritmos/ia/trained_models/model_1_beta_large"
    ia_filename = "qrs_det_model_1_epoch_10.pt"

    # Señales a testear
    signal_freq = 50

    data = generate_artificial_signals(250, signal_freq, stop_time = 10)

    # Cargo modelo
    model = qrs_detector.qrs_det_1_beta(24)
    model.load_state_dict(torch.load(os.path.join(ia_file_path, ia_filename)))
    model.eval()

    counter = 0

    while True:
        this_square_data = torch.Tensor(data['square'][counter * slice_samples:counter * slice_samples + slice_samples])
        this_sin_data = torch.Tensor(data['sine'][counter * slice_samples:counter * slice_samples + slice_samples])
        this_triang_data = torch.Tensor(data['triang'][counter * slice_samples:counter * slice_samples + slice_samples])

        this_square_data = this_square_data.view(1, 1, 24)
        this_sin_data = this_sin_data.view(1, 1, 24)
        this_triang_data = this_triang_data.view(1, 1, 24)

        y_pred_square = model(this_square_data)
        y_pred_sin = model(this_sin_data)
        y_pred_triang = model(this_triang_data)

        print("Valor predecido cuadrada: ", y_pred_square.item())
        print("Valor predecido senoidal: ", y_pred_sin.item())
        print("Valor predecido triangular: ", y_pred_triang.item())

        if y_pred_square.item() >= 0.5:
            graph_color_square = 'b'
        else:
            graph_color_square = 'r'

        if y_pred_sin.item() >= 0.5:
            graph_color_sin = 'b'
        else:
            graph_color_sin = 'r'

        if y_pred_triang.item() >= 0.5:
            graph_color_triang = 'b'
        else:
            graph_color_triang = 'r'

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

        plt.subplot(3,1,1)
        plt.plot(this_square_data[0][0].tolist(), graph_color_square)
        plt.grid(True)
        plt.ylabel("Cuadrada")

        plt.subplot(3,1,2)
        plt.plot(this_sin_data[0][0].tolist(), graph_color_sin)
        plt.grid(True)
        plt.ylabel("Senoidal")

        plt.subplot(3,1,3)
        plt.plot(this_triang_data[0][0].tolist(), graph_color_triang)
        plt.grid(True)
        plt.ylabel("Triangular")

        plt.show()

        counter += 1
        if counter * slice_samples + slice_samples >= len(data['square']):
            break


import os

def poster_path(instance, filename):
    """
    Given a Series instance and file name return path and file name to be saved in

    If the instance is not None then the filename will be {pk}.{ext}
    """
    path = 'series/poster'
    root, ext = os.path.splitext(filename)
    # get filename
    if instance:
        filename = '{}{}'.format(instance.id, ext)
    # return the whole path to the file
    return os.path.join(path, filename)


#importing required modules
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense

#reading the dataset
dataset = pd.read_csv('SOCR-HeightWeight.csv')
#setting x and y values
y=dataset['Weight(Pounds)']
x=dataset['Height(Inches)']

#creating model that is an empty brain
model=Sequential()
model.get_config()

#adding layers
model.add(
    Dense(
        units=1,
        activation="linear",
        kernel_initializer="zeros",
        bias_initializer="zeros",
        input_shape=(1,)
    )
)

#getting information about model summary
model.summary()

model.get_config()

#model.get_layer("dense").input
#model.get_layer("dense").output

model.compile(loss="mean_squared_error",optimizer="Adam")

#trianing model
model.fit(x, y,epochs=5)

w=model.predict([68.22])
print("Estimated Weight of that person is = ",w)


"""You input a number and the function created checks whether
 the number belongs to the Fibonacci sequence or not.
info: In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence,
 called the Fibonacci sequence, such that each number is the sum of the
 two preceding ones, starting from 0 and 1. That is,
F_{0}=0, F_{1}=1, and F_{n}=F_{n-1}+F_{n-2}} for n > 1.
The beginning of the sequence is thus: 0,1,1,2,3,5,8,13,21,34,55..."""

seq=[]
F0,F1=0,1
number=int(input("What number you want to check? > "))
while F1<=number:
    F0, F1=F1,F0+F1
    seq.append(F1)

print(seq)

if number in seq:
    print("Answer: Yes, the number belongs to the Fibonacci sequence.")
else:
    print("Answer: No, the number doesn't belong to the Fibonacci sequence.")


import logging
import os
import subprocess
import tempfile

import yaml

from autogluon.bench.benchmark import Benchmark

logger = logging.getLogger(__name__)

class TabularBenchmark(Benchmark):
    def __init__(self, benchmark_name: str, root_dir: str = "./benchmark_runs/tabular/"):
        super().__init__(
            benchmark_name=benchmark_name,
            root_dir=root_dir,
        )
        self.module = "tabular"

    def setup(
        self,
    ):
        setup_script_path = os.path.abspath(os.path.dirname(__file__)) + "/setup.sh"
        command = [setup_script_path, self.benchmark_dir]
        result = subprocess.run(command)
        if result.stdout:
            logging.info("Successfully set up the environment under %s/.venv.", self.benchmark_dir)
        elif result.stderr:
            logging.error(result.stderr)

    def run(
        self,
        framework: str = "AutoGluon:latest",
        benchmark: str = "test",
        constraint: str = "test",
        task: str = None,
        custom_branch: str = None,
    ):

        exec_script_path = os.path.abspath(os.path.dirname(__file__)) + "/exec.sh"
        command = [
            exec_script_path,
            framework,
            benchmark,
            constraint,
            self.benchmark_dir,
        ]

        if task is not None:
            command += ["-t", task]

        if custom_branch is not None:

            custom_repo, custom_branch_name = tuple(custom_branch.split("#"))

            temp_dirpath = tempfile.mkdtemp()
            custom_framework_name = "AutoGluon_dev"
            command[1] = custom_framework_name

            custom_config_contents = {
                "frameworks": {
                    "definition_file": ["{root}/resources/frameworks.yaml", "{user}/frameworks.yaml"],
                    "allow_duplicates": "true",
                }
            }

            with open(os.path.join(temp_dirpath, "config.yaml"), "w") as fo:
                yaml.dump(custom_config_contents, fo)

            custom_framework_contents = {
                custom_framework_name: {"extends": "AutoGluon", "repo": custom_repo, "version": custom_branch_name}
            }

            with open(os.path.join(temp_dirpath, "frameworks.yaml"), "w") as fo:
                yaml.dump(custom_framework_contents, fo)

            command += ["-c", temp_dirpath]

        subprocess.run(command)


import sys
from collections import deque

input = sys.stdin.readline

N, M = map(int, input().split())

graph = [[] for _ in range(N + 1)]

for _ in range(M):
    a, b = map(int, input().split())
    graph[b].append(a)

def search(start):
    visited[start] = True

    que = deque()
    que.append(start)

    cnt = 1
    while que:
        v = que.popleft()

        for i in graph[v]:
            if not visited[i]:
                que.append(i)
                cnt += 1
    rel[start] = cnt

rel = [0] * (N + 1)

for i in range(1, N + 1):
    visited = [False] * (N + 1)
    search(i)

max_value = max(rel)

for i in range(len(rel)):
    if max_value == rel[i]:
        print(i, end=' ')

백준-효율적인해킹.py


from sortedcontainers import SortedList

class Solution:
  def advantageCount(self, A: List[int], B: List[int]) -> List[int]:
    sl = SortedList(A)

    for i, b in enumerate(B):
      index = 0 if sl[-1] <= b else sl.bisect_right(b)
      A[i] = sl[index]
      del sl[index]

    return A


# -*- coding: utf-8 -*-
"""
https://leetcode.com/problems/count-numbers-with-unique-digits/

Let f(k) be the number of numbers with unique digits with 0

Then we know,
f(1) = 10
f(2) = 9 * 9
f(3) = 9 * 9 * 8
f(k) = f(k - 1) * (9 - k + 2)

Let s(n) be the answer for n, then
s(n) = s(n - 1) + f(n)

If n > 10, return s(min(n, 10))
Time complexity O(1)
"""
class Solution:
    def countNumbersWithUniqueDigits(self, n: 'int') -> 'int':
        f = [0] * 11 # count of number of k-digit
        for i in range(1, 11):
            if i == 1:
                f[i] = 10
            elif i == 2:
                f[i] = 9 * 9
            else:
                f[i] = f[i - 1] * (9 - i + 2)
        s = [0] * 11 # answer for number of k-digit
        for i in range(1, 11):
            s[i] = s[i-1] + f[i]
        if n <= 0: return 1
        return s[min(n, 10)]


import api
import bson
from api.annotations import (api_wrapper, block_after_competition,
                             block_before_competition, check_csrf, log_action,
                             require_admin, require_login, require_teacher)
from api.common import WebError, WebSuccess
from flask import (Blueprint, Flask, render_template, request,
                   send_from_directory, session)

blueprint = Blueprint("stats_api", __name__)

@blueprint.route('/team/solved_problems', methods=['GET'])
@api_wrapper
@require_login
@block_before_competition(WebError("The competition has not begun yet!"))
def get_team_solved_problems_hook():
    tid = request.args.get("tid", None)
    stats = {
        "problems": api.stats.get_problems_by_category(),
        "members": api.stats.get_team_member_stats(tid)
    }

    return WebSuccess(data=stats)

@blueprint.route('/team/score_progression', methods=['GET'])
@api_wrapper
@require_login
@block_before_competition(WebError("The competition has not begun yet!"))
def get_team_score_progression():
    category = request.args.get("category", None)

    tid = api.user.get_team()["tid"]

    return WebSuccess(
        data=api.stats.get_score_progression(tid=tid, category=category))

@blueprint.route('/scoreboard', methods=['GET'])
@api_wrapper
@block_before_competition(WebError("The competition has not begun yet!"))
def get_scoreboard_hook():
    result = {}
    result['public'] = api.stats.get_all_team_scores(eligible=True)
    result['groups'] = []

    if api.auth.is_logged_in():
        user = api.user.get_user()
        if not api.team.get_team(tid=user["tid"])["eligible"]:
            result['ineligible'] = api.stats.get_all_team_scores(eligible=False)
        for group in api.team.get_groups(uid=user["uid"]):
            result['groups'].append({
                'gid':
                group['gid'],
                'name':
                group['name'],
                'scoreboard':
                api.stats.get_group_scores(gid=group['gid'])
            })

    return WebSuccess(data=result)

@blueprint.route('/top_teams/score_progression', methods=['GET'])
@api_wrapper
def get_top_teams_score_progressions_hook():
    eligible = request.args.get("eligible", "true")

    eligible = bson.json_util.loads(eligible)

    return WebSuccess(
        data=api.stats.get_top_teams_score_progressions(eligible=eligible))

@blueprint.route('/group/score_progression', methods=['GET'])
@api_wrapper
def get_group_top_teams_score_progressions_hook():
    gid = request.args.get("gid", None)
    return WebSuccess(
        data=api.stats.get_top_teams_score_progressions(gid=gid, eligible=True))

@blueprint.route('/registration', methods=['GET'])
@api_wrapper
def get_registration_count_hook():
    return WebSuccess(data=api.stats.get_registration_count())


import os

IMAGE_SIZE = 128
IMAGES_STORAGE_BUCKET = os.environ.get("IMAGES_STORAGE_BUCKET", "easy-dank-meme-classifier-images")

MODELS_LOCATION = os.environ.get(
    "MODEL_STORAGE_LOCATION",
    os.path.join(os.path.dirname(os.path.abspath(__file__)), "ml_models")
)

MODEL_FILE = os.path.join(MODELS_LOCATION, "vgg16_complex_small_images_40_dense_checkpoint.h5")

PROJECT_ID = "serverless-hackathon-devin"


import os
import sys, getopt
from collections import defaultdict
from gensim import corpora
import spacy

PROG_NAME = "conv-to-doc.py"

nlp = spacy.load("en_core_web_sm")

def usage(out):
    print("Usage: "+PROG_NAME+" [options] <tsv conv file> <output dir>",file=out)
    print("",file=out)
    print("  TODO",file=out)
    print("",file=out)
    print("  Options:")
    print("    -h: print this help message.",file=out)
#    print("    -o <min overlap>: include user if at least this number of initial users follow them",file=out)
#    print("    -b: do not add default query filter: '"+default_filters+"'",file=out)
#    print("    -c <cities file>: list of accepted place names.",file=out)
#    print("    -a: no filtering on location at all.",file=out)

    print("",file=out)

def read_input_files(filenames):
    data = {}
    for file_no, filename in enumerate(filenames):
        with open(filename, newline="\n") as infile:
            data_this_user = defaultdict(list)
            text_col = None
            conv_col = None
            for line in infile:
                fields = line.rstrip().replace("\r", " ").split('\t')
                if len(fields) > 1:
                    if text_col is None:
                        for col_no,col_name in enumerate(fields):
                            if col_name == 'text':
                                text_col = col_no
                            if col_name == 'conversation_id':
                                conv_col = col_no
                        if text_col is None or conv_col is None:
                            raise Exception(f"Col name 'text' not found in supposed header [{','.join(fields)}] in file '{filename}'")
                    else:
                        try:
                            data_this_user[fields[conv_col]].append(fields[text_col])
                        except IndexError:
                            print(conv_col)
                            print(text_col)
                else:
                    print('Weird line??', fields,file=sys.stderr)
            for conv_id, text_list in data_this_user.items():
                if data.get(conv_id) is None:
                    data[conv_id] = text_list
#                    print(conv_id, text_list)
                else:
                    if len(data[conv_id]) != len(text_list):
                        raise Exception(f"Unexpected: same conversation id {conv_id} but different content.")
    return data

def preprocess(data, remove_stop=True, keep_pos=["NOUN", "VERB", "PROPN", "ADJ", "ADV", "INTJ" ], use_lemma=True, min_freq=3):

    frequency = defaultdict(int)
    processed = []
    no = 0
    for conv,tweets in data.items():
        no += 1
        print(f"preprocessing conv {no}/{len(data)}")
        new_doc = []
        for tweet in tweets:
            spacy_doc = nlp(tweet)
            for token in spacy_doc:
                #                print(token.text, token.lemma_, token.pos_, token.shape_, token.is_alpha, token.is_stop)
                if not remove_stop or not token.is_stop:
                    if keep_pos is None or token.pos_ in keep_pos:
                        val = token.text
                        if use_lemma:
                            val = token.lemma_
                        frequency[val] += 1
                        new_doc.append(val)
        processed.append(new_doc)
    texts = []
    for doc in processed:
        texts.append([ token for token in doc if frequency[token] >= min_freq ])
    return texts

def save_data(corpus, fname):
    #dictionary.filter_extremes(no_below=20, no_above=0.5)
    dictionary = corpora.Dictionary(corpus)
    bow = [ dictionary.doc2bow(doc) for doc in corpus ]
    corpora.MmCorpus.serialize(fname, bow, dictionary)  # store to disk, for later use
    dictionary.save(fname+".dict")

def process(input_file, output_dir):
    header = False
    with open(input_file, newline="\n") as f:
        for line in f:
            fields = line.rstrip().replace("\r", " ").split("\t")
            if not header:
                col_conv_id = fields.index("conversation_id")
                col_text = fields.index("text")
                header = True
            else:
                conv_id = fields[col_conv_id]
                text = fields[col_text]
                target_file = os.path.join(output_dir, conv_id)
                with open(target_file, "a") as output:
                    output.write(text+"\n")

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:],"ho:")
    except getopt.GetoptError:
        usage(sys.stderr)
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            usage(sys.stdout)
            sys.exit()
#        elif opt == "-o":
#            overlap_min = int(arg)
#        elif opt == "-b":
#            basic = True
#        elif opt == "-c":
#            with open(arg) as infile:
#                accepted_places = [ line.rstrip() for line in infile ]
#        elif opt == '-a':
#            filter_loc = False
#           with open(arg) as infile:
#                accepted_places = [ line.rstrip() for line in infile ]

    if len(args) != 2:
        usage(sys.stderr)
        sys.exit(2)

    input_file = args[0]
    output_dir = args[1]

    if os.path.exists(input_file):
        if not os.path.exists(output_dir):
            os.mkdir(output_dir)
        process(input_file, output_dir)
    else:
        print('Error input file not found')

if __name__ == "__main__":
    main()