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

import sys

MEMORY_SIZE = 0x10000
BYTE_MIN_VALUE = 0
BYTE_MAX_VALUE = 0xff

LITTLE_ENDIAN = 1
BIG_ENDIAN = 2

EXE_FILE_MAGIC_NUMBER = 0xffff
NOT_MODIFIED = 0
MODIFIED = 1

DFLAGS = 0x0240
BOOTAD = 0x0242
DOSINI = 0x000C

SECTOR_SIZE = 0x80
BOOT_HEADER_SIZE = 6
DUMP_SIZE = 0x100

ascii2glyphe = ['.' for x in range(32)] + [chr(x) for x in range(32, 128)] + ['.' for x in range(128)]

ZERO = ' '
ONE = 'X'
CR = '\n'

TEMPLATE_HEADER = """#ifndef %LABEL%_HEADER
#define %LABEL%_HEADER

#include "datatype.h"

extern const byte %DATANAME%[%SIZE%];

#define %SIZENAME%_SIZE %SIZE%

#endif
"""

TEMPLATE_SOURCE = """

#include "%HEADERNAME%"

const byte %DATANAME%[%SIZE%] =
{
%VALUES%};

"""

OLD_HEX  = 0 # $1234
OLD_HEX2 = 1 # 01234h
HEX      = 2 # 0x1234
DEC      = 3 # 4660
PROG     = 4 # 1234
SHOW_MODE_TAB = (OLD_HEX, OLD_HEX2, HEX, DEC, PROG)
SHOW_MODE = PROG

def word2hex(value):
    if value == None:
        size = len(word2hex(0))
        return " " * size
    elif SHOW_MODE == OLD_HEX:
        return "$%04X"%value
    elif SHOW_MODE == OLD_HEX2:
        return "0%04xh"%value
    elif SHOW_MODE == HEX:
        return "0x%04x"%value
    elif SHOW_MODE == DEC:
        return "%05d"%value
    elif SHOW_MODE == PROG:
        return "%04x"%value
    raise Exception("Unexpected SHOW_MODE %s!"%str(SHOW_MODE))

def byte2hex(value):
    if value == None:
        size = len(byte2hex(0))
        return " " * size
    elif SHOW_MODE == OLD_HEX:
        return "$%02X"%value
    elif SHOW_MODE == OLD_HEX2:
        return "0%02xh"%value
    elif SHOW_MODE == HEX:
        return "0x%02x"%value
    elif SHOW_MODE == DEC:
        return "%03d"%value
    elif SHOW_MODE == PROG:
        return "%02x"%value
    raise Exception("Unexpected SHOW_MODE %s!"%str(SHOW_MODE))

def getGlyphe(value):
    if value < 32:
        return "."
    elif value < 128:
        return chr(value)
    else:
        return "."

class DESASS_6502():
    def __init__(self):
        self.__pc = None
        self.__getByte = None
        self.__addr16label={}
        self.__mnemo=[
        {'mnemo':'BRK','hook':self.inherent},
        {'mnemo':'ORA','hook':self.indzerox},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ORA','hook':self.zeropage},
        {'mnemo':'ASL','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'PHP','hook':self.inherent},
        {'mnemo':'ORA','hook':self.immediate},
        {'mnemo':'ASL','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ORA','hook':self.absolute},
        {'mnemo':'ASL','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BPL','hook':self.relative},
        {'mnemo':'ORA','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ORA','hook':self.zeropagex},
        {'mnemo':'ASL','hook':self.zeropagex},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CLC','hook':self.inherent},
        {'mnemo':'ORA','hook':self.absoly},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ORA','hook':self.absolx},
        {'mnemo':'ASL','hook':self.absolx},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'JSR','hook':self.absolute},
        {'mnemo':'AND','hook':self.indzerox},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BIT','hook':self.zeropage},
        {'mnemo':'AND','hook':self.zeropage},
        {'mnemo':'ROL','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'PLP','hook':self.inherent},
        {'mnemo':'AND','hook':self.immediate},
        {'mnemo':'ROL','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BIT','hook':self.absolute},
        {'mnemo':'AND','hook':self.absolute},
        {'mnemo':'ROL','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BMI','hook':self.relative},
        {'mnemo':'AND','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'AND','hook':self.zeropagex},
        {'mnemo':'ROL','hook':self.zeropagex},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'SEC','hook':self.inherent},
        {'mnemo':'AND','hook':self.absoly},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ORA','hook':self.absolx},
        {'mnemo':'ASL','hook':self.absolx},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'RTI','hook':self.inherent},
        {'mnemo':'EOR','hook':self.indzerox},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'EOR','hook':self.zeropage},
        {'mnemo':'LSR','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'PHA','hook':self.inherent},
        {'mnemo':'EOR','hook':self.immediate},
        {'mnemo':'LSR','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'JMP','hook':self.absolute},
        {'mnemo':'EOR','hook':self.absolute},
        {'mnemo':'LSR','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BVC','hook':self.relative},
        {'mnemo':'EOR','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'EOR','hook':self.zeropagex},
        {'mnemo':'LSR','hook':self.zeropagex},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CLI','hook':self.inherent},
        {'mnemo':'EOR','hook':self.absoly},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'EOR','hook':self.absolx},
        {'mnemo':'LSR','hook':self.absolx},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'RTS','hook':self.inherent},
        {'mnemo':'ADC','hook':self.indzerox},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ADC','hook':self.zeropage},
        {'mnemo':'ROR','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'PLA','hook':self.inherent},
        {'mnemo':'ADC','hook':self.immediate},
        {'mnemo':'ROR','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'JMP','hook':self.indirect},
        {'mnemo':'ADC','hook':self.absolute},
        {'mnemo':'ROR','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BCS','hook':self.relative},
        {'mnemo':'ADC','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ADC','hook':self.zeropagex},
        {'mnemo':'ROR','hook':self.zeropagex},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'SEI','hook':self.inherent},
        {'mnemo':'ADC','hook':self.absoly},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'ADC','hook':self.absolx},
        {'mnemo':'ROR','hook':self.absolx},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'STA','hook':self.indzerox},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'STY','hook':self.zeropage},
        {'mnemo':'STA','hook':self.zeropage},
        {'mnemo':'STX','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'DEY','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'TXA','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'STY','hook':self.absolute},
        {'mnemo':'STA','hook':self.absolute},
        {'mnemo':'STX','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BCC','hook':self.relative},
        {'mnemo':'STA','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'STY','hook':self.inherent},
        {'mnemo':'STA','hook':self.zeropagex},
        {'mnemo':'STX','hook':self.zeropagey},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'TYA','hook':self.inherent},
        {'mnemo':'STA','hook':self.absoly},
        {'mnemo':'TXS','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'STA','hook':self.absolx},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'LDY','hook':self.immediate},
        {'mnemo':'LDA','hook':self.indzerox},
        {'mnemo':'LDX','hook':self.immediate},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'LDY','hook':self.zeropage},
        {'mnemo':'LDA','hook':self.zeropage},
        {'mnemo':'LDX','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'TAY','hook':self.inherent},
        {'mnemo':'LDA','hook':self.immediate},
        {'mnemo':'TAX','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'LDY','hook':self.absolute},
        {'mnemo':'LDA','hook':self.absolute},
        {'mnemo':'LDX','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BCS','hook':self.relative},
        {'mnemo':'LDA','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'LDY','hook':self.zeropagex},
        {'mnemo':'LDA','hook':self.zeropagex},
        {'mnemo':'LDX','hook':self.zeropagey},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CLV','hook':self.inherent},
        {'mnemo':'LDA','hook':self.absoly},
        {'mnemo':'TSX','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'LDY','hook':self.inherent},
        {'mnemo':'LDA','hook':self.absolx},
        {'mnemo':'LDX','hook':self.absoly},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CPY','hook':self.immediate},
        {'mnemo':'CMP','hook':self.indzerox},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CPY','hook':self.zeropage},
        {'mnemo':'CMP','hook':self.zeropage},
        {'mnemo':'DEC','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'INY','hook':self.inherent},
        {'mnemo':'CMP','hook':self.immediate},
        {'mnemo':'DEX','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CPY','hook':self.absolute},
        {'mnemo':'CMP','hook':self.absolute},
        {'mnemo':'DEC','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BNE','hook':self.relative},
        {'mnemo':'CMP','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CMP','hook':self.zeropagex},
        {'mnemo':'DEC','hook':self.zeropagex},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CLD','hook':self.inherent},
        {'mnemo':'CMP','hook':self.absoly},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CMP','hook':self.absolx},
        {'mnemo':'DEC','hook':self.absolx},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CPX','hook':self.immediate},
        {'mnemo':'SBC','hook':self.indzerox},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'CPX','hook':self.zeropage},
        {'mnemo':'SBC','hook':self.zeropage},
        {'mnemo':'INC','hook':self.zeropage},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'INX','hook':self.inherent},
        {'mnemo':'SBC','hook':self.immediate},
        {'mnemo':'NOP','hook':self.inherent},
        {'mnemo':'SBC','hook':self.inherent},
        {'mnemo':'CPX','hook':self.absolute},
        {'mnemo':'SBC','hook':self.absolute},
        {'mnemo':'INC','hook':self.absolute},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'BEQ','hook':self.relative},
        {'mnemo':'SBC','hook':self.indzeroy},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'SBC','hook':self.zeropagex},
        {'mnemo':'INC','hook':self.zeropagex},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'SED','hook':self.inherent},
        {'mnemo':'SBC','hook':self.absoly},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'???','hook':self.inherent},
        {'mnemo':'SBC','hook':self.absolx},
        {'mnemo':'INC','hook':self.absolx},
        {'mnemo':'???','hook':self.inherent},]

    def __oneLine(self):
        label_line = ""
        if self.__pc in self.__addr16label.keys():
            label_line = "%s %s:\n"%(word2hex(self.__pc), self.__addr16label[self.__pc])
            line = word2hex(None)
        else:
            label_line = ""
            line = word2hex(self.__pc)
        byte = self.__getNextByte()
        return "%s%s %s\n"%(label_line, line, self.__mnemo[byte]["hook"](byte))

    def setAddr16Table(self, table):
        self.__addr16label = table

    def desass(self, addr, get_byte_hook, nb_lines=24):
        self.__pc = addr
        self.__getByte = get_byte_hook
        text = ""
        while nb_lines:
            text += self.__oneLine()
            nb_lines -= 1
        return text

    def __getNextByte(self):
        byte = self.__getByte(self.__pc)
        self.__pc += 1
        return byte

    def GetPc(self):
        return self.__pc

    def Add1Value(self,value1):
        return "%s %s %s"%(byte2hex(value1), byte2hex(None), byte2hex(None))

    def Add2Values(self,value1,value2):
        return "%s %s %s"%(byte2hex(value1), byte2hex(value2), byte2hex(None))

    def Add3Values(self,value1,value2,value3):
        return "%s %s %s"%(byte2hex(value1), byte2hex(value2), byte2hex(value3))

    def GetRel(self,byterel):
        if byterel<128:
            return self.GetPc()+byterel
        else:
            return self.GetPc()-256+byterel

    #----------------#
    # Mnemonic Hooks #
    #----------------#

    def immediate(self,opcode):
        b2 = self.__getNextByte()
        retval = "%s %s "%(self.Add2Values(opcode,b2), self.__mnemo[opcode]["mnemo"])
        retval += "#%s"%byte2hex(b2)
        return retval

    def inherent(self,opcode):
        return "%s %s"%(self.Add1Value(opcode), self.__mnemo[opcode]["mnemo"])

    def zeropage(self,opcode):
        b2 = self.__getNextByte()
        retval = "%s %s "%(self.Add2Values(opcode,b2), self.__mnemo[opcode]["mnemo"])
        retval += byte2hex(b2)
        return "%s"%retval

    def zeropagex(self,opcode):
        b2 = self.__getNextByte()
        retval = "%s %s "%(self.Add2Values(opcode,b2), self.__mnemo[opcode]["mnemo"])
        retval += " %s,X"%byte2hex(b2)
        return retval

    def zeropagey(self,opcode):
        b2 = self.__getNextByte()
        retval = "%s %s "%(self.Add2Values(opcode,b2), self.__mnemo[opcode]["mnemo"])
        retval += "%s,Y"%(byte2hex(b2))
        return retval

    def indzerox(self,opcode):
        b2 = self.__getNextByte()
        retval = "%s %s "%(self.Add2Values(opcode,b2), self.__mnemo[opcode]["mnemo"])
        retval += "(%s,X)"%(byte2hex(b2))
        return retval

    def indzeroy(self,opcode):
        b2 = self.__getNextByte()
        retval = "%s %s "%(self.Add2Values(opcode,b2), self.__mnemo[opcode]["mnemo"])
        retval += "(%s),Y"%(byte2hex(b2))
        return retval

    def absolute(self,opcode):
        b2 = self.__getNextByte()
        b3 = self.__getNextByte()
        value = b3*256+b2
        valuestr = word2hex(value)
        if value in self.__addr16label.keys():
            valuestr=self.__addr16label[value]
        retval = "%s %s "%(self.Add3Values(opcode,b2,b3), self.__mnemo[opcode]["mnemo"])
        retval+="%s"%valuestr
        return retval

    def absolx(self,opcode):
        b2 = self.__getNextByte()
        b3 = self.__getNextByte()
        value =b3*256+b2
        valuestr = word2hex(value)
        if value in self.__addr16label.keys():
            valuestr=self.__addr16label[value]
        retval = "%s %s "%(self.Add3Values(opcode,b2,b3), self.__mnemo[opcode]["mnemo"])
        retval += "%s,X"%valuestr
        return retval

    def absoly(self,opcode):
        b2 = self.__getNextByte()
        b3 = self.__getNextByte()
        value = b3*256+b2
        valuestr = word2hex(value)
        if value in self.__addr16label.keys():
            valuestr=self.__addr16label[value]
        retval = "%s %s "%(self.Add3Values(opcode,b2,b3), self.__mnemo[opcode]["mnemo"])
        retval+="%s,Y"%valuestr
        return retval

    def indirect(self,opcode):
        b2 = self.__getNextByte()
        b3 = self.__getNextByte()
        value = b3*256+b2
        valuestr = word2hex(value)
        if value in self.__addr16label.keys():
            valuestr=self.__addr16label[value]
        retval = "%s %s "%(self.Add3Values(opcode,b2,b3), self.__mnemo[opcode]["mnemo"])
        retval+="(%s)"%valuestr
        return retval

    def relative(self,opcode):
        b2 = self.__getNextByte()
        target = self.GetRel(b2)
        retval = "%s %s "%(self.Add2Values(opcode,b2), self.__mnemo[opcode]["mnemo"])
        retval += "%s"%word2hex(target)
        return retval

class DESASS_ANTIC():
    def __init__(self):
        self.__pc = None
        self.__getByte = None
        self.__addr16label={}
        self.__data_end = None

    def __getNextByte(self):
        byte = self.__getByte(self.__pc)
        self.__pc += 1
        return byte

    def __oneLine(self):
        pc = self.__pc
        byte1 = self.__getNextByte()
        byte2 = None
        byte3 = None
        line = ""

        if (byte1 & 0x0f) in [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]:
            line += "MODE_%02d"%(byte1 & 0x0f)
            if byte1 & 0x10:
                line += " | HSCROL_ON"
            if byte1 & 0x20:
                line += " | VSCROL_ON"
            if byte1 & 0x80:
                line += " | DLI_ON"
            if byte1 & 0x40:
                byte2 = self.__getNextByte()
                byte3 = self.__getNextByte()
                target = byte2 + byte3 * 256
                if target in self.__addr16label.keys():
                    valuestr = self.__addr16label[target]
                else:
                    valuestr = word2hex(byte2 + byte3 * 256)
                line += " | setScreenMemory %s"%valuestr
        elif byte1 in [0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70, ]:
            line += "BLANK_%02d"%(byte1 / 16 + 1)
        elif byte1 == 0x01:
                byte2 = self.__getNextByte()
                byte3 = self.__getNextByte()
                target = byte2 + byte3 * 256
                if target in self.__addr16label.keys():
                    valuestr = self.__addr16label[target]
                else:
                    valuestr = word2hex(byte2 + byte3 * 256)
                line += "jmp %s"%valuestr
        elif byte1 == 0x41:
                byte2 = self.__getNextByte()
                byte3 = self.__getNextByte()
                target = byte2 + byte3 * 256
                if target in self.__addr16label.keys():
                    valuestr = self.__addr16label[target]
                else:
                    valuestr = word2hex(byte2 + byte3 * 256)
                line += "jmp %s & wait VBI"%valuestr
                self.__data_end = True
        else:
            line += "unknow ANTIC opcode %s"%byte2hex(byte1)
        if pc in self.__addr16label.keys():
            prefix = "%s %s:\n%s"%(word2hex(pc), self.__addr16label[pc], word2hex(None))
        else:
            prefix = word2hex(pc)
        ret_line = "%s %s %s %s %s\n"%(prefix, byte2hex(byte1), byte2hex(byte2), byte2hex(byte3), line)
        return ret_line

    def setAddr16Table(self, table):
        self.__addr16label = table

    def desass(self, addr, get_byte_hook):
        self.__data_end = False
        self.__pc = addr
        self.__getByte = get_byte_hook
        text = ""
        while not self.__data_end:
            text += self.__oneLine()
        return text

class DESASS_8():
    def __init__(self):
        self.__pc = None
        self.__getByte = None
        self.__addr16label={}

    def __getNextByte(self):
        byte = self.__getByte(self.__pc)
        self.__pc += 1
        return byte

    def setAddr16Table(self, table):
        self.__addr16label = table

    def desass(self, addr, get_byte_hook, nb_bytes=256):
        text = ""
        self.__pc = addr
        self.__getByte = get_byte_hook
        index = 0
        line = ""
        while nb_bytes:
            pc = self.__pc
            byte = self.__getNextByte()
            if pc in self.__addr16label.keys():
                text += "%s %s:\n%s .byte %s\n"%(word2hex(pc), self.__addr16label[pc], word2hex(None), byte2hex(byte))
            else:
                text += "%s .byte %s\n"%(word2hex(pc), byte2hex(byte))
            nb_bytes -= 1
        return text

class DESASS_16():
    def __init__(self):
        self.__pc = None
        self.__getByte = None
        self.__addr16label={}

    def __getNextByte(self):
        byte = self.__getByte(self.__pc)
        self.__pc += 1
        return byte

    def setAddr16Table(self, table):
        self.__addr16label = table

    def desass(self, addr, get_byte_hook, nb_bytes=256):
        text = ""
        self.__pc = addr
        self.__getByte = get_byte_hook
        index = 0
        line = ""
        while nb_bytes:
            pc = self.__pc
            byte1 = self.__getNextByte()
            byte2 = self.__getNextByte()
            value = byte1 + byte2 * 256
            if value in self.__addr16label.keys():
                valuestr = self.__addr16label[value]
            else:
                valuestr = word2hex(value)
            if pc in self.__addr16label.keys():
                text += "%s %s:\n%s .word %s\n"%(word2hex(pc), self.__addr16label[pc], word2hex(None), valuestr)
            else:
                text += "%s .word %s\n"%(word2hex(pc), valuestr)
            nb_bytes -= 1
        return text

class MEMORY:
    def __init__(self, endianess=LITTLE_ENDIAN):
        self.endianess = endianess
        self.data      = [0 for x in range(MEMORY_SIZE)]
        self.modified  = [NOT_MODIFIED for x in range(MEMORY_SIZE)]

    def setPC(self, pc):
        self.__pc = pc

    def getByte(self):
        byte = mem.peek(self.__pc)
        self.__pc = (self.__pc + 1) & 0xff
        return byte

    def __str__(self):
        return "<MEMORY_instance 0x%x bytes v 0.99>"%MEMORY_SIZE

    def poke(self, addr, value, strict=1):
        if addr >= MEMORY_SIZE or addr < 0:
            raise Exception("addr 0x%x is out of range"%addr)
        if value > BYTE_MAX_VALUE or value < BYTE_MIN_VALUE:
            raise Exception("byte 0x%x is out of range"%value)
        self.data[addr] = value
        if strict:
            if self.modified[addr] != NOT_MODIFIED:
                raise Exception("addr 0x%x is overwritten!"%addr)
        self.modified[addr] = MODIFIED

    def wpoke(self, addr, value):
        lovalue = value & 0xff
        hivalue = value / 0x100
        if self.endianess == BIG_ENDIAN:
            self.poke(addr, hivalue)
            self.poke(addr + 1, lovalue)
        elif self.endianess == LITTLE_ENDIAN:
            self.poke(addr, lovalue)
            self.poke(addr + 1, hivalue)
        else:
            raise Exception("unknown endianess!")

    def peek(self, addr):
        if addr >= MEMORY_SIZE or addr < 0:
            raise Exception("addr 0x%x is out of range"%addr)
        return self.data[addr]

    def wpeek(self, addr):
        if self.endianess == BIG_ENDIAN:
            hivalue = self.peek(addr)
            lovalue = self.peek(addr + 1)
        elif self.endianess == LITTLE_ENDIAN:
            hivalue = self.peek(addr + 1)
            lovalue = self.peek(addr)
        else:
            raise Exception("unknown endianess!")
        return hivalue * 256 + lovalue

    def getModifiedRange(self, start=0):
        modified = []
        for x in range(start,MEMORY_SIZE):
            if self.modified[x]:
                modified.append(x)
        if len(modified):
            return (modified[0], modified[-1] - modified[0] + 1)

    def getMemlo(self, start=0):
        # returns address of first not modified byte after last modified bytes area
        memlo = None
        for addr in range(start,MEMORY_SIZE):
            if self.modified[addr]:
                memlo = addr
        if memlo == None:
            return 0
        else:
            return memlo + 1

    def getModifiedSize(self, start=0):
        # returns quantity of modified bytes
        count = 0
        for addr in range(start,MEMORY_SIZE):
            if self.modified[addr]:
                count += 1
        return count

    def getBloc(self, start, size):
        text = ""
        max = start+size
        for addr in range(start, start+size):
            text += chr(self.peek(addr))
        return text

    def dump(self, addr):
        text = ""
        for index in range(DUMP_SIZE):
            if index % 16 == 0:
                asciibuffer = ""
                text += "%04x "%(addr + index)
            text += "%02x "%self.peek(addr + index)
            asciibuffer += getGlyphe(self.peek(addr + index))
            if index % 16 == 15:
                text += asciibuffer + "\n"
        return text

    def getByte(self, fp):
        car = fp.read(1)
        if car == '':
            return None
        return ord(car)

    def getWord(self, fp):
        # *** WARNING! In an Atari binary file, 16 bits values are in LITTLE ENDIAN! ***
        byte2 = self.getByte(fp)
        byte1 = self.getByte(fp)
        if byte2 == None:
            return None
        return byte1 * 256 + byte2

    def getSegment(self, fp):
        start = self.getWord(fp)
        if start == None:
            return None
        if start == EXE_FILE_MAGIC_NUMBER:
            start = self.getWord(fp)
        last = self.getWord(fp)
        if last == None:
            raise Exception("Unexpected end of executable file!")
        size = 1 + last - start
        bytes = fp.read(size)
        if len(bytes) != size:
            raise Exception("Unexpected end of executable file!")
        return (start, bytes)

    def loadFile(self, fname, addr=0, verbose=False):
        fp = open(fname, 'rb')
        bytes = fp.read(-1)
        for car in bytes:
            if addr > MEMORY_SIZE:
                raise Exception("%s Loading out of memory range!"%fname)
            self.poke(addr, ord(car))
            addr += 1
        return len(bytes)

    def loadAtariBinaryFile(self, fname, verbose=False, strict=True):
        fp = open(fname, 'rb')
        if self.getWord(fp) != EXE_FILE_MAGIC_NUMBER:
            raise Exception("%s is not an executable file!"%shortname)
        while 1:
            bloc = self.getSegment(fp)
            if bloc == None:
                break
            if verbose:
                sys.stdout.write("$%04x %d\n"%(bloc[0], len(bloc[1])))
            addr = bloc[0]
            bytes = bloc[1]
            for index in range(len(bytes)):
                self.poke(addr + index, ord(bytes[index]), strict=strict)

    def loadAtariBootDisk(self, dname):
        fp = open(dname, 'rb')
        flags = self.getByte(fp)
        self.poke(DFLAGS, flags)
        nb_sectors = self.getByte(fp)
        size = nb_sectors * SECTOR_SIZE
        start_addr = self.getWord(fp)
        self.wpoke(BOOTAD, start_addr)
        init_addr = self.getWord(fp)
        self.wpoke(DOSINI, init_addr)
        fp.seek(0)
        addr = start_addr# - BOOT_HEADER_SIZE
        try:
            for x in range(size):
                self.poke(addr + x, self.getByte(fp))
        except:
            raise Exception("Unexpected end of disk!")

    def compare(self, other, max=20):
        differences = 0
        text = ""
        for addr in range(MEMORY_SIZE):
            if self.peek(addr) != other.peek(addr):
                text += "%04x %02x %02x\n"%(addr, self.peek(addr), other.peek(addr))
                differences += 1
                if differences == max:
                    text += "Too much errors, abort!\n"
                    break
        return text

    def find(self, bytes, start=0, stop=MEMORY_SIZE, max_occurences=MEMORY_SIZE):
        addresses = []
        size = len(bytes)
        max_index = size - 1
        for addr in range(start, stop):
            for index in range(size):
                if self.peek(addr + index) != bytes[index]:
                    break
                elif index == max_index:
                    addresses.append(addr)
                    if len(addresses) == max_occurences:
                        break
        return addresses

    def map(self):
        values = []
        for pagenum in range(0x100):
            addr = pagenum * 0x100
            addr_max = addr + 0x100
            while(1):
                if addr == addr_max:
                    values.append("  ")
                    break
                if self.modified[addr] != NOT_MODIFIED:
                    values.append(" X")
                    break
                addr += 1
        text = ""
        for pagenum in range(0x100):
            addr = pagenum * 0x100
            if not pagenum % 16:
                text += "%04x "%addr
            text += "%s"%values[pagenum]
            if pagenum % 16 == 15:
                text += "\n"
        return text

    def load(self, fname, addr=0, size=None):
        with open(fname, 'rb') as fp:
            body = fp.read(-1)
        if size == None:
            size = len(body)
        if addr + size > MEMORY_SIZE:
            size = MEMORY_SIZE - addr
        body = body[:size]
        for car in body:
            self.poke(addr, ord(car))
            addr += 1

    def getBitmap(self, byte):
        text = " // "
        for cpt in range(8):
            if byte & 0x80:
                text += ONE
            else:
                text += ZERO
            byte <<= 1
        return text

    def getDatalines(self, data, cols=8, glypheview=0):
        datalines = ""
        max = len(data) -1
        if cols == 1:
            for index, byte in enumerate(data):
                line = "    0x%02x"%byte
                if index == max:
                    line += ' '
                else:
                    line += ','
                if glypheview:
                    line += self.getBitmap(byte)

                line += CR
                datalines += line
        else:
            for index, byte in enumerate(data):
                if index % cols == 0:
                    datalines += "    "
                datalines += "0x%02x"%byte
                if index == max:
                    datalines += ' '
                else:
                    datalines += ','
                if (index % cols == (cols - 1)) or (index == max):
                    datalines += "\n"
        return datalines

    def bytes2C(self, start, size, fbasename, dataname, cols=8, glypheview=0):
        data = [self.peek(pbyte) for pbyte in range(start, start + size)]
        headername = "%s.h"%(fbasename)
        headerbody = TEMPLATE_HEADER
        headerbody = headerbody.replace("%LABEL%", fbasename.upper())
        headerbody = headerbody.replace("%DATANAME%", dataname)
        headerbody = headerbody.replace("%SIZE%", "%u"%size)
        headerbody = headerbody.replace("%SIZENAME%", dataname.upper())
        with open(headername, "w") as fp:
            fp.write(headerbody)
        sourcename = "%s.c"%(fbasename)
        sourcebody = TEMPLATE_SOURCE
        sourcebody = sourcebody.replace("%HEADERNAME%", headername)
        sourcebody = sourcebody.replace("%DATANAME%", dataname)
        sourcebody = sourcebody.replace("%SIZE%", "%u"%size)
        datalines = self.getDatalines(data, cols, glypheview)
        sourcebody = sourcebody.replace("%VALUES%", datalines)
        with open(sourcename, "w") as fp:
            fp.write(sourcebody)

if __name__ == '__main__':

    from disk import *

    def utest():
        mem=MEMORY()
        mem.poke(0x1000, 255)
        mem.poke(0x1fff, 255)
        start, size = mem.getModifiedRange()
        assert start == 0x1000
        assert size == 0x1000

        mem=MEMORY(endianess=BIG_ENDIAN)
        mem.poke(0, 0x12)
        mem.poke(1, 0x34)
        assert mem.wpeek(0) == 0x1234
        mem.wpoke(5, 0xcafe)
        assert mem.peek(5) == 0xca
        assert mem.peek(6) == 0xfe

        mem=MEMORY()
        mem.poke(0, 0x12)
        mem.poke(1, 0x34)
        mem.endianess = LITTLE_ENDIAN
        assert mem.wpeek(0) == 0x3412
        mem.wpoke(5, 0xcafe)
        assert mem.peek(5) == 0xfe
        assert mem.peek(6) == 0xca

        mem=MEMORY()
        for x in range(256):
            mem.poke(34567 + x, x)
        start, size = mem.getModifiedRange()
        assert start == 34567
        assert size == 0x100
        bytes = mem.getBloc(start, size)
        for index, car in enumerate(bytes):
            assert ord(car) == index

        mem=MEMORY()
        mem.poke(34567, 1)
        memlo = mem.getMemlo()
        assert memlo == 34568
        mem=MEMORY()
        memlo = mem.getMemlo()
        assert memlo == 0

        sys.stdout.write("A L L   T E S T S   P A S S E D !\n")

    utest()

    from disk import *

    disk = VIRTUAL_DISK("./../out/DISK.XFD")
    #~ sys.stdout.write(str(disk.directory()))
    bytes = disk.readFile("A")
    with open("./A", "wb") as fp:
        fp.write(bytes)
    mem = MEMORY()
    mem.loadAtariBinaryFile("A", strict=False)
    sys.stdout.write("MEMLO 0x%04x %05d\n"%(mem.getMemlo(), mem.getMemlo()))
    sys.stdout.write("USED  0x%04x %05d\n"%(mem.getModifiedSize(), mem.getModifiedSize()))
    sys.stdout.write(mem.dump(9000))


import sys
import logging

primary_file_name = str(sys.argv[1])
secondary_file_name = str(sys.argv[2])
tagfreq_file_name = str(sys.argv[3])
primary_file_desc = open(primary_file_name,'r')
secondary_file_desc = open(secondary_file_name,'r')
tagfreq_file_desc = open(tagfreq_file_name,'r')
output_file_desc = open("likelihood.in",'w')
logging.basicConfig(filename='likelihood.log',level=logging.DEBUG)

logging.info("Tag Index Processing Started.")
tag_dict = {}
for line in tagfreq_file_desc.readlines():
	temp = line.split("|")
	tag = str(temp[0])
	freq = int(temp[1])
	tag_dict[tag] = freq
logging.info("Tag Index Processing ended.")

logging.info("Writing to likelihood.in Started.")
count=0
for line in secondary_file_desc.readlines():
	temp = line.strip().split(":")
	word = str(temp[0])
	offset = int(temp[1].split(";")[0])
	primary_file_desc.seek(offset)
	temp = primary_file_desc.readline().split(";")
	for tag_freq_pair in temp:
		tag = str(tag_freq_pair.split("|")[0])
		freq = int(tag_freq_pair.split("|")[1])
		if tag in tag_dict:
			likelihood = float(freq)/tag_dict[tag]
			output_string = word + ";" + tag + "|" + str(likelihood) + "\n"
			output_file_desc.write(output_string)
			count+=1
logging.info("Number of word;tag pairs : " + str(count))
logging.info("Writing to likelihood.in ended.")


from unicorn import *
from capstone import *
from keystone import *

import serial
import struct
import time

from uart_interface import *
usbuart = serial.Serial('/dev/ttyUSB0', 115200)
uartinterface = UartInterface(usbuart,False)
p = ProxyUart(uartinterface,False)

def assembly(MIPS_CODE):
    md = Cs(CS_ARCH_MIPS,CS_MODE_MIPS32+CS_MODE_BIG_ENDIAN)
    for instruction in md.disasm(MIPS_CODE,0x1000):
        print("0x%x:\t%s\t%s" % (instruction.address, instruction.mnemonic, instruction.op_str))

addr = 0x80020000
limit = addr+1000
l = b""

while(addr < limit):
    c = p.read32(addr)
    ch = c.to_bytes(4,'big')
    l += ch
    print(str(hex(addr)) + ": " + str(hex(c)))
    addr +=4

print("-------------------------------")
assembly(l)


from cx_Freeze import setup, Executable
import pygame._view
import sys

base = None
if sys.platform == "win32":
	base = "Win32GUI"

excludes = ["numpy","wx","lib2to3","urllib","pydoc","PodSixNet.Channel",
		"PodSixNet.Server","PodSixNet.Connection","asynchat","asyncore"]

includes = ["re","pygame", "pygame._view", "tkinter", "tkinter.filedialog", "json"]
includefiles = ["fonts","classes", "images"]

setup(name = "GMS2 Room Editor",version = "1",description = "External Room Editor for GameMaker Studio 2",
	executables = [Executable("main.py", base = base)],
	options = {"build_exe": {"excludes":excludes, "includes":includes, 'include_files':includefiles}})


import sys

input_file = open(sys.argv[1])
vars_from_file = lambda: [int(x) for x in input_file.readline().split()]

V, E, R, C, X = vars_from_file()
Vsizes = vars_from_file()

assert V == len(Vsizes), "%d != %s" % (V, Vsizes)  # Number of cache servers
cache_sizes = [X] * C
cache_latencies = {}
datacenter_latencies = {}

for endpoint_id in range(E):
    datacenter_latency, number_of_caches = vars_from_file()
    datacenter_latencies[endpoint_id] = datacenter_latency
    for cache in range(number_of_caches):
        cache_id, cache_latency = vars_from_file()

        cache_latencies[(cache_id, endpoint_id)] = cache_latency

def get_cache_latency(cache_id, endpoint_id):
    return cache_latencies.get((cache_id, endpoint_id), None)
    # eger None'sa baglanti yok

def get_datacenter_latency(endpoint_id):
    r = datacenter_latencies.get(endpoint_id, None)
    assert r is not None, "Oup"
    return r
    # eger none geliyorsa bi yerde hata yapilmis

endpoint_video_requests = {}
for request in range(R):
    video_id, endpoint_id, number_of_requests = vars_from_file()
    endpoint_video_requests[(video_id, endpoint_id)] = number_of_requests

def get_endpoint_video_requests(video_id, endpoint_id):
    return endpoint_video_requests.get((video_id, endpoint_id), 0)

videos_and_caches = {}

def add_video_to_cache(cache_id, video_id):
    videos_and_caches.setdefault(cache_id, [])
    if video_id in videos_and_caches[cache_id]:
        raise Exception("Video already added")
    cache_sizes[cache_id] -= Vsizes[video_id]
    assert cache_sizes[cache_id] >= 0, "There is no enough space on cache"
    videos_and_caches[cache_id] += [video_id]

def can_add_video_to_cache(cache_id, video_id):
    videos = videos_and_caches.get(cache_id, [])
    if video_id in videos:
        return False
    if cache_sizes[cache_id] < Vsizes[video_id]:
        return False
    return True

def generate_output():
    print(len(list(videos_and_caches.keys())))
    for cache, videos in videos_and_caches.items():
        print("%d %s" % (cache, " ".join([str(v) for v in videos])))

# Check if all values are used
eof = input_file.readline()
assert not eof, "I got: `%s`" % eof
# CODE HERE

# for video_id in range(V):
#     for cache_id in range(C):
#         if can_add_video_to_cache(cache_id, video_id):
#             add_video_to_cache(cache_id, video_id)
#             break
for cache_id in range(C):
    requests  = []
    for endpoint_id in range(E):
        if get_cache_latency(cache_id, endpoint_id) is not None:
            for video_id in range(V):
                number_of_requests = get_endpoint_video_requests(video_id, endpoint_id)
                if number_of_requests:
                    requests.append([video_id, number_of_requests])
    requests = sorted(requests,reverse=True, key=lambda x: x[1])
    requests = [t[0] for t in requests]
    for video_id in requests:
        if can_add_video_to_cache(cache_id, video_id):
            add_video_to_cache(cache_id, video_id)

generate_output()


from django.contrib import admin
from edc_fieldsets.fieldlist import Insert
from edc_fieldsets.fieldsets_modeladmin_mixin import FormLabel
from edc_model_admin import audit_fieldset_tuple

from ...admin_site import flourish_facet_admin
from ...forms import FacetChildMedicalHistoryForm
from ...models import FacetChildMedicalHistory
from ..modeladmin_mixins import CrfModelAdminMixin

@admin.register(FacetChildMedicalHistory, site=flourish_facet_admin)
class FacetChildMedicalHistoryAdmin(CrfModelAdminMixin, admin.ModelAdmin):

    form = FacetChildMedicalHistoryForm

    list_display = (
        'facet_visit', 'chronic_since')
    list_filter = ('chronic_since',)

    fieldsets = (
        (None, {
            'fields': [
                'facet_visit',
                'report_datetime',
                'chronic_since',
                'child_chronic',
                'child_chronic_other',
                'current_illness',
                'current_symptoms',
                'current_symptoms_other',
                'symptoms_start_date',
                'seen_at_local_clinic',
                'currently_taking_medications',
                'current_medications',
                'current_medications_other',
                'duration_of_medications',

            ]}
         ), audit_fieldset_tuple)

    radio_fields = {'chronic_since': admin.VERTICAL,
                    'med_history_changed': admin.VERTICAL, }

    filter_horizontal = ('child_chronic',)

    custom_form_labels = [
        FormLabel(
            field='med_history_changed',
            label=('Since the last scheduled visit in {previous}, has any of '
                   'your medical history changed?'),
            previous_appointment=True)
    ]

    quartely_schedules = ['child_a_sec_qt_schedule1', 'child_a_quart_schedule1',
                          'child_b_sec_qt_schedule1', 'child_b_quart_schedule1',
                          'child_c_sec_qt_schedule1', 'child_c_quart_schedule1',
                          'child_pool_schedule1', 'child_a_fu_schedule1',
                          'child_b_fu_schedule1', 'child_c_fu_schedule1',
                          'child_a_fu_qt_schedule1', 'child_b_fu_qt_schedule1',
                          'child_c_fu_qt_schedule1']

    radio_fields = {'chronic_since': admin.VERTICAL,
                    'currently_taking_medications': admin.VERTICAL,
                    'duration_of_medications': admin.VERTICAL,
                    'current_illness': admin.VERTICAL,
                    'seen_at_local_clinic': admin.VERTICAL,
                    'med_history_changed': admin.VERTICAL}

    filter_horizontal = (
        'child_chronic', 'current_symptoms', 'current_medications')

    conditional_fieldlists = {}
    for schedule in quartely_schedules:
        conditional_fieldlists.update(
            {schedule: Insert('med_history_changed', after='report_datetime')})

    def get_form(self, request, obj=None, *args, **kwargs):
        form = super().get_form(request, *args, **kwargs)
        form.previous_instance = self.get_previous_instance(request)
        return form


def solution(str1, str2):
    str1 = str1.lower()
    str2 = str2.lower()
    arr1 = []
    arr2 = []

    for i in range(len(str1)-1) :
        word1 = str1[i:i+2]
        if word1.isalpha() :
            arr1.append(word1)

    for j in range(len(str2)-1) :
        word2 = str2[j:j+2]
        if word2.isalpha() :
            arr2.append(word2)

    print(arr1, arr2)

    if not arr1 and not arr2 :
        return 65536

    else :
        plus = []
        cross = []

        for k in arr1 :
            if k in arr2 :
                arr2.remove(k)
                cross.append(k)

        plus = arr1 + arr2

        answer = (len(cross) / len(plus)) * 65536
        return int(answer)

프로그래머스/lv2/17677. ［1차］ 뉴스 클러스터링/［1차］ 뉴스 클러스터링.py

［1차］ 뉴스 클러스터링.py


"""
    215. Kth Largest Element in an Array

    Find the kth largest element in an unsorted array. Note that it is the kth largest element in the sorted order, not the kth distinct element.

    For example,
    Given [3,2,1,5,6,4] and k = 2, return 5.

    Note:
    You may assume k is always valid, 1 ≤ k ≤ array's length.
"""

import random
class Solution(object):
    def findKthLargest(self, nums, k):
        """
        :type nums: List[int]
        :type k: int
        :rtype: int
        """
        rand = random.randint(0,len(nums)-1)
        p = nums[rand]
        small = []
        large = []

        for i in xrange(len(nums)):
            if i != rand:
                if nums[i] < p:
                    small.append(nums[i])
                else:
                    large.append(nums[i])
        if len(large) == k - 1:
            return p
        if len(large) > k - 1:
            return self.findKthLargest(large , k )
        if len(large) < k - 1:
            return self.findKthLargest(small, k - len(large) -  1)


from urllib.parse import urlparse

import requests
from django.core.files.base import ContentFile
from django.core.management.base import BaseCommand
from places.models import Place, Image

def get_filename(url):
    image_path = urlparse(url).path
    filename = image_path.split('/')[-1]
    return filename

class Command(BaseCommand):
    help = 'Loads places description and photos to database'

    def add_arguments(self, parser):
        parser.add_argument('url', type=str)

    def handle(self, *args, **options):
        response = requests.get(options['url'])
        response.raise_for_status()
        payload = response.json()

        place, created = Place.objects.update_or_create(
            title=payload['title'],
            description_short=payload['description_short'],
            lng=payload['coordinates']['lng'],
            lat=payload['coordinates']['lat'],
            defaults={'description_long': payload['description_long']}
        )

        image_urls = payload['imgs']
        if not created:
            place.imgs.all().delete()

        for number, url in enumerate(image_urls):
            image = Image.objects.create(place=place, number=number)
            image_response = requests.get(url)
            image_response.raise_for_status()
            content = ContentFile(image_response.content)
            filename = get_filename(url)
            image.photo.save(filename, content, save=True)


from AsteroidsCore import *
import random
def spriteGroup(*lst):
    return pygame.sprite.Group (*lst)

GameColors = ({
            'black':'#000000',
            'white':'#ffffff',
            'red'  :'#ff0000',
            'green':'#00ff00',
            'blue' :'#0000ff'
            })

gameover = ImageLoad ('Dead.png')
GameOverSprt = GameObject(end=[EasyConfigSurface().resize(gameover.loadedSprite,640,480)])
GGameOver = pygame.sprite.Group ()
GGameOver.add (GameOverSprt)

Planets = ImageLoad ('Planets.png')
PlanetList = []
PlanetList.append (Planets.manualSplit(0,0,160,166))
PlanetList.append(Planets.manualSplit(160,0,160,158))
PlanetList.append(Planets.manualSplit(160+160,0,170,166))
PlanetList.append(Planets.manualSplit(160+160+172,0,180,160))
PlanetList.append(Planets.manualSplit(160+160+170+180,0,166,164))
PlanetList.append(Planets.manualSplit(160+160+170+180+166,0,157,157))

Gplanet = pygame.sprite.Group ()
PlanetSprite = AnimateGameElements (Planet = random.choice(PlanetList))
PlanetSprite.warp(random.randint (100,640), random.randint (0,480))
Gplanet.add(PlanetSprite)

starz = ImageLoad ('stars.png')
manuallist = []
for index in range(0,48,16): #sprites
    manuallist.append(starz.manualSplit(index,0,16,14)[0])

Gstars = pygame.sprite.Group ()
for i in range(0,100,1):
    choiced = []
    for randomstars in range(0,len(manuallist),1):
        choiced.append(random.choice (manuallist))
    StarsSprite = AnimateGameElements (Glow = choiced)
    StarsSprite.warp(random.randint (0,640), random.randint (0,480))
    Gstars.add (StarsSprite)

dogyclip = ImageLoad ('Animal2.png')
dogyclip=dogyclip.autoSplit(40,40, autocolorkey=True)
playerone = Player \
                    (right= [dogyclip[2],dogyclip[6],dogyclip[10]],
                     up   = [dogyclip[3],dogyclip[7],dogyclip[11]],
                     down = [dogyclip[0],dogyclip[4],dogyclip[8]],
                     left = [dogyclip[1],dogyclip[5],dogyclip[9]])

playerone.setSpeed(2,2)
playerone.warp(150,150)
GPlayerone = spriteGroup(playerone)

AsteroidSprite= ImageLoad ('asteroid3.png') #Big Asteroid
Asteroidclip = AsteroidSprite.autoSplit(32,32)
rotatedanim  =  [Asteroidclip[0],Asteroidclip[4], Asteroidclip[8],Asteroidclip[12],Asteroidclip[16]]

blastSprite = ImageLoad ('Blast.png')
blastSprite = blastSprite.autoSplit(100,100)
blastlist = []
for count in range(32,45,1):
    resized = EasyConfigSurface().resize (blastSprite[count], 32,32)
    blastlist.append(resized)

GAsteroidz = pygame.sprite.Group()
for cout in range(0,20,1):
    Ast = Monster (rotate = rotatedanim,
                   zap = blastlist) #Sprite for rotation animation Asteroid
    Ast.direction = 'rotate'
    Ast.setSpeed(random.randint(0,5),random.randint(0,5)) #SpeedAsteriod If moved
    Ast.warp(random.randint(10,600),random.randint(10,400)) #StartPos Asteroid
    Ast.changedirectionvector(random.randint(-1,1),random.randint(-1,1)) #Move Asteroid
    GAsteroidz.add (Ast) #Get Group

GBullet = pygame.sprite.Group ()
BulletPic = ImageLoad('Bulletz.png').manualSplit(0,0,9,12)

pygame.init()
screen = pygame.display.set_mode ([640,480])
FPS = pygame.time

lives = Label ('Data 70 LET.ttf', 30)
lives.text = 'Lives: '+ str (playerone.Lives)
lives.color = GameColors['green']

playerScore = 0
score = Label ('Data 70 LET.ttf', 28)
score.text = 'Score: '+ str (playerScore)
score.color = GameColors['green']

WinText = Label ('Data 70 LET.ttf', 50)
WinText.text = 'You win! Game loose. ' \
               'End.'
WinText.color = GameColors['green']

playeroneanimationEvent = pygame.USEREVENT
FPS.set_timer (playeroneanimationEvent ,60)
FPS.set_timer (playeroneanimationEvent+1, 750)

ifmainwindowclose = False
counter = False

def keys ():
    keys =  pygame.key.get_pressed()
    if keys [pygame.K_RIGHT] and keys[pygame.K_UP]:
        playerone.moveElement(1,-1, 'right')
    elif keys [pygame.K_LEFT] and keys[pygame.K_UP]:
        playerone.moveElement(-1,-1, 'left')
    elif keys [pygame.K_LEFT] and keys[pygame.K_DOWN]:
        playerone.moveElement(-1,1, 'left')
    elif keys [pygame.K_RIGHT] and keys[pygame.K_DOWN]:
        playerone.moveElement(1,1, 'right')

    elif keys[pygame.K_UP]:
        playerone.moveElement(0,-1,'up')

    elif keys[pygame.K_DOWN]:
        playerone.moveElement(0,1, 'down')

    elif keys [pygame.K_LEFT]:
        playerone.moveElement(-1,0,'left')

    elif keys [pygame.K_RIGHT]:
        playerone.moveElement(1,0, 'right')

    if not (keys [pygame.K_RIGHT])and  \
       not (keys[pygame.K_LEFT])  and  \
       not (keys[pygame.K_DOWN])  and  \
       not (keys[pygame.K_UP]):
           playerone.image = playerone.clips[playerone.direction][0]

while not ifmainwindowclose:
    for event in pygame.event.get():
        if event.type ==pygame.QUIT:
            ifmainwindowclose = True

        if event.type == playeroneanimationEvent:
            playerone.animate()
            GAsteroidz.update(640,480)

        if event.type == playeroneanimationEvent+1:
            Gstars.update()

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_s:
                if len(GBullet) < 3:
                    BulletSprt = Bullets (left=BulletPic)
                    BulletSprt.warp(playerone.rect.x, playerone.rect.y)
                    BulletSprt.setSpeed (5,5)
                    GBullet.add (BulletSprt)
                    BulletSprt.warp(playerone.rect.x+12, playerone.rect.y+12)
                    BulletSprt.MoveWhereX, BulletSprt.MoveWhereY = playerone.MoveWhereX, playerone.MoveWhereY
    keys()
    GBullet.update()

    screen.fill (pygame.Color(GameColors['black']))
    collide = pygame.sprite.spritecollide(playerone, GAsteroidz, False)
    if len(collide) !=0:
            if collide[0].direction != 'zap':
                playerone.Lives -=1
            scorePlayer = 0
            collide[0].moveElement (0,0, 'zap')
            lives.text = 'Lives: ' + str(playerone.Lives)

    for bullet in GBullet:
        bul = pygame.sprite.spritecollide(bullet, GAsteroidz, False)
        if len(bul) !=0: #hit# !
            GBullet.remove (bullet)
            bul[0].moveElement (0,0, 'zap')
            playerScore +=10
            score.text = 'Score: ' + str(playerScore)
            smalize = []
            for sprt in rotatedanim:
                    smalize.append(EasyConfigSurface().resize(sprt,10,10))
            if bul [0].iterate == True:
                for number in range (0,3,1):
                    SS = Monster (rotate = smalize, zap = blastlist)
                    SS.setSpeed(random.randint(0,5),random.randint(0,5)) #SpeedAsteriod If moved
                    SS.warp(bul[0].rect.x, bul[0].rect.y) #StartPos Asteroid
                    SS.changedirectionvector(random.randint(-1,1),random.randint(-1,1)) #Move Asteroid
                    SS.iterate =False
                    GAsteroidz.add (SS)

    if playerone.Lives <= 0:
        lives.text = 'GAME OVER!'
        GGameOver.draw (screen)
    elif len (GAsteroidz) == 0:
        screen.blit (WinText.render(), (75,220))
    else:
        for bullet in GBullet:
            if bullet.rect.x < -10 or bullet.rect.x > 650:
                GBullet.remove(bullet)
            elif bullet.rect.y < -10 or bullet.rect.y > 490:
                GBullet.remove (bullet)
        for asteroid in GAsteroidz:
            if asteroid.direction == 'zap':
                #There live
                if len (asteroid.clips[asteroid.direction])-1 == asteroid.clipCounter: GAsteroidz.remove (asteroid)
        Gstars.draw (screen)
        Gplanet.draw (screen)
        GAsteroidz.draw (screen)
        GBullet.draw (screen)
        GPlayerone.draw(screen)

    screen.blit (lives.render(), (10,10))
    screen.blit (score.render(), (10,35))

    FPS.Clock().tick (40)
    pygame.display.flip()
pygame.quit()


"""
Funções para determinar se é triangulo
"""

def forma_triangulo(a, b, c):
    print()
    if a < b + c and b < a + c and c < b + a:
        if a == b == c:
            tipo = 'Equilátero'
        elif a == b or a == c or b == c:
            tipo = 'Isósceles'
        elif a != b != c:
            tipo = 'Escaleno'
        return f'Forma um triângulo do tipo \033[1;7;31m{tipo}\033[m'
    else:
        return f'\033[1;31mNão forma um triângulo\033[m'

lado1 = float(input('Digite lado 1: '))
lado2 = float(input('Digite lado 2: '))
lado3 = float(input('Digite lado 3: '))
while lado1 <= 0 or lado2 <= 0 or lado3 <= 0:
    if lado1 <= 0:
        lado1 = float(input('Digite um valor maior do que "0" para o lado 1: '))
    elif lado2 <= 0:
        lado2 = float(input('Digite um valor maior do que "0" para o lado 2: '))
    elif lado3 <= 0:
        lado3 = float(input('Digite um valor maior do que "0" para o lado 3: '))
print(f'Pelos valores digitados sabemos que:'
      f'\n{forma_triangulo(lado1, lado2, lado3)}')


from kafka import KafkaProducer
from datetime import datetime
import time
from json import dumps
import requests

TOPIC_NAME_CONS = "topic-weather"
BOOTSTRAP_SERVERS_CONS = 'localhost:9092'

def get_data(url):

    response_data = requests.get(url=url)
    data = response_data.json()
    weather = {}
    event_datetime = datetime.now()
    weather["event_datetime"] 		= event_datetime.strftime("%Y-%m-%d %H:%M")
    weather["humidity"] 			= data["main"]["humidity"]
    weather["pressure"] 			= data["main"]["pressure"]
    weather["temperature"] 			= data["main"]["temp"]
    weather["temperature_max"] 		= data["main"]["temp_max"]
    weather["temperature_min"] 		= data["main"]["temp_min"]
    weather["temperature_feels"] 	= data["main"]["feels_like"]
    weather["city_name"] 			= data["name"]
    weather["wind_deg"] 			= data["wind"]["deg"]
    weather["wind_speed"] 			= data["wind"]["speed"]

    return weather

if __name__ == "__main__":
    print("Open Weather API Data | Kafka Producer Application Started ... ")

    kafka_producer_obj = KafkaProducer(bootstrap_servers=BOOTSTRAP_SERVERS_CONS,
                             value_serializer=lambda x: dumps(x).encode('utf-8'))

    city_names = ["Hamburg","Berlin","Frankfurt am Main","Stuttgart","Munich","Düsseldorf","Köln","Dresden","Leipzig"]

    i = 0
    while True:
        try:

            for city in city_names:
                api_key = "API KEY"
                url = "https://api.openweathermap.org/data/2.5/weather?q={0}&appid={1}".format(city,api_key)
                weather_data = get_data(url)
                i = i + 1
                print("<<<<<<<<<<  Live Straeming Data >>>>>>>>>>")
                print("Printing message id: " + str(i))
                print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
                print("Sending message to Kafka topic: " + TOPIC_NAME_CONS)
                print("Message to be sent: ", weather_data)
                kafka_producer_obj.send(TOPIC_NAME_CONS, weather_data)

        except Exception as ex:
            print("Event Message Construction Failed. ")
            print(ex)

        time.sleep(10)


# -*- coding: utf-8 -*-
from __future__ import print_function, division

#------------------------------------------------------------------------------
# SENTIMENT MODEL - BUILD MODEL
#------------------------------------------------------------------------------

# Functions:
# [1] ...

# Version: 2.0
# Last edited: 21 Dec 2016
# Edited by: Minh PHAN

#------------------------------------------------------------------------------
# Global variables and settings
#------------------------------------------------------------------------------

# Seting working directory
import os
os.chdir('D:\\SentimentTM\\23_sentiment_analysis\\model')

#------------------------------------------------------------------------------
# Initiating
#------------------------------------------------------------------------------

import pandas as pd
import numpy as np

import time

from sklearn import preprocessing

from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.ensemble import RandomForestClassifier
from sklearn.svm import LinearSVC
from sklearn.svm import SVC
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import BaggingClassifier
from sklearn.dummy import DummyClassifier

from scipy import sparse
import xgboost as xgb
import pickle

#------------------------------------------------------------------------------
# Self-defined functions
#------------------------------------------------------------------------------

# Function to calculate the probability of each target class
# Can replace this function with predict_proba()
def classification_ProbClass(clf, data_test_new, labelEncoder, n_top):

    # Estimate prob of belonging to each class
    target_predProb = clf.predict_proba(data_test_new) # Matrix containing prob for each row of data_test
    idx_sort = np.argsort(-target_predProb,axis=1) # Indexes of array if sorted largest prob first
    i_top = idx_sort[:,idx_sort.shape[1]-n_top:idx_sort.shape[1]] # Index n_top predicted clases, order decreasing prob

    # Top n probabilities, decreasing order
    target_predProb_top = np.vstack([target_predProb[i,i_top[i,:]] for i in range(target_predProb.shape[0])]) # prob of top clases, order decreasing prob

    # Top n classes, convert class code to real target value
    realTop_target = labelEncoder.inverse_transform(i_top)

    # Create string output that combines pred class and prob, for easy visualization
    assign_class_prob = ([zip(realTop_target[i,:].astype(np.str), target_predProb_top[i,:].astype(np.str))
                          for i in range(target_predProb.shape[0])])

    pred_class_prob = [] # np.zeros((len(assign_class_prob),), dtype=object)
    for i in  range(len(assign_class_prob)):
        row = assign_class_prob[i]
        str_row = ''
        for j in range(len(row)):
            str_row = str_row + '='.join(row[j]) + ', '

        str_row = str_row[0:-2] # Remove last space and coma

        #pred_class_prob[i] = str_row
        pred_class_prob.append(str_row)

    return target_predProb_top, realTop_target, pred_class_prob

# Function to select best features
def feature_selection(data_train, target_train, data_test, scoring_type):

    # Fewature selection using linear svm
    tuned_parameters = [{'C': [0.05,0.1, 0.5, 1 ,5,10,50,100,500], 'penalty':["l1","l2"], 'dual': [False],'class_weight': ['auto'] }]
    clf_featureSelect = GridSearchCV(LinearSVC(), tuned_parameters, cv=10, scoring=scoring_type)
    clf_featureSelect.fit(data_train,target_train)
    data_train_new = clf_featureSelect.transform(data_train)
    data_test_new = clf_featureSelect.transform(data_test)

    return data_train_new, data_test_new, clf_featureSelect

# Function to run the classifier and save the models
def classifyTwitter(dataIn_training, dataIn_test):

    # Drop NA data
    dataIn_training = dataIn_training.dropna()
    dataIn_test = dataIn_test.dropna()
    dataIn_training = dataIn_training.reset_index(drop=True)
    dataIn_test = dataIn_test.reset_index(drop=True)

    # Enocde target variable
    # To decode: labelEncoder.inverse_transform([2, 2, 1])='neutral,..
    target_training_org = dataIn_training.polarity.values
    target_test_org = dataIn_test.polarity.values
    labelEncoder = preprocessing.LabelEncoder()
    labelEncoder.fit(target_training_org)
    target_train = labelEncoder.transform(target_training_org)
    target_test = labelEncoder.transform(target_test_org)

    # Drop target variable
    dataIn_training.drop('polarity', axis=1, inplace=True)
    dataIn_test.drop('polarity', axis=1, inplace=True)

    # Sparse data
    data_train_sparse = sparse.csr_matrix(dataIn_training.as_matrix())
    data_test_sparse = sparse.csr_matrix(dataIn_test.as_matrix())

    # Scale data
    # Need to preprocess data: norlaize--> probelm: if sparse, not possible
    # to standarize (if d-mean/std--> 0 besomes sometihng--> dense)
    # either no standarization, or standarization [0,1] o just by std
    use_scaler = False
    if use_scaler == True:
        scaler = preprocessing.StandardScaler(with_mean=False).fit(data_train_sparse)
        data_train = scaler.transform(data_train_sparse)
        data_test = scaler.transform(data_test_sparse)
    else:
        data_train = data_train_sparse
        data_test = data_test_sparse
        scaler = None

    # Fewature selection
    # Need to save the original data_trin/test for the decoding of one-hot
    use_featureSelect = False
    scoring_type = 'f1_weighted'
    if use_featureSelect == True:
        start = time.time()
        data_train_new, data_test_new, clf_featureSelect = feature_selection(data_train,target_train,data_test,scoring_type)
        end = time.time()
        print('Feature Select time =', str(end-start))
        print('new shape= ', data_test_new.shape)
    else:
       data_train_new, data_test_new=data_train, data_test
       clf_featureSelect = None

    # Convert training data back to arrary
    # Sparse matrix has error when running cross validation
    data_train_new = data_train_new.toarray()
    data_test_new = data_test_new.toarray()

    # Train xgboost model with GridSearchCV
#    start = time.time()
#    xgb_model = xgb.XGBClassifier({'nthread':4, 'objective':'multi:softprob',
#                                   'num_class':3, 'random_state':0})
#    tuned_parameters = {'max_depth':[2,4,6,8],
#                        'n_estimators':[10,50,100,200,400,600]}
#    clf_xgb = GridSearchCV(xgb_model, tuned_parameters, cv=10, scoring=scoring_type,
#                           verbose=10)
#
#    clf_xgb.fit(data_train_new, target_train)
#    target_pred_xgb = clf_xgb.predict(data_test_new)
#    end = time.time()
#
#    print('xgboost classifier:')
#    print(clf_xgb.best_score_)
#    print(clf_xgb.best_params_)
#    print('clf_xgb time = ', str(end-start))
#    print(classification_report(target_test, target_pred_xgb))
#    print(confusion_matrix(target_test, target_pred_xgb))
#    acc_xgb = clf_xgb.score(data_test_new, target_test)
#    print(acc_xgb)

    # Re-train xgboost model with best params to evaluate
    xgb_best_params = xgb.XGBClassifier(nthread=4, objective='multi:softprob',
                                        seed=0, n_estimators=600, max_depth=2)
    xgb_best_params.fit(data_train_new, target_train)
    target_pred_xgb = xgb_best_params.predict(data_test_new)

    print('xgboost classifier:')
    print(classification_report(target_test, target_pred_xgb))
    print(confusion_matrix(target_test, target_pred_xgb))
    acc_xgb = xgb_best_params.score(data_test_new, target_test)
    print(acc_xgb)

    # Save xgboost model with best params
    xgb_best_params = xgb.XGBClassifier(nthread=4, objective='multi:softprob',
                                        seed=0, n_estimators=600, max_depth=2)
    train_all = np.concatenate((data_train_new, data_test_new), axis=0)
    target_all = np.concatenate((target_train, target_test), axis=0)
    xgb_best_params.fit(train_all, target_all)

    file_out = '.\\output\\sentiment_classifier_model.pkl'
    save_data = [labelEncoder, xgb_best_params]
    pickle.dump(save_data, open(file_out, 'wb'))

    # Dummy calssifier (baseline to compare)
    clf_dummy = DummyClassifier(strategy='stratified', random_state=0)
    clf_dummy.fit(data_train_new, target_train)
    target_pred_dummy = clf_dummy.predict(data_test_new)

    print('Dummy classifier:')
    print(classification_report(target_test, target_pred_dummy))
    print(confusion_matrix(target_test, target_pred_dummy))
    acc_dummy = clf_dummy.score(data_test_new, target_test)
    print(acc_dummy)

    # Create output results
    dataIn_test['polarity'] = labelEncoder.inverse_transform(target_test)
    dataOut = dataIn_test

    col_output = 'EstimatedPolarity_XGB'
    dataOut[col_output] = labelEncoder.inverse_transform(target_pred_xgb)

    n_top = 3 # chose top 3 classes (in this case only 3 in total but other cases can  bemore)
    target_predProb_top, realTop_target, pred_class_prob = classification_ProbClass(xgb_best_params, data_test_new, labelEncoder, n_top)

    col_output = 'EstimatedPolarity_XGB_prob'
    dataOut[col_output] = pred_class_prob

    return dataOut

#------------------------------------------------------------------------------
# MAIN
#------------------------------------------------------------------------------

if __name__ == '__main__':

    # Read data in and train sentiment classifier model
    fileNameIn_train = '.\\output\\tweeti-b.distFULL_featureEncoded.tsv'
    fileNameIn_test = '.\\output\\tweeti-b.dev.distFULL_featureEncoded.tsv'

    dataIn_training = pd.read_csv(fileNameIn_train, sep='\t', encoding='utf-8')
    dataIn_test = pd.read_csv(fileNameIn_test, sep='\t', encoding='utf-8')

    dataOut_test = classifyTwitter(dataIn_training, dataIn_test)

    # Merge and export results
    fileNameIn_test_withMsg = '.\\input\\data_challenge2013\\tweeti-b.dev.distFULL.tsv'
    fileNameOut_test_withMsg = '.\\output\\tweeti-b.dev.distFULL_classificationOut_withMSg.csv'

    dataIn_test_withMsg = pd.read_csv(fileNameIn_test_withMsg, sep='\t')
    colNames = list(dataIn_test_withMsg.columns)
    dataIn_test_withMsg['EstimatedPolarity_XGB_prob'] = dataOut_test['EstimatedPolarity_XGB_prob']
    dataIn_test_withMsg = dataIn_test_withMsg[colNames[0:3] + ['EstimatedPolarity_XGB_prob'] + [colNames[3]]]

    dataIn_test_withMsg.to_csv(fileNameOut_test_withMsg, index=False)

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


import threading

from flask import Flask, render_template
import ssh

from gevent import pywsgi

app = Flask(__name__)

host_info = {}
cfg_dict = {}

@app.before_first_request
def start_ssh():
    global cfg_dict, host_info
    ssh_pool, cfg_dict = ssh.init()
    for (ssh_id, (host, ssh_cfg)) in enumerate(ssh_pool.items()):
        t = threading.Thread(target=ssh.query_host, args=(ssh_id, host, ssh_cfg, host_info, cfg_dict['timeout']))
        t.start()

@app.route('/')
def hello_world():
    return "hello world"

@app.route('/gpu', methods=['GET', 'POST'])
def gpu():
    global host_info, cfg_dict
    host_i = dict(sorted(host_info.items(), key=lambda item: item[0]))
    if cfg_dict['warmup'] > 0:
        refresh = 5
        cfg_dict['warmup'] -= 1
    else:
        refresh = cfg_dict['refresh']
    return render_template('gpu.html', title='Who Moved My GPU?', host_info=host_i, refresh_time=refresh)

@app.route('/fix', methods=['GET', 'POST'])
def fix():
    return render_template('fix.html')

if __name__ == '__main__':
    server = pywsgi.WSGIServer(('0.0.0.0', 1301), app)
    server.serve_forever()


#taxi fare:

'''
taxi fare= 4.00
for 140 meters=0.25
base fare=0.2
'''
base_fare=2.0
taxi_fare=4.00
for_140_meters=0.25

def distance(km):
    meters=distance*1000
    total=base_fare + (km * taxi_fare) + (meters / 140 * for_140_meters)
    return total

distance_km=float(input('enter the km:'))
fare=distance(distance_km)
print(fare)


import os.path as op

import numpy as np
import matplotlib.pyplot as plt
import mne

import config_drago as cfg

info = np.load(op.join(cfg.path_data, 'info_allch.npy')).item()
picks = mne.pick_types(info, meg='mag')

fname = op.join(cfg.path_outputs, 'covs_allch_oas.h5')
data = mne.externals.h5io.read_hdf5(fname)  # (sub, fb, ch, ch)

subjects = [d['subject'] for d in data if 'subject' in d]
covs = [d['covs'][:, picks][:, :, picks] for d in data if 'subject' in d]
covs = np.array(covs)  # (sub,fb,chan,chan)

ranks = []
for sub in range(len(subjects)):
    cov = mne.Covariance(covs[sub][4], np.array(info['ch_names'])[picks],
                         [], [], 1)
    ranks.append(mne.compute_rank(cov, info=info)['mag'])
plt.figure()
plt.hist(ranks)


import requests
import json
import datetime as dt

today = dt.datetime.now()
yesterday = today - dt.timedelta(days=1)
tomorrow = today + dt.timedelta(days=1)

# B100005528
# J100005670

def getLunch(day, month):
    school = 'J100005670'
    url = f'https://schoolmenukr.ml/api/high/{school}?date={day}&allergy=hidden&month={month}'
    response = requests.get(url)
    school_menu = json.loads(response.text)
    lunch = school_menu['menu'][0]['lunch']
    for menu in lunch:
        print(menu)

print('\n오늘급식:\n')
getLunch(today.day, today.month)
print('\n내일급식:\n')
getLunch(tomorrow.day, tomorrow.month)
print('\n어제급식:\n')
getLunch(yesterday.day, yesterday.month)


# Singly-linked lists are already defined with this interface:
# class ListNode(object):
#   def __init__(self, x):
#     self.value = x
#     self.next = None
#
def findMiddleElement(l):
    first = l
    second = l

    if l is not None:
        while first is not None and first.next is not None:
            first = first.next.next
            second = second.next

    return second.value

# Singly-linked lists are already defined with this interface:
# class ListNode(object):
#   def __init__(self, x):
#     self.value = x
#     self.next = None
#
def findMiddleElement(l):
    temp = l
    count = 0
    while l:
        if count % 2 != 0:
            temp = temp.next
        l = l.next
        count += 1

    return temp.value

Codesignal and Geekforgeeks Combined/linkedListMiddle.py


#! /usr/bin/python
import sys
import warnings
from selenium import webdriver
from appium import webdriver as app_driver
import json
from utils.my_logger import log
from config.get_config_data import get_sys_yml_data
from config.PATH import os, DRIVERS

def __get_driver_path(driver_type):
    """
    获取 driver 文件路径
    :param driver_type: 传入 driver 类型, 系统自动 配合 系统配置文件中的文件名, 匹配项目中是否存储有 driver 文件
    :return 有的话，返回 绝对路径
            无的话，返回 None
    """

    driver_type = driver_type.lower()
    if driver_type not in ['chrome', 'firefox', 'ie', 'safari']:
        raise Exception(f'不支持的 driver 类型: {driver_type}')

    current_sys_type = sys.platform
    sys_yml_data = get_sys_yml_data()

    if current_sys_type == 'win32':
        current_sys_type = 'win'
    else:
        current_sys_type = current_sys_type

    driver_name = sys_yml_data['driver_path'][current_sys_type][driver_type]
    if driver_name:
        if os.path.exists(driver_name):  # 如果是 绝对路径的
            driver_path = driver_name
        else:  # 如果是 名字 + driver存放于项目中
            driver_path = os.path.join(DRIVERS, current_sys_type, driver_name)

        if os.path.exists(driver_path):
            return driver_path
        else:
            return None
    else:
        return None

def get_h5_driver(driver_type='chrome'):
    driver_type = driver_type.lower()
    driver_path = __get_driver_path(driver_type)
    if driver_path is None:
        driver_path = 'default_path'

    mobile_emulation = {"deviceName": "iPhone 5/SE"}
    chrome_options = webdriver.ChromeOptions()
    chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
    chrome_options.add_experimental_option('w3c', False)
    warnings.simplefilter("ignore", ResourceWarning)

    log.info(f'driver路径: {driver_path}')
    log.info('打开H5浏览器。')
    if driver_path:
        driver = webdriver.Chrome(options=chrome_options, executable_path=driver_path)
    else:
        driver = webdriver.Chrome(options=chrome_options)
    driver = __check_webdriver_to_undefined(driver)
    return driver

def get_web_driver(driver_type='chrome'):
    driver_type = driver_type.lower()
    driver_path = __get_driver_path(driver_type)
    if driver_path is None:
        driver_path = 'default_path'

    log.info(f'driver路径: {driver_path}')
    log.info('打开web浏览器。')
    if driver_path:
        driver = webdriver.Chrome(executable_path=driver_path)
    else:
        driver = webdriver.Chrome()
    driver = __check_webdriver_to_undefined(driver)
    driver.maximize_window()
    return driver

def get_app_driver(appium_port, desired_caps):
    """
    打开APP
    :param appium_port: appium端口号
    :param desired_caps: 移动设备的关键信息
    """
    log.info('=' * 40 + '  设备初始化信息  ' + '=' * 40)
    log.info('appium_port：{}'.format(appium_port))
    log.info('desired_capabilities：{}'.format(json.dumps(desired_caps, indent=2, ensure_ascii=False)))
    log.info('=' * 40 + '  设备初始化信息  ' + '=' * 40)
    log.info('打开APP。')
    driver = app_driver.Remote(command_executor='http://127.0.0.1:{}/wd/hub'.format(appium_port),
                               desired_capabilities=desired_caps)
    return driver

def __check_webdriver_to_undefined(driver):
    """
    去掉 selenium 反爬检测
    :param driver: driver
    :return: driver
    """
    driver.execute_cdp_cmd('Page.addScriptToEvaluateOnNewDocument', {
        'source': 'Object.defineProperty(navigator, "webdriver", {get: () => undefined})'
    })
    return driver


# Programming exercise:
# Same word twice

# Please write a program which asks the user for words.
# If the user types in a word for the second time, the program should print out the number of different words typed in, and exit.

# Write your solution here
unique=0
list=[]
while True:
    word=input("word: ")
    if word in list:
        break
    if word not in list:
        unique+=1
    list.append(word)

print(f"You typed in {unique} different words")


'''
06 - Unix timestamps

Datetimes are sometimes stored as Unix timestamps: the  number of  seconds  since
January 1, 1970. This is especially common with computer infrastructure, like the
log files that websites keep when they get visitors.

Instructions

- Complete the for loop to loop over timestamps.
- Complete the code to turn each timestamp ts into a datetime.
'''
# Import datetime
from datetime import datetime

# Starting timestamps
timestamps = [1514665153, 1514664543]

# Datetime objects
dts = []

# Loop
for ts in timestamps:
  dts.append(datetime.fromtimestamp(ts))

# Print results
print(dts)

'''
<script.py> output:
    [datetime.datetime(2017, 12, 30, 20, 19, 13), datetime.datetime(2017, 12, 30, 20, 9, 3)]

The largest number that some older computers can hold in one variable is 2147483648, which as
a Unix timestamp is in January 2038. On that day, many computers which haven't been upgraded
will fail.
'''

18_Working with Dates and Times in Python/02_Combining Dates and Times/06_Unix timestamps.py


import time, re
from itertools import groupby
from helpers import *

t = time.time()

input = "1113122113"

# Part 1
def splitSequence(input):
    return [m.group(0) for m in re.finditer(r"(\d)\1*", input)]

def lookAndSay(seq):
    seq = splitSequence(seq)
    say = "".join(map(lambda c: str(len(c)) + c[0], seq))
    return say

for i in range(45):
    input = lookAndSay(input)

dropstar(19, len(input), t)

# Part 2
def lookAndSay2(number):
    return "".join(str(len(list(g))) + k for k, g in groupby(number))

# 1113122113
# 132113
# 3113
# 1113
# 13
# 3

input = "3"
for i in range(55):
    input = lookAndSay2(input)

dropstar(20, len(input), t)


from models import AppConfig as ac
from controllers import Webdriver as wd
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.common.keys import Keys
from models import UserConfig as uc
from controllers import Variaveis as v

class Tema:
  @staticmethod
  def preencher(data):
    try:
      temaSplitted = data.split('//')
      campoTema = wd.Webdriver.wait["regular"].until(EC.element_to_be_clickable(
        (By.XPATH, ac.AppConfig.xpaths["publicacao"]["temaSelect"])),
        message="Não foi possível localizar ou clicar no campo 'Tema'")
      campoTema.click()
      time.sleep(0.3)

      campoBuscarTema = wd.Webdriver.wait["regular"].until(EC.element_to_be_clickable(
        (By.XPATH, ac.AppConfig.xpaths["publicacao"]["buscarTemaInput"])),
        message="Não foi possível localizar ou clicar no campo 'Buscar tema'")
      wd.Webdriver.nav.execute_script("arguments[0].setAttribute('value',arguments[1])",campoBuscarTema, "")
      time.sleep(0.3)
      campoBuscarTema.send_keys(temaSplitted[0])
      time.sleep(1.5)

      if (len(temaSplitted) == 2):
        i = 1
        while (i < int(temaSplitted[1])):
          campoBuscarTema.send_keys(Keys.ARROW_DOWN)
          time.sleep(0.3)
          i += 1

      campoBuscarTema.send_keys(Keys.ENTER)
      wd.Webdriver.waitLoadingModal()

      campoTemaPreenchido = wd.Webdriver.wait["regular"].until(EC.element_to_be_clickable(
        (By.XPATH, ac.AppConfig.xpaths["publicacao"]["temaSelect"])),
        message="Não foi possível localizar ou clicar no campo 'Tema' preenchido")

      return {"log": f"Tema selecionado: {campoTemaPreenchido.text}", "type": "n"}

    except Exception as e:
      return wd.Webdriver.handleExceptions(e, "tema")

  @staticmethod
  def buscar(filetext):
    try:
      termos = v.Variaveis.atribuirValorVariaveis(uc.UserConfig.obterAutoTemasAssuntos())
      for termo, obj in termos.items():
        if termo.lower() in filetext.lower():
          return {"log": f"Tema identificado: {obj['tema']}", "type": "n", "return": obj["tema"]}
      raise Exception("não foi localizado um termo correspondente a um tema no conteúdo do documento.")
    except Exception as e:
      return {"log": f"Falha ao selecionar tema: {e}", "type": "e", "e": e, "return": False}


import sys
#sys.stdin = open("input.txt", "rt")

##### 큐 자료구조 활용 #####
## deque 라는 자료구조를 통해 적용
## deque : 앞뒤 둘다 뺐다 넣었다 할 수 있음
## appendleft, popleft / append, pop
from collections import deque

n, k = map(int, input().split())
dq = list(range(1, n+1))
dq = deque(dq)

while dq:
    for _ in range(k-1):
        cur = dq.popleft()
        dq.append(cur)
    dq.popleft()
    if len(dq) == 1:
        print(dq[0])
        dq.popleft() # break 할 수도 있지만 비워버려서 while문 조건 만족시켜서 끝냄

'''
# 코드 설명 안보고 개념만 보고 푼 풀이
n, k = map(int, input().split())

pr = [x for x in range(1, n+1)]

#print(pr)
lst = []

while len(pr) > 1:

    for _ in range(k-1):
        pr.append(pr.pop(0))
    pr.pop(0)
print(pr[0])
'''


"""
使用双向链表实现一个lru
"""

class DoubleLinkedList:
    def __init__(self, key=None, val=None):
        self.key = key
        self.val = val
        self.prev = None
        self.next = None

class LRUCache:

    def __init__(self, capacity: int):
        self.capacity = capacity

        # 双向链表维护 最近 最少原则
        self.head = DoubleLinkedList()
        self.tail = DoubleLinkedList()
        self.head.next = self.tail
        self.tail.prev = self.head

        # key: node 放key和node的映射关系
        self.cache = {}

    def get(self, key: int) -> int:
        if key in self.cache:
            node = self.cache[key]
            # 因为被使用了，所以移动到双向链表的头部
            self.move_to_head(node)
            return node.val
        return -1

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            node = self.cache[key]
            node.val = value
            self.move_to_head(node)
            return

        # 添加数据，但是满了
        if len(self.cache) >= self.capacity:
            # 移除尾部的
            tail_node = self.tail.prev
            self.remove_node(tail_node)
            del self.cache[tail_node.key]
        # 添加数据到头节点
        new_node = DoubleLinkedList(key, value)
        self.cache[key] = new_node
        self.add_to_head(new_node)

    def move_to_head(self, node):
        self.remove_node(node)
        self.add_to_head(node)

    def add_to_head(self, node):
        node.prev = self.head
        node.next = self.head.next
        self.head.next.prev = node
        self.head.next = node

    def remove_node(self, node):
        prev_node = node.prev
        next_node = node.next
        prev_node.next = next_node
        next_node.prev = prev_node

        pass

if __name__ == '__main__':
    # Initialize an LRU cache with a capacity of 2
    lru_cache = LRUCache(2)

    # Insert key-value pairs
    lru_cache.put(1, 1)
    lru_cache.put(2, 2)

    # Retrieve a value
    print(lru_cache.get(1))  # Output: 1

    # Insert a new key-value pair, causing the eviction of the least recently used item (key 2)
    lru_cache.put(3, 3)

    # The value associated with key 2 has been evicted, so get(2) returns -1
    print(lru_cache.get(2))  # Output: -1


from PIL import Image
from pathlib import Path
from torchvision import transforms
from torchvision.datasets import MNIST
from tqdm import tqdm
import cv2
import numpy as np
import torch

class MNISTF1(MNIST):
    SIZE = 64
    SMALL_START = 18
    SMALL_END = 46

    def __init__(self,
                 root,
                 train=True,
                 transform=None,
                 target_transform=None,
                 download=False):
        super(MNISTF1, self).__init__(root, train, transform, target_transform,
                                      download)
        self.root = root
        self.transform = transform
        self.train = train  # training set or test set

        if download:
            self.download()

        if not self._check_exists():
            raise RuntimeError('Dataset not found.' +
                               ' You can use download=True to download it')

        if self.train:
            data_file = self.training_file
        else:
            data_file = self.test_file
        self.data, self.targets = torch.load(
            Path(self.root, self.processed_folder, data_file))

        self.num_positives = 0
        self._build()

    def _build(self):
        data_, targets_ = [], []

        print("Building dataset...")
        for [img, target] in tqdm(zip(self.data, self.targets)):
            img = img.numpy()

            # We create "small" and
            small = np.zeros([self.SIZE, self.SIZE])
            small[self.SMALL_START:self.SMALL_END, self.SMALL_START:self.
                  SMALL_END] += img
            data_.append(small)
            targets_.append((target, 0))

            # "big" versions of each image in the MNIST dataset
            big = cv2.resize(img,
                             dsize=(self.SIZE, self.SIZE),
                             interpolation=cv2.INTER_CUBIC)

            data_.append(big)
            targets_.append((target, 1))

            # We count the number of positive examples for use in our algorithm
            self.num_positives += 1

        self.data = data_
        self.targets = targets_

    def __getitem__(self, index):
        img, target = self.data[index], self.targets[index]

        img = Image.fromarray(img)
        if self.transform is not None:
            img = self.transform(img)
        else:
            img = transforms.ToTensor()(img)

        # (class, big_or_small, index)
        target = torch.tensor([int(target[0]), int(target[1]), index])

        return img, target


from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from puppyShelterDBsetup import Base, Shelter, Puppy, Owner
from random import randint
import datetime
import random

engine = create_engine('sqlite:///puppyshelter.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind=engine)
session = DBSession()

#Create shelter instances
shelter1 = Shelter(
	name = "Oakland Animal Services",
	address = "1101 29th Ave",
	city = "Oakland",
	state = "California",
	zipCode = "94601",
	website = "oaklandanimalservices.org",
	maximum_capacity = 30)

shelter2 = Shelter(
	name = "San Francisco SPCA Mission Adoption Center",
	address="250 Florida St",
	city="San Francisco",
	state="California",
	zipCode = "94103",
	website = "sfspca.org",
	maximum_capacity = 35)

shelter3 = Shelter(
	name = "Wonder Dog Rescue",
	address= "2926 16th Street",
	city = "San Francisco",
	state = "California" ,
	zipCode = "94103",
	website = "http://wonderdogrescue.org",
	maximum_capacity = 50)

shelter4 = Shelter(
	name = "Humane Society of Alameda",
	address = "PO Box 1571",
	city = "Alameda" ,
	state = "California",
	zipCode = "94501",
	website = "hsalameda.org",
	maximum_capacity = 35)

shelter5 = Shelter(
	name = "Palo Alto Humane Society" ,
	address = "1149 Chestnut St.",
	city = "Menlo Park",
	state = "California" ,
	zipCode = "94025",
	website = "paloaltohumane.org",
	maximum_capacity = 40)

#Add all instances of shelter to the ORM
session.add_all([shelter1, shelter2, shelter3, shelter4, shelter5])

owner1 = Owner(
	firstName = "Mr. Bob" ,
	lastName = "Dobolina",
	address = "123 North View",
	city = "Durango",
	state = "Colorado" ,
	zipCode = "80024",
	cellnum = "1111111111",
	email = "bob@dobolina.com",
	needs = "I'm interested in getting a lovable puppy.")

owner2 = Owner(
	firstName = "Smaug" ,
	lastName = "TheTerrible",
	address = "1 Lonely Mountain",
	city = "Boulder",
	state = "Colorado" ,
	zipCode = "80024",
	cellnum = "2222222222",
	email = "smoug@theterrible.com",
	needs = "I want a puppy to keep me company in my mountain.")

owner3 = Owner(
	firstName = "Kylo" ,
	lastName = "Ren",
	address = "666 Starkiller Base",
	city = "Colorado Springs",
	state = "Colorado" ,
	zipCode = "80024",
	cellnum = "3333333333",
	email = "renk@firstorder.com",
	needs = "I need a puppy to finish what you started.")

owner4 = Owner(
	firstName = "Boba" ,
	lastName = "Fett",
	address = "9 Jabba's Pallace",
	city = "Mos Isley",
	state = "Colorado" ,
	zipCode = "80024",
	cellnum = "4444444444",
	email = "boba@fett.com",
	needs = "I need a hypoallergenic puppy to keep me company on long journeys.")

session.add_all([owner1, owner2, owner3, owner4])

#Add Puppies
male_names = ["Bailey", "Max", "Charlie", "Buddy", "Rocky",
	"Jake", "Jack", "Toby", "Cody", "Buster",
	"Duke", "Cooper", "Riley", "Harley", "Bear",
	"Tucker", "Murphy", "Lucky", "Oliver", "Sam",
	"Oscar", "Teddy", "Winston", "Sammy", "Rusty",
	"Shadow", "Gizmo", "Bentley", "Zeus", "Jackson",
	"Baxter", "Bandit", "Gus", "Samson", "Milo",
	"Rudy", "Louie", "Hunter", "Casey", "Rocco",
	"Sparky", "Joey", "Bruno", "Beau", "Dakota",
	"Maximus", "Romeo", "Boomer", "Luke", "Henry"]
female_names = ['Bella', 'Lucy', 'Molly', 'Daisy', 'Maggie',
	'Sophie', 'Sadie', 'Chloe', 'Bailey', 'Lola',
	'Zoe', 'Abby', 'Ginger', 'Roxy', 'Gracie',
	'Coco', 'Sasha', 'Lily', 'Angel', 'Princess',
	'Emma', 'Annie', 'Rosie', 'Ruby', 'Lady',
	'Missy', 'Lilly', 'Mia', 'Katie', 'Zoey',
	'Madison', 'Stella', 'Penny', 'Belle', 'Casey',
	'Samantha', 'Holly', 'Lexi', 'Lulu', 'Brandy',
	'Jasmine', 'Shelby', 'Sandy', 'Roxie', 'Pepper',
	'Heidi', 'Luna', 'Dixie', 'Honey', 'Dakota']
puppy_images = ["http://pixabay.com/get/da0c8c7e4aa09ba3a353/1433170694/dog-785193_1280.jpg?direct",
	"http://pixabay.com/get/6540c0052781e8d21783/1433170742/dog-280332_1280.jpg?direct",
	"http://pixabay.com/get/8f62ce526ed56cd16e57/1433170768/pug-690566_1280.jpg?direct",
	"http://pixabay.com/get/be6ebb661e44f929e04e/1433170798/pet-423398_1280.jpg?direct",
	"http://pixabay.com/static/uploads/photo/2010/12/13/10/20/beagle-puppy-2681_640.jpg",
	"http://pixabay.com/get/4b1799cb4e3f03684b69/1433170894/dog-589002_1280.jpg?direct",
	"http://pixabay.com/get/3157a0395f9959b7a000/1433170921/puppy-384647_1280.jpg?direct",
	"http://pixabay.com/get/2a11ff73f38324166ac6/1433170950/puppy-742620_1280.jpg?direct",
	"http://pixabay.com/get/7dcd78e779f8110ca876/1433170979/dog-710013_1280.jpg?direct",
	"http://pixabay.com/get/31d494632fa1c64a7225/1433171005/dog-668940_1280.jpg?direct"]

#This method will make a random age for each puppy between 0-18 months(approx.) old from the day the algorithm was run.
def CreateRandomAge():
	today = datetime.date.today()
	days_old = randint(0,540)
	birthday = today - datetime.timedelta(days = days_old)
	return birthday

#This method will create a random weight between 1.0-40.0 pounds (or whatever unit of measure you prefer)
def CreateRandomWeight():
	return random.randint(1, 40)

#This method will create a random number between 1-5 for shelter ID.
def CreateRandomShelterAssignment():
	return random.randint(1, 5)

for i,x in enumerate(male_names):
	new_puppy = Puppy(name = x,
		gender = "male", \
		dateOfbirth = CreateRandomAge(), \
		picture=random.choice(puppy_images), \
		weight= CreateRandomWeight(), \
		shelter_id = CreateRandomShelterAssignment())
	session.add(new_puppy)
	session.commit()

for i,x in enumerate(female_names):
	new_puppy = Puppy(name = x, \
		gender = "female", \
		dateOfbirth = CreateRandomAge(), \
		picture=random.choice(puppy_images), \
		weight= CreateRandomWeight(), \
		shelter_id = CreateRandomShelterAssignment())
	session.add(new_puppy)
	session.commit()


# from importlib.resources import path
from django.urls import path
from . import views

app_name = 'posts'

urlpatterns = [
    # главная страница
    path('', views.index, name='index'),
    # <slug:название группы>
    path('group/<slug:slug>/', views.group_posts, name='group_list'),
    # Профайл пользователя
    path('profile/<slug:username>/', views.profile, name='profile'),
    # Просмотр записи
    path('posts/<int:post_id>/', views.post_detail, name='post_detail'),
    path('create/', views.post_create, name='post_create'),
    path('posts/<int:post_id>/edit/', views.post_edit, name='post_edit'),
    path(
        'posts/<int:post_id>/comment/',
        views.add_comment,
        name='add_comment'
    ),
    path('follow/', views.follow_index, name='follow_index'),
    # Подписаться на автора
    path(
        'profile/<str:username>/follow/',
        views.profile_follow,
        name='profile_follow'
    ),
    # Отписаться от автоора
    path(
        'profile/<str:username>/unfollow/',
        views.profile_unfollow,
        name='profile_unfollow'
    ),
]


from scipy.fftpack import fft
import matplotlib.pyplot as plt
import numpy as np
from obspy.signal.util import next_pow_2

#Wiggle plots
def wigb(data,t_axis,offsets,amx):
	''' This function plots seismic traces as wiggle plot
	data: Is a matrix of seismic data where the columns are the seismic traces
	t_axis: Is your time axis
	offsets: vector of each trace offset
	amx: is a screen gain to the data'''
	amx2=amx*np.max(data)
	i=0
	for offset in offsets:

		x=np.divide(data[:,i],amx2)+offset
		i=i+1

		plt.plot(x,t_axis,'k')
		plt.fill_betweenx(t_axis,offset,x,where=(x>offset),color='k')

	plt.ylabel('Time (s)')
	plt.xlabel('Offset (m)')
	plt.xlim((offsets[0]-1.,offsets[-1]+1.))
	plt.ylim((0.0,t_axis[-1]))
	plt.gca().invert_yaxis()
	#plt.show()

def pick_wigb(data,t_axis,offsets,filename,amx):
	''' This function enables picking and saving on a seismic wiggle plot
	data: Is a matrix of seismic data where the columns are the seismic traces
	t_axis: Is your time axis
	offsets: vector of each trace offset
	filename: Is the output filename
	amx: is a screen gain to the data'''
	amx2=amx*np.max(data)
	i=0
	for offset in offsets:

		x=np.divide(data[:,i],amx2)+offset
		i=i+1

		plt.plot(x,t_axis,'k')
		plt.fill_betweenx(t_axis,offset,x,where=(x>offset),color='k')

	plt.ylabel('Time (s)')
	plt.xlabel('Offset (m)')
	plt.gca().invert_yaxis()
	plt.xlim((offsets[0]-1.,offsets[-1]+1.))
	picks = plt.ginput( n=0, timeout=0, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)
	np.savetxt(filename, picks)
	plt.show()

def interpret_refract(name):
	'''Select the maximum time each event is observed'''

	M=np.loadtxt(name)

	x=M[:,0]
	t_axis=M[:,1]
	plt.plot(x,t_axis,'k.-')
	plt.ylabel('Time (s)')
	plt.xlabel('Offset (m)')
	picks = plt.ginput( n=0, timeout=0, show_clicks=True, mouse_add=1, mouse_pop=3, mouse_stop=2)
	plt.show()
	ninterfaces=len(picks) #number of layers
	M2=np.array([ninterfaces,0])

	M4=np.vstack([M2,picks,M])
	filename="r_"+name
	np.savetxt(filename, M4)

def ampli_spec(D,header):
	'''Plots the amplitude spectrum for each seismic trace of data matrix D
	in a same graph'''

	dt=header["dt"]
	nx=header['tracl']
	ns=header['ns']
	k=next_pow_2(ns)
	nf=4*(2^k)

	t=np.linspace(0.0,ns*dt,ns)
	tf=np.linspace(0.0,1.0/(2*dt),nf/2)
	i=0
	while i<nx:
		df=fft(D[:,i],nf)
		i=i+1
		plt.plot(tf,2.0/dt*np.abs(df[0:int(nf/2)]))

	plt.ylabel('Amplitude')
	plt.xlabel('Frequency (Hz)')
	plt.grid()
	plt.show()


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Bokeh Visualization Template

This template is a general outline for turning your data into a
visualization using Bokeh.
"""

from __future__ import (division, absolute_import, print_function,
                        unicode_literals)

import os
import pandas as pd

# Bokeh Libraries
from bokeh.plotting import figure, show
from bokeh.io import output_file
from bokeh.models import ColumnDataSource, CategoricalColorMapper
from bokeh.models import NumeralTickFormatter
from bokeh.layouts import gridplot

# Get File Directory
WORK_DIR = os.path.dirname((os.path.realpath(__file__)))

# Read the csv files
player_stats = pd.read_csv(WORK_DIR + '/data/2017-18_playerBoxScore.csv',
                           parse_dates=['gmDate'])
team_stats = pd.read_csv(WORK_DIR + '/data/2017-18_teamBoxScore.csv',
                         parse_dates=['gmDate'])
standings = pd.read_csv(WORK_DIR + '/data/2017-18_standings.csv',
                        parse_dates=['stDate'])

# Output inline in the notebook
output_file('phi-gm-linked-selections.html',
            title='76ers Percentages vs. Win-Loss')

# Isolate relevant data
phi_gm_stats_2 = (
    team_stats[(team_stats['teamAbbr'] == 'PHI')
               & (team_stats['seasTyp'] == 'Regular')].
    loc[:, ['gmDate', 'team2P%', 'team3P%', 'teamPTS', 'opptPTS']].sort_values(
        'gmDate'))

# Add game number
phi_gm_stats_2['game_num'] = range(1, len(phi_gm_stats_2) + 1)

# Derive a win_loss column
win_loss = []
for _, row in phi_gm_stats_2.iterrows():

    # If the 76ers score more points, it's a win
    if row['teamPTS'] > row['opptPTS']:
        win_loss.append('W')
    else:
        win_loss.append('L')

# Add the win_loss data to the DataFrame
phi_gm_stats_2['winLoss'] = win_loss

# Store the data in a ColumnDataSource
gm_stats_cds = ColumnDataSource(phi_gm_stats_2)

# Create a CategoricalColorMapper that
# assigns specific colors to wins and losses
win_loss_mapper = CategoricalColorMapper(factors=['W', 'L'],
                                         palette=['Green', 'Red'])

# Specify the tools
toolList = ['lasso_select', 'tap', 'reset', 'save']

# Create a figure relating the percentages
pctFig = figure(title='2PT FG % vs 3PT FG %, 2017-18 Regular Season',
                plot_height=400,
                plot_width=400,
                tools=toolList,
                x_axis_label='2PT FG%',
                y_axis_label='3PT FG%')

# Draw with circle markers
pctFig.circle(x='team2P%',
              y='team3P%',
              source=gm_stats_cds,
              size=12,
              color='black')

# Format the y-axis tick labels as percenages
pctFig.xaxis[0].formatter = NumeralTickFormatter(format='00.0%')
pctFig.yaxis[0].formatter = NumeralTickFormatter(format='00.0%')

# Create a figure relating the totals
totFig = figure(title='Team Points vs Opponent Points, 2017-18 Regular Season',
                plot_height=400,
                plot_width=400,
                tools=toolList,
                x_axis_label='Team Points',
                y_axis_label='Opponent Points')

# Draw with square markers
totFig.square(x='teamPTS',
              y='opptPTS',
              source=gm_stats_cds,
              size=10,
              color=dict(field='winLoss', transform=win_loss_mapper))

# Create layout
grid = gridplot([[pctFig, totFig]])

# Visualize
show(grid)


from pathlib import Path
import logging
import os
import sys

logger = logging.getLogger("defaultLogger")

def get_newest(path: str, file_extension: str):
    """
    Fetchest name of the newest file in a folder

    args:
    ---

    returns:
    ---
    newest_file -- str
        Name of the newest file in a folder

    """
    logger.info(f"Getting first timestamp from {path}")
    files = list(Path(path).rglob(f"*{file_extension}*"))
    if not files:
        logger.info(f"No files found in {path}")
        logger.warning("EXITING")
        # BUG: NEED A BETTER WAY OF EXITING THE FUNCTION BECAUSE THIS
        # STOPS THE LOOPING THROUGH FILES
        sys.exit(0)

    # linux only
    # newest_file = str(max([f for f in files], key=lambda item: item.stat().st_ctime))
    # cross platform
    newest_file = str(max(files, key=os.path.getmtime))
    return newest_file