from datetime import datetime,timedelta
import os
import logging
import shutil

lista_dados = []
caminho = '/home/hitallo/valcann/backupsFrom'
lista_arquivos = os.listdir(caminho)
caminho_backup = '/home/hitallo/valcann/backupsTo'
caminho_log_backup = '/home/hitallo/valcann/'
caminho_log_To = '/home/hitallo/valcann/'

for arquivo in lista_arquivos:
    # tamanho dos arquivos
    tamanho = os.stat(f'{caminho}/{arquivo}').st_size
    # data de criacao
    data_criacao = os.path.getctime(f'{caminho}/{arquivo}')
    # data da ultima modificacao
    data = os.path.getmtime(f'{caminho}/{arquivo}')
    # lista completa
    lista_dados.append((data, arquivo, data_criacao, tamanho))

logging.basicConfig(filename=f'{caminho_log_backup}/backupsFrom.log' , level=logging.DEBUG)
logging.basicConfig(filename=f'{caminho_log_To}/backupsTo.log', level=logging.DEBUG)

# listando data por ordem  decrescente
lista_dados.sort(reverse=True)

logging.debug("verificando datas")
for arquivo in lista_dados:

    tempo_modificado = arquivo[0]
    date_time = datetime.fromtimestamp(tempo_modificado)
    now = date_time.now()
    tempo_exclusao = now - timedelta(3)

    if tempo_exclusao >= date_time:
        # deletando arquivos com mais de 3 dias
        os.remove(f'{caminho}/{arquivo[1]}')
        print(f'Deletado o arquivo:{arquivo[1]}.')
        # logs de acoes
        logging.debug(f'Hoje: {now}, data dos arquivos: {date_time}')
        logging.debug("Deletando arquivos")

    elif tempo_exclusao <= date_time:
        # copiando arquivos para o caminho
        shutil.copy2(f'{caminho}/{arquivo[1]}',caminho_backup)
        # log de acoes
        logging.warning(f'salvando arquivos {arquivo[1]} em {caminho_backup}')


import itertools

from centrality_metrics.utils import filter_pos, preprocess

TEXT = "Cosmology (from the Greek κόσμος, kosmos 'world' and -λογία, " \
       "-logia 'study of') is a branch of astronomy concerned with the " \
       "studies of the origin and evolution of the universe, from the " \
       "Big Bang to today and on into the future. It is the scientific " \
       "study of the origin, evolution, and eventual fate of the " \
       "universe. Absolutely. Big Apple. Running fast."

def test_filter_pos():
    assert filter_pos("I am running fast towards a library") == "library"

def test_empty_strings():
    preprocessing_args = itertools.product([True, False], repeat=2)

    for stop_filter, pos_filter in preprocessing_args:
        preprocessed_text = preprocess(text="",
                                       stop_filter=stop_filter,
                                       pos_filter=pos_filter)
        assert len(preprocessed_text) == 0

    assert filter_pos("") == ""

def test_preprocess_with_stopword_filtered():
    preprocessed_text = preprocess(TEXT, stop_filter=True,
                                   pos_filter=False)
    assert len(preprocessed_text) == 4

def test_preprocess_with_pos_filtered():
    preprocessed_text = preprocess(TEXT, stop_filter=False,
                                   pos_filter=True)
    assert len(preprocessed_text) == 3

def test_preprocess_with_pos_stopword_filtered():
    preprocessed_text = preprocess(TEXT, stop_filter=True,
                                   pos_filter=True)
    assert len(preprocessed_text) == 3

def test_preprocess_with_no_filter():
    preprocessed_text = \
        preprocess(TEXT, stop_filter=False, pos_filter=False)
    assert len(preprocessed_text) == 5


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 29 13:50:25 2022S

@author: chggo
"""

# Get .h5 files from all the zip files given in the "path"

import os
from zipfile import ZipFile
from modules.logger import logger
from .H5Reader import H5Reader

class dump_helper_with_labels():
    def __init__(self,path):

       self.path=path

    def getlabels(self):

        F=[]

        for item in os.listdir(self.path):
            if item=='DumpFP':
                dd=self.unZip(os.path.join(self.path,'DumpFP'),l=1)
                if dd is not None:
                    F.append(dd)

            elif item=='DumpTP':
                dd=self.unZip(os.path.join(self.path,'DumpTP'),l=0)
                if dd is not None:
                    F.append(dd)

            elif item=='DumpUnsure':
                dd=self.unZip(os.path.join(self.path,'DumpUnsure'),l=None)
                if dd is not None:
                    F.append(dd)
        return(F)

    def unZip(self,p,l=None):

        fold=[]
        j=0
        label=[]
        ZipName=[]
        dictn=None
        dup_loc=[]
        dup_recut=[]

        for item in os.listdir(p):                # loop through items in dir
            if item.endswith('.zip'):                # check for ".zip" extension
                file_name=os.path.join(p,item)
                zip_ref = ZipFile(file_name)         # create zipfile object
                listOfFiles = zip_ref.namelist()
                count=0
                opd=os.path.dirname
                logger.info('{} zipfile is opened'.format(j))
                for f in listOfFiles :

                    if f.endswith('.h5') and opd(f)=='data/lossOfCutDetected':

                         f2=zip_ref.open(f)
                         dup_loc.append(f2)
                         count=count+1
                    elif f.endswith('.h5') and opd(f)=='data/lossOfCutRecut':

                         f2=zip_ref.open(f)
                         dup_recut.append(f2)
                         count=count+1
                if count !=2 :                            #(more than 2 .h5 files in any folder)

                    logger.info('-------------------------------------------------------------------')
                    logger.info('Number of .h5 file in dump {} is {}'.format(j,count))

                emp=self.empty(dup_loc[-1],j)
                emp1=self.empty(dup_recut[-1],j)
                if emp==False and emp1 ==False:

                    # append only last two elements to fix more than 2 .h5 files error
                    fold.append(dup_loc[-1])
                    fold.append(dup_recut[-1])

                    label.append(l)
                    ZipName.append(item)

                j=j+1
                zip_ref.close()
        dictn={'fold':fold,'label':label,'ZipName':ZipName}

        return(dictn)

    def createFolder(self):

        foldTest=0
        F=self.getlabels()
        logger.info('total zip files read from FP:{}'.format(len(F[0]['fold'])/2))
        logger.info('total zip files read from TP : {}'.format(len(F[1]['fold'])/2))
        logger.info('total zip files read from UnSure:{}'.format(len(F[2]['fold'])/2))

        if len(F)==1:
            fold=(F[0]['fold'])
            labels=(F[0]['label'])
            ZipName=(F[0]['ZipName'])
        elif len(F)==2:
            fold=F[0]['fold']+F[1]['fold']
            labels=F[0]['label']+F[1]['label']
            ZipName=F[0]['ZipName']+F[1]['ZipName']
        elif len(F)==3:
            fold=F[0]['fold']+F[1]['fold']
            labels=F[0]['label']+F[1]['label']
            ZipName=F[0]['ZipName']+F[1]['ZipName']
            foldTest=F[2]['fold']
            zipTest=F[2]['ZipName']

        return(fold,labels,foldTest,ZipName,zipTest)

    def empty(self,fold1,dumpNum,setLimit=90):

        emp=False
        H5File=H5Reader(fold1)
        h5=H5File.readH5()

        ecat=h5['ecat']

        if ecat.shape[0]<setLimit:
            emp=True
            logger.info('discard dump {}'.format(dumpNum))

        return(emp)


import sys, subprocess

top = '.'
out = 'build'

def options(cnf):
	cnf.load('compiler_c compiler_cxx')
	cnf.add_option('-w', '--windows', dest='windows_build', default=False, action='store_true', help='Enables windows builds')
	cnf.add_option('-d', '--debug', dest='debug_build', default=False, action='store_true', help='Enables debug info')

def configure(cnf):
	cnf.env.BINPREFIX = ''
	cnf.env.ACTUAL_LIBDIR = []

	cnf.env.DEBUG_BUILD = cnf.options.debug_build

	if cnf.options.windows_build:
		cnf.env.WINDOWS_BUILD = True

		cnf.env.PREFIX = '/opt/mxe/usr/i686-w64-mingw32.static'
		cnf.env.BINDIR = ['/opt/mxe/usr/bin/', cnf.env.PREFIX+'/bin/']
		cnf.env.LIBDIR = [cnf.env.PREFIX+'/lib/']
		cnf.env.ACTUAL_LIBDIR = cnf.env.LIBDIR
		cnf.env.BINPREFIX = '/opt/mxe/usr/bin/i686-w64-mingw32.static-'

		cnf.find_program('i686-w64-mingw32.static-g++', var = 'CXX', mandatory = True, path_list = cnf.env.BINDIR)
		cnf.find_program('i686-w64-mingw32.static-gcc', var = 'CC', mandatory = True, path_list = cnf.env.BINDIR)
		cnf.find_program('i686-w64-mingw32.static-ar', var = 'AR', mandatory = True, path_list = cnf.env.BINDIR)

	cnf.load('compiler_c compiler_cxx')
	cnf.check_cfg(path=cnf.env.BINPREFIX + 'sdl2-config', args='--cflags --libs',
				package='', uselib_store='SDL2')

	cnf.check_cfg(args='--cflags --libs', package='lua5.2', uselib_store='lua')
	cnf.check_cfg(args='--cflags --libs', package='bullet', uselib_store='bullet')

def build(bld):
	sflags = ['-O2', '-std=c++11', '-Wall', '-Wextra']
	includes = ['.']
	libs = []

	if bld.env.DEBUG_BUILD:
		sflags += ['-g']

	if bld.env.DEST_OS.find("linux") >= 0:
		libs += ['dl', 'GL']
	elif bld.env.DEST_OS.find("win32") >= 0 or bld.env.WINDOWS_BUILD:
		libs += ['opengl32']

	# Build dependencies
	bld.objects(
		target		=	'ext',
		# source	=	bld.path.ant_glob("ext/*.c*"),
		source		=	bld.path.ant_glob("ext/stb_stub.c"),
		features	=	'c'
	)

	bld.recurse("lua-synth")

	bld.program(
		target		=	'voi',
		source		=	bld.path.ant_glob("*.cpp"),
		features	=	'cxx cxxprogram',

		includes	=	includes,
		lib			=	libs,
		libpath		=	bld.env.ACTUAL_LIBDIR,

		use			=	'SDL2 ext lua bullet synth',

		cxxflags	=	sflags
	)

def run(ctx):
	subprocess.Popen("build/voi")
	# subprocess.Popen(["optirun", "build/voi"])

def package(ctx):
	# suffix = ''
	# if ctx.env.WINDOWS_BUILD:
	# 	suffix = '.exe'

	files = []
	files += ['scripts/test5.lua', 'data/cursor.png', 'data/cursor2.png', 'Testing/test5.voi', 'voi.cfg']

	# ctx.exec_command('mkdir __voi_package')
	# for f in files
	# ctx.exec_command('cp %s __voi_package' % f)

	ctx.exec_command('tar -caf package.tar.gz %s' % ' '.join(str(x) for x in files))
	ctx.exec_command('tar -raf ../package.tar.gz voi.exe', cwd = 'build')


from pathlib import Path

def RfileSearch(pathlist):

    if len(pathlist) == 0:
        return []
    else:
        if pathlist[0].is_file():
            return [pathlist[0]] + RfileSearch(pathlist[1:])
        else:
            return RfileSearch(list(pathlist[0].iterdir())) + RfileSearch(pathlist[1:])

def getSearchOption():

    interest = input("Enter option (N,E,<,> followed by name, extension or size): ").split()
    valid_input = ['N','E','<','>']

    if (interest[0] == 'T'):
        while(interest[0] == 'T' and len(interest) < 2):
            print("ERROR")
            interest = input("Enter again: ").split()
        nInterest = list(map(str, interest[1:]))
        interest = [interest[0], ' '.join(nInterest)]

    elif (interest[0] != 'A' or interest[0] != 'T'):
        while (len(interest) != 2 or interest[0] not in valid_input):
            print("ERROR")
            interest = input("").split()

    return interest

def getPaths():

    pathTd = input("Enter mode and path (R/D <path>): ").split()

    while ((len(pathTd) != 2) or (not Path(pathTd[1]).exists())):
        print("ERROR")
        pathTd = input("Enter again: ").split()

    (mode, path) = (pathTd[0],Path(pathTd[1]))

    if mode == "D":
        files = list(path.iterdir())
    else:
        files = RfileSearch(list(path.iterdir()))
        files.sort(key = lambda x: str(x).count("/"))

    final_files = []

    for i in files:
        if str(i).split('/')[-1][0] != '.':
            final_files.append(i)

    return final_files

def requiredFiles(interest, files):

    output = []
    if interest[0] == 'A':
        for i in files:
            output.append(i)

    elif interest[0] == 'N':
        interest[1] = str(interest[1])
        for i in files:
            if i.name[:len(interest[1])] == interest[1]:
                      output.append(i)

    elif interest[0] == 'E':
        interest[1] = str(interest[1])
        if ('.' in interest[1]):
            interest[1] = interest[1].replace('.','')
        for i in files:
            if i.suffix[1:] == interest[1]:
                output.append(i)

    elif interest[0] == 'T':
        interest[1] = str(interest[1])

        for i in files:
            try:
                infile = i.open('r')
                for lines in infile:
                    if interest[1] in lines:
                        output.append(i)
            except:
                continue

    elif interest[0] == '>':
        try:
            value = int(interest[1])
            for i in files:
                if i.stat().st_size > value:
                    output.append(i)
        except ValueError:
            raise ValueError

    elif interest[0] == '<':
        try:
            value = int(interest[1])
            for i in files:
                if i.stat().st_size < value:
                    output.append(i)
        except ValueError:
            raise ValueError

    return output

def getAction():

    action = input("Enter option: ")
    while ((action != 'F') and (action != 'D') and (action != 'T')):
        print ("ERROR")
        action = input("Enter again: ")

    return action

def main():

    files = getPaths()

    interest = getSearchOption()

    result = requiredFiles(interest, files)

    if len(result) != 0:
        for i in result:
            print(i)

        choice = getAction()

        if (choice == 'F'):
            for i in result:
                try:
                    infile = i.open('r')
                    print(infile.readline().strip())
                    infile.close()
                except:
                    print("NOT A TEXT")

        if (choice == 'D'):
            for i in result:
                infile = i.open('r')
                newP = Path(str(i) + '.dup')
                outfile = newP.open('w')
                for line in infile:
                    outfile.write(line)
                infile.close()
                outfile.close()

        if (choice == 'T'):
            for i in result:
                i.touch()

if __name__ == '__main__':
    main()


import unittest
import xtypes_py

class TestComponent(unittest.TestCase):

    def test_instance_of(self):
        cm = xtypes_py.ComponentModel()
        c = xtypes_py.Component()
        model = xtypes_py.ComponentModel()
        c.add_model(model)
        assert c.has_relation("model")
        assert c.has_facts("model")
        assert c.get_facts("model")
        assert len(c.get_facts("model")) > 0
        assert type(c.get_facts("model")[0][0]) == xtypes_py.ComponentModel

    def test_part_of(self):
        cm = xtypes_py.ComponentModel()
        cm.set_all_unknown_facts_empty()
        c = xtypes_py.Component()
        c.set_all_unknown_facts_empty()
        whole = xtypes_py.ComponentModel()
        whole.set_all_unknown_facts_empty()
        c.add_whole(whole)
        assert c.has_relation("model")
        assert c.has_facts("model")
        assert c.get_facts("whole")
        assert len(c.get_facts("whole")) == 1
        assert type(c.get_facts("whole")[0][0]) == xtypes_py.ComponentModel

    def test_has(self):
        c = xtypes_py.Component()
        i= xtypes_py.Interface()
        c.add_interfaces(i)
        assert c.get_interface("UNKNOWN")

    def test_get_interface(self):
        c = xtypes_py.Component()
        i = xtypes_py.Interface()
        local_interface_instance = xtypes_py.Interface()
        i.name = "name1"
        c.add_interfaces(local_interface_instance)
        local_interface_instance.name = "name2"
        c.add_interfaces(i)
        obj1 = c.get_interface("name1")
        obj2 = c.get_interface("name2")
        assert obj1.name == i.name
        assert obj1 == i
        assert obj2.name == local_interface_instance.name

if __name__ == '__main__':

    unittest.main()


HOST="C:\Windows\System32\drivers\etc\hosts"
REDIRECT_IP='127.0.0.1'

def block_website(websites):
    '''Blocks the all the websites which are mentioned in the list'''

    if type(websites) != type([]):
        raise TypeError('Paramerter websites expects a list')

    with open(HOST,'r+') as f:
        content=f.read()

        for website in websites:

            if website not in content:
                f.write("{} {}\n".format(REDIRECT_IP,website))

    f.close()
    print('Given Websites are Blocked !',end='\n\n')

def unblock_website(websites):
    with open(HOST,'r+') as f:
        content=f.readlines()
        f.seek(0)

        for line in content:
            if not any(website in line for website in websites):
                f.write(line)
        f.truncate()
        f.close()
    print('Given Wnsites are Unblocked !',end='\n\n')

if __name__=='__main__':
    while True:
        for op in ["1.Block Website","2.UnBlock Website","3.Exit"]:
            print(op)
        option=int(input('Enter option number :'))

        if option==1:
            print('You have chosen option 1: To Block Websites')
            print('Please Enter the websites you want to block seperated by a comma (,)',end='\n\n')
            webpages=input('Enter Websites :')
            webpages=webpages.split(',')
            block_website(webpages)

        elif option==2:
            print('You have chosen option 2: To Unblock Websites')
            print('Please Enter the websites you want to unblock seperated by a comma (,)',end='\n\n')
            webpages=input('Enter Websites :')
            webpages=webpages.split(',')
            unblock_website(webpages)

        elif option==3:
            print('Exiting Program')
            break
        else:
            print('Wrong Option')
            break


""" Definitions of blocks, and the genesis block. """

from datetime import datetime
from binascii import hexlify, unhexlify

import json
import logging

import src.utils as utils

from .config import *
from .merkle import merkle_tree
from .crypto import get_hasher

__all__ = ['Block']

class Block:
    """
    A block: a container for all the data associated with a block.

    To figure out whether the block is valid on top of a block chain, there are a few `verify`
    methods. Without calling these, you must assume the block was crafted maliciously.

    :ivar hash: The hash value of this block.
    :vartype hash: bytes
    :ivar id: The ID of this block. Genesis-Block has the ID '0'.
    :vartype id: int
    :ivar prev_block_hash: The hash of the previous block.
    :vartype prev_block_hash: bytes
    :ivar merkle_root_hash: The hash of the merkle tree root of the transactions in this block.
    :vartype merkle_root_hash: bytes
    :ivar time: The time when this block was created.
    :vartype time: datetime
    :ivar nonce: The nonce in this block that was required to achieve the proof of work.
    :vartype nonce: int
    :ivar height: The height (accumulated target) of this block.
    :vartype height: int
    :ivar received_time: The time when we received this block.
    :vartype received_time: datetime
    :ivar target: The target of this block.
    :vartype target: int
    :ivar transactions: The list of transactions in this block.
    :vartype transactions: List[Transaction]
    """

    # TODO: Check if  "id" is really needed. Should be the same as "height".

    def __init__(self, prev_block_hash, time, nonce, height, received_time, target, transactions,
                 merkle_root_hash=None, id=None):
        self.id = id
        self.prev_block_hash = prev_block_hash
        self.merkle_root_hash = merkle_root_hash
        self.time = time
        self.nonce = nonce
        self.height = height
        self.received_time = received_time
        self.target = target
        self.transactions = transactions
        self._hash = self._get_hash()

    @property
    def hash(self):
        return self._hash

    @hash.setter
    def hash(self, value):
        self._hash = value

    def to_json_compatible(self):
        """ Returns a JSON-serializable representation of this object. """
        val = {}
        val['id'] = self.id
        val['hash'] = hexlify(self._hash).decode()
        val['prev_block_hash'] = hexlify(self.prev_block_hash).decode()
        val['merkle_root_hash'] = hexlify(self.merkle_root_hash).decode()
        val['time'] = self.time.strftime("%Y-%m-%dT%H:%M:%S.%f UTC")
        val['nonce'] = self.nonce
        val['height'] = self.height
        val['target'] = self.target
        val['transactions'] = [t.to_json_compatible() for t in self.transactions]
        return val

    @classmethod
    def from_json_compatible(cls, val):
        """ Create a new block from its JSON-serializable representation. """
        from .transaction import Transaction
        return cls(unhexlify(val['prev_block_hash']),
                   datetime.strptime(val['time'], "%Y-%m-%dT%H:%M:%S.%f UTC"),
                   int(val['nonce']),
                   int(val['height']),
                   datetime.utcnow(),
                   int(val['target']),
                   [Transaction.from_json_compatible(t) for t in list(val['transactions'])],
                   unhexlify(val['merkle_root_hash']),
                   int(val['id']))

    @classmethod
    def create(cls, chain_difficulty: int, prev_block: 'Block', transactions: list, ts=None):
        """
        Create a new block for a certain blockchain, containing certain transactions.
        """
        tree = merkle_tree(transactions)
        difficulty = chain_difficulty
        id = prev_block.height + 1
        if ts is None:
            ts = datetime.utcnow()
        if ts <= prev_block.time:
            ts = prev_block.time + timedelta(microseconds=1)
        return Block(prev_block.hash, ts, 0, prev_block.height + 1,
                     None, difficulty, transactions, tree.get_hash(), id)

    def __str__(self):
        return json.dumps(self.to_json_compatible(), indent=4)

    def get_partial_hash(self):
        """
        Computes a hash over the contents of this block, except for the nonce. The proof of
        work can use this partial hash to efficiently try different nonces. Other uses should
        use `hash` to get the complete hash.
        """
        hasher = get_hasher()
        hasher.update(self.prev_block_hash)
        hasher.update(self.merkle_root_hash)
        hasher.update(self.time.strftime("%Y-%m-%dT%H:%M:%S.%f UTC").encode())
        hasher.update(utils.int_to_bytes(self.target))
        return hasher

    def finish_hash(self, hasher):
        """
        Finishes the hash in `hasher` with the nonce in this block. The proof of
        work can use this function to efficiently try different nonces. Other uses should
        use `hash` to get the complete hash in one step.
        """
        hasher.update(utils.int_to_bytes(self.nonce))
        return hasher.digest()

    def _get_hash(self):
        """ Compute the hash of the header data. This is not necessarily the received hash value for this block! """
        hasher = self.get_partial_hash()
        return self.finish_hash(hasher)

    def verify_merkle(self):
        """ Verify that the merkle root hash is correct for the transactions in this block. """
        return merkle_tree(self.transactions).get_hash() == self.merkle_root_hash

    def verify_proof_of_work(self):
        """ Verify the proof of work on a block. """
        return int.from_bytes(self._hash, 'big') < self.target

    def verify_difficulty(self):
        """ Verifies that the hash value is correct and fulfills its target promise. """
        if not self.verify_proof_of_work():
            logging.warning("block does not satisfy proof of work")
            return False
        return True

    def verify_prev_block(self, prev_block: 'Block', chain_target: int):
        """ Verifies that the previous block pointer points to the head of the given blockchain and target and height are correct. """
        if prev_block.hash != self.prev_block_hash:
            logging.warning("Previous block is not head of the block chain.")
            return False

        if self.target != chain_target:
            logging.warning("Block has wrong target.")
            return False
        if prev_block.height + 1 != self.height:
            logging.warning("Block has wrong height.")
            return False
        return True

    def verify_block_transactions(self, unspent_coins: dict, reward: int):
        """ Verifies that all transaction in this block are valid in the given blockchain. """
        mining_rewards = []
        all_inputs = []
        for t in self.transactions:
            all_inputs += t.inputs
            if t.inputs[0].is_coinbase:
                if len(mining_rewards) > 1:
                    logging.warning("block has more than one coinbase transaction")
                    return False
                mining_rewards.append(t)

            if not t.validate_tx(unspent_coins):
                return False

        fees = sum(t.get_transaction_fee(unspent_coins) for t in self.transactions)
        actual_reward_and_fees = sum(t.amount for t in mining_rewards[0].targets)

        if actual_reward_and_fees > reward + fees:
            warn = "{} is different than specified({})".format(actual_reward_and_fees, reward+fees)
            logging.error(warn)
            return False

        if not self._verify_input_consistency(all_inputs):
            return False

        return True

    def _verify_input_consistency(self, tx_inputs: 'List[TransactionInputs]'):
        """"Verify that all the transactions in the transaction list are not spending from a same input transaction and index"""
        tx_inp = [(i.transaction_hash, i.output_idx) for i in tx_inputs]
        return len(tx_inp) == len(set(tx_inp))

    def verify_time(self, head_time: datetime):
        """
        Verifies that blocks are not from far in the future, but a bit younger
        than the head of `chain`.
        """
        if self.time - timedelta(hours=2) > datetime.utcnow():
            logging.warning("discarding block because it is from the far future")
            return False
        if self.time <= head_time:
            logging.warning("discarding block because it is younger than its predecessor")
            return False
        return True

    def verify(self, prev_block: 'Block', chain_difficulty: int, unspent_coins: dict, chain_indices: dict, reward: int):
        """
        Verifies that this block contains only valid data and can be applied on top of the block
        chain `chain`.
        """
        assert self._hash not in chain_indices
        if self.height == 0:
            logging.warning("only the genesis block may have height=0")
            return False

        return self.verify_difficulty() and self.verify_merkle() and self.verify_prev_block(prev_block,
                                                                                chain_difficulty) \
               and self.verify_time(prev_block
                                    .time) and self.verify_block_transactions(unspent_coins, reward)


# from selenium import webdriver
# from selenium.webdriver.common.by import By
from pages.demoqa import DemoQA

def test_icon_exist(browser):
    demo_page = DemoQA(browser)
    demo_page.visit()
    demo_page.icon.click()
    assert demo_page.equal_url()
    assert demo_page.icon.exist()

#     # driver = webdriver.Chrome()
#     browser.get("https://demoqa.com/")
#     icon = browser.find_element(By.CSS_SELECTOR, "#app > header > a")
#
#     if icon is None:
#         print('Элемент не найден')
#     else:
#         print('Элемент найден')


"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Coset Enumeration using Todd-Coxeter Algorithm
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Reference:
    [1] "Handbook of Computational Group Theory", Holt, D., Eick, B., O'Brien, E.
    [2] "Computation with finitely presented groups", Charles C.Sims.
    [3] GAP doc at "https://www.gap-system.org/Manuals/doc/ref/chap47.html".
    [4] Ken Brown's code at "http://www.math.cornell.edu/~kbrown/toddcox/".

"""

class CosetTable:
    """
    Let G = < X | R > be a finitely presented group and H be a subgroup of
    G with |G:H| < inf. The coset table T of G/H is a 2D array with rows
    indexed by the right cosets of G/H and columns indexed by the generators
    of G and their inverses. The entry of T at row k and column x (x is a
    generator or the inverse of a generator) records the right action of
    coset k by x: T[k][x] = kx. If T[k][x] is not defined yet we set it to
    None. When the algorithm terminates all entries in the table are
    assigned a non-negative integer, all rows scan correctly under all words
    in R and the first row scans correctly under all generators of H.
    """

    def __init__(self, gens, rels, subgens=(), coxeter=True):
        """
        :param gens: a 1D list of integers that represents the generators,
            e.g. [0, 1, 2] for [a, b, c]

        :param rels: a 2D list of integers that represents the relators R,
            e.g. [[0, 0], [1, 1, 1], [0, 2]*3] for a^2 = b^3 = (ac)^3 = 1

        :param subgens: a 2D list of integers that represents the subgroup generators,
            e.g. [[0, 2]] for < ac >.

        :param coxeter: whether this is a Coxeter group. If false then the inverse of
            the generators are also included as generators, otherwise they are not.

        we use a list p to hold the equivalence classes of the cosets,
        p[k] = l means k and l really represent the same coset. It's always
        true that p[k] <= k, if p[k] = k then we call k "alive" otherwise we call
        k "dead". All cosets are created "alive", but as the algorithm runs
        some of them may be declared to "dead" and their rows are deleted from
        the table (we do not explicitly free the memory of these row but keep
        in mind that they do not belong to our table).

        A "dead" coset arise when an `coincidence` is found, and while handling
        this coincidence more coincidences may also be found, so we use a queue
        q to hold them.
        """
        self.coxeter = coxeter
        if coxeter:
            self.inv = lambda x: x
        else:
            self.inv = lambda x: x - 1 if x % 2 else x + 1
        self.A = gens
        self.R = rels  # relations R between the generators
        self.H = subgens  # generators of H
        self.p = [0]  # initially we only have the 0-th coset H
        self.q = []  # a queue holds all dead cosets to be processed.
        self.table = [[None] * len(self.A)]

    def __getitem__(self, item):
        return self.table.__getitem__(item)

    def __len__(self):
        return len(self.table)

    def is_alive(self, coset):
        """Check if a coset is alive.
        """
        return self.p[coset] == coset

    def is_defined(self, coset, x):
        """Check if an entry is defined.
        """
        return self[coset][x] is not None

    def undefine(self, coset, x):
        self[coset][x] = None

    def define(self, coset, x):
        """
        To define a new coset we need to:
        1. Append a new empty row to the table.
        2. Fill the two entries.
        3. Add this new coset to `p`.
        """
        n = len(self.table)
        self.table.append([None] * len(self.A))
        self[coset][x] = n
        self[n][self.inv(x)] = coset
        self.p.append(n)

    def rep(self, coset):
        """Find the minimal equivalent representative of a given coset
        and modify `p` along the way.
        """
        m = coset
        while m != self.p[m]:
            m = self.p[m]

        j = coset
        while j != self.p[j]:
            j, self.p[j] = self.p[j], m

        return m

    def merge(self, coset1, coset2):
        """
        Merge two equivalent cosets. The larger one is declared to "dead"
        and is added to the queue `q` to be processed later on.
        """
        s = self.rep(coset1)
        t = self.rep(coset2)
        if s != t:
            s, t = min(s, t), max(s, t)
            self.p[t] = s
            self.q.append(t)

    def scan_and_fill(self, coset, word):
        """
        Scan the row of a coset under a given word.
        1. Firstly we start from the left and scan forward to the right as
           far as possible.
           (1a) If it completes correctly then it yields no
                information, do nothing.
           (1b) If it completes incorrectly then a coincidence
                is found, process it.
           (1c) If it does not complete, go to step 2.
        2. Then we start from the right and scan backward to the left as far
           as possible until it "meets" the forward scan `f`. Let this scan
           results in coset `b`.
           (2a) if `f` and `b` overlap, then a coincidence
                is found, process it.
           (2b) if `f` and `b` are about to meet (with a length 1 gap between)
                then a deduction is found, fill in the two new entries.
           (2c) else the scan is incomplete, define a new coset
                and continue scanning forward.
        """
        f = coset
        b = coset
        i = 0
        j = len(word) - 1
        while True:
            # scan forward as far as possible.
            while i <= j and self.is_defined(f, word[i]):
                f = self[f][word[i]]
                i += 1
            # if complete
            if i > j:
                # if complete incorrectly a coincidence is found, process it.
                if f != b:
                    self.coincidence(f, b)
                # else the scan yields no information
                return

            # if scan forward is not completed then scan backward as
            # far as possible until it meets the forward scan.
            while j >= i and self.is_defined(b, self.inv(word[j])):
                b = self[b][self.inv(word[j])]
                j -= 1

            # if f and b overlap then a coincidence is found.
            if j < i:
                self.coincidence(f, b)
                return
            # if f and b are about to meet a deduction is found.
            elif j == i:
                self[f][word[i]] = b
                self[b][self.inv(word[i])] = f
                return
            # else define a new coset and continue scanning forward.
            else:
                self.define(f, word[i])

    def coincidence(self, coset1, coset2):
        """
        Process a coincidence. When two cosets are found to be equivalent
        the larger one is deleted: we need to copy all information in its
        row to the equivalent row and modify all entries it occurs in the
        table. During this process new coincidences may be found and they
        are also processed. The subtle thing here is that we must keep
        filling/deleting entries in pairs, i.e. we must make sure the table
        always satisfy table[k][x] = l <===> table[l][y] = k (y = inv(x)).
        """
        self.merge(coset1, coset2)
        # at this stage the queue contains only one item,
        # but new items may be added to it later.
        while len(self.q) > 0:
            e = self.q.pop(0)
            for x in self.A:
                if self.is_defined(e, x):
                    f = self[e][x]
                    y = self.inv(x)
                    # the entry (f, y) in the row f is also deleted since we
                    # must make sure all entries in the table come in pairs.
                    self.undefine(f, y)
                    # copy the information at (e, x) to (e1, x),
                    # but is (e1, x) already defined?
                    e1 = self.rep(e)
                    f1 = self.rep(f)
                    # if (e1, x) is already defined then
                    # a new coincidence is found.
                    if self.is_defined(e1, x):
                        self.merge(f1, self.table[e1][x])
                    elif self.is_defined(f1, y):
                        self.merge(e1, self.table[f1][y])
                    else:
                        # else (e1, x) is not defined, copy the information
                        # at (e, x) to (e1, x).
                        self[e1][x] = f1
                        self[f1][y] = e1
                        # keep in mind all changes come in pairs,
                        # so we also copy the information at (f, y) to (f1, y).

    def hlt(self):
        """Run the HLT strategy (Haselgrove, Leech and Trotter).
        """
        for word in self.H:
            self.scan_and_fill(0, word)

        current = 0
        while current < len(self.table):
            for rel in self.R:
                if not self.is_alive(current):
                    break
                self.scan_and_fill(current, rel)

            if self.is_alive(current):
                for x in self.A:
                    if not self.is_defined(current, x):
                        self.define(current, x)
            current += 1

    def compress(self):
        """
        Delete all dead cosets in the table. The live cosets are renumbered and
        their entries are also updated.
        """
        ind = -1
        for coset in range(len(self)):
            if self.is_alive(coset):
                ind += 1
                if ind != coset:
                    for x in self.A:
                        y = self[coset][x]
                        if y == coset:
                            self[ind][x] = ind
                        else:
                            self[ind][x] = y
                            self[y][self.inv(x)] = ind

        self.p = list(range(ind + 1))
        self.table = self.table[: len(self.p)]

    def swap(self, k, l):
        """
        Swap two live cosets in the table. It's called in the `standardize()`
        method after the table is compressed, but it also works for
        non-compressed table.
        """
        for x in self.A:
            # swap the two rows k and l.
            self[k][x], self[l][x] = self[l][x], self[k][x]
            # modify all k/l in the table.
            for coset in range(len(self)):
                # this check is not required for a compressed table.
                if self.is_alive(coset):
                    if self[coset][x] == k:
                        self[coset][x] = l
                    elif self[coset][x] == l:
                        self[coset][x] = k

    def standardize(self):
        """Rearrange the cosets in the table to a standard form.
        """
        # the next coset we want to encounter in the table.
        next_coset = 1
        for coset in range(len(self)):
            for x in self.A:
                y = self[coset][x]
                if y >= next_coset:
                    if y > next_coset:
                        self.swap(y, next_coset)
                    next_coset += 1
                    if next_coset == len(self) - 1:
                        return

    def run(self, standard=False):
        self.hlt()
        self.compress()
        if standard:
            self.standardize()

    def get_words(self):
        """
        Return the list of all words in this table. This method must be called
        when the table is already compressed.
        """
        from collections import deque

        gens = self.A if self.coxeter else self.A[::2]
        result = [None] * len(self)
        result[0] = ()
        q = deque([0])
        while q:
            coset = q.popleft()
            for x in gens:
                new_coset = self[coset][x]
                if result[new_coset] is None:
                    result[new_coset] = result[coset] + (x,)
                    q.append(new_coset)
        return result


import json
from socket import timeout

class Point:
    def __init__(self, row, column):
        self._row = row
        self._column = column

    @property
    def row(self):
        return self._row

    @property
    def column(self):
        return self._column

    def serialize(self):
        return {"row": self._row, "column": self._column}

class Player:
    def __init__(self, id, socket, name, group, teammate, coordinate):
        self._id = id
        self._socket = socket
        self._name = name
        self._group = group
        self._teammate = teammate
        self._coordinate = coordinate

    @property
    def id(self):
        return self._id

    @property
    def socket(self):
        return self._socket

    @property
    def name(self):
        return self._name

    @property
    def group(self):
        return self._group

    @property
    def teammate(self):
        return self._teammate

    @property
    def coordinate(self):
        return self._coordinate

    @coordinate.setter
    def coordinate(self, coordinate):
        self._coordinate = coordinate

    def serialize(self):
        return {
            "id": self._id,
            "name": self._name,
            "group": self._group,
            "coordinate": self._coordinate.serialize(),
            "teammate": self._teammate,
        }

class Cell:
    def __init__(self, coordinate: Point):
        self._coordinate = coordinate
        self._player = None

    @property
    def coordinate(self):
        return self._coordinate

    @property
    def player(self):
        return self._player

    @player.setter
    def player(self, player):
        self._player = player

    def serialize(self):
        return {
            "coordinate": self._coordinate.serialize(),
            "player": self._player.serialize(),
        }

class Game:
    def __init__(self, players: list):
        self._height = 13
        self._width = 13
        self._cycle = 1
        self._turn = -1
        self._grid = []

        for i in range(self._height):
            for j in range(self._width):
                self._grid.append((Cell(Point(i, j))))

        self._players = players
        self._walls = {}

    @property
    def cycle(self):
        return self._cycle

    @property
    def turn(self):
        return self._turn

    @property
    def grid(self):
        return self._grid

    @property
    def players(self):
        return self._players

    @property
    def walls(self):
        return self._walls

    def adjacents(self, cell):
        adjs = []
        adjR = [0, 0, 1, -1]
        adjC = [1, -1, 0, 0]
        dir = ['R', 'L', 'D', 'U']
        for i in range(4):
            if cell.coordinate in self._walls.keys():
                if dir[i] in self._walls[cell.coordinate]:
                    continue
            new_cell = Cell(Point(cell.coordinate.row + adjR[i], cell.coordinate.column + adjC[i]))
            if 0 <= new_cell.coordinate.row < self._height and 0 <= new_cell.coordinate.column < self._width:
                adjs.append((dir[i], new_cell))
        return adjs

    @staticmethod
    def index(row, column):
        return row*13+column

    def run(self):
        win = False
        if self._cycle == 1:
            res = {
                "type": "NOP",
                "turn": 0
            }
            for p, conn in self._players:
                conn.send((json.dumps(res) + '\n').encode())
                print(res)
            print("Sent NOP to all for the first time")

        else:
            l = [0, 2, 1, 3]
            player, conn = self._players[l[self._turn]]
            res = {"player": player.id}
            conn.settimeout(20)
            try:
                data = conn.recv(1024)
                str_data = json.loads(data.decode())
                type_ = str_data['type']
                print(str_data)
                res['turn'] = l[(self._turn + 1) % 4]

                if type_ == 'MOVE':
                    res['type'] = type_
                    action = str_data['action']
                    res['action'] = action
                    player_cell = self._grid[Game.index(player.coordinate.row, player.coordinate.column)]
                    adjs = self.adjacents(player_cell)
                    print(adjs)
                    for act, cell in adjs:
                        print(act, action)
                        if action == act:
                            self._grid[self.index(player.coordinate.row, player.coordinate.column)].player = None
                            player.coordinate = cell.coordinate
                            self._grid[self.index(cell.coordinate.row, cell.coordinate.column)] = player
                            print(player.coordinate.row, player.coordinate.column)
                            if player.coordinate.row == 6 and player.coordinate.column == 6:
                                res['type'] = "WIN"
                                res['group'] = player.group
                                win = True

                elif type_ == 'BLOCK':
                    res['type'] = type_
                    point1 = Point(str_data['point1']['row'], str_data['point1']['column'])
                    point2 = Point(str_data['point2']['row'], str_data['point2']['column'])
                    print(point1.row, point1.column, " ", point2.row, point2.column)

                    if point1 not in self._walls.keys():
                        self._walls[point1] = []
                    if point2 not in self._walls.keys():
                        self._walls[point2] = []

                    if point1.row == point2.row + 1:
                        self._walls[point1].append('U')
                        self._walls[point2].append('D')

                    elif point1.row == point2.row - 1:
                        self._walls[point1].append('D')
                        self._walls[point2].append('U')

                    elif point1.column == point2.column + 1:
                        self._walls[point1].append('L')
                        self._walls[point1].append('R')

                    elif point1.column == point2.column - 1:
                        self._walls[point1].append('R')
                        self._walls[point1].append('L')

                    res['point1'] = point1.serialize()
                    res['point2'] = point2.serialize()

                for p, conn in self._players:
                    conn.send((json.dumps(res) + '\n').encode())
                    print(json.dumps(res))

                if win:
                    return

            except:
                print("timeout")
                res = {
                    "type": "NOP",
                    "turn": l[(self._turn + 1) % 4],
                }
                for p, conn in self._players:
                    conn.send((json.dumps(res) + '\n').encode())

        self._turn = (self._turn + 1) % 4
        self._cycle += 1
        self.run()


# file_en = "es-en/europarl-v7.es-en.en"
# file_es = "es-en/europarl-v7.es-en.es"

file_en = "english_million.txt"
file_es = "spanish_million.txt"

num = 100000

# for i in range(num):
#     file3.writelines(file1.readline())

##########################################
# Source : https://machinelearningmastery.com/prepare-french-english-dataset-machine-translation/

import string
import re
from pickle import dump
from unicodedata import normalize

# load doc into memory
def load_doc(filename):
	# open the file as read only
	file = open(filename, mode='rt', encoding='utf-8')
	# read all text
	text = file.read()
	# close the file
	file.close()
	return text

# split a loaded document into sentences
def to_sentences(doc):
	return doc.strip().split('\n')

# clean a list of lines
def clean_lines(lines):
	cleaned = list()
	# prepare regex for char filtering
	re_print = re.compile('[^%s]' % re.escape(string.printable))
	# prepare translation table for removing punctuation
	table = str.maketrans('', '', string.punctuation)
	for line in lines:
		# normalize unicode characters
		line = normalize('NFD', line).encode('ascii', 'ignore')
		line = line.decode('UTF-8')
		# tokenize on white space
		line = line.split()
		# convert to lower case
		line = [word.lower() for word in line]
		# remove punctuation from each token
		line = [word.translate(table) for word in line]
		# remove non-printable chars form each token
		line = [re_print.sub('', w) for w in line]
		# remove tokens with numbers in them
		line = [word for word in line if word.isalpha()]
		# store as string
		cleaned.append(' '.join(line))
	return cleaned

# save a list of clean sentences to file
def save_clean_sentences(sentences, filename):
	# dump(sentences, open(filename, 'wb'))
    file = open(filename, "w")
    sentences = [sen + "\n" for sen in sentences]
    file.writelines(sentences)
	# print('Saved: %s' % filename)

# load English data

doc = load_doc(file_en)
sentences = to_sentences(doc)
sentences = clean_lines(sentences)
save_clean_sentences(sentences, 'english.txt')
# spot check
for i in range(10):
	print(sentences[i])

# load French data
filename = file_es
doc = load_doc(filename)
sentences = to_sentences(doc)
sentences = clean_lines(sentences)
save_clean_sentences(sentences, 'spanish.txt')
# spot check
for i in range(10):
	print(sentences[i])


# 트럭 n개 지나감 순서 변경 x
# 다리의 길이는 w 단위 길이 이며, 단위 시간에 하나의 단위길이만큼 이동 가능.
# 동시에 올라가있는 트럭은 최대 하중인 L보다 작을 것.
# 큐로 풀 수 있는데 배열? 을 두개 만들어야함.
# 1. 입력된 배열
# 2. 다리 길이만한 배열

# 도착하면 0으로 바꾸고 배열에 있는 숫자와 더해서 몇인지 판별 후 하중 아래면 넣는다.
# 그리고 다음 배열로 고고

from collections import deque

N, W, L = map(int, input().split())
# N : 다리를 건너는 트럭 수
# W : 다리 길이
# L : 최대 하중

trucks = deque(list(map(int, input().split())))
bridge = [0]*W

i = 0
time = 0
while trucks:
    bridge[i] = 0
    if (sum(bridge) + trucks[0]) <= L:
        bridge[i] = trucks.popleft()
    i = (i + 1) % W
    time += 1

print(time + W)


#!/usr/bin/env python
from myalgotrade.strategy import sample
from myalgotrade.strategy import Frequency
from myalgotrade.broker import tradeutil

def func_default_param(instrument):
    return {
        'SR': {
            'ma_short': 5,
            'ma_long': 20
        },
        'L': {
            'ma_short': 3,
            'ma_long': 25,
        },
    }[instrument]

def func_param_select(instrument):
    def select_param(results):
        best_sharpe = -100
        for pid, content in results.items():
            result = dict([(kv[0], float(kv[1])) for kv in [p.split(':') for p in content['result'].split(';')]])
            if result['sharpe'] > best_sharpe:
                best_sharpe = result['sharpe']
                best_id = pid
        return results[best_id]['param']

    return select_param

def func_param_generate(instrument):
    def _param_generator_factory():
        for ma_short in range(1, 15, 2):
            for ma_long in range(min(ma_short * 2, 20), 60, 5):
                yield {
                    'ma_short': ma_short,
                    'ma_long': ma_long,
                }

    return _param_generator_factory

ALPHA = {
    'name': 'alpha0',
    'strategy_class': sample.SampleStrategy,
    'frequency': Frequency.MINUTE * 5,
    'train_param': True,
    'train_window': 200,
    'test_window': 150,
    'func_param_generate': func_param_generate,
    'func_param_select': func_param_select,
    'func_default_param': func_default_param,

    'instruments': {
        'SR': {
            'lots': 1,
            'train_param': False,
        },
        'L': {
            'lots': 2,
        }
    }
}

from myalgotrade.util import alpha_runner
import pprint
import cPickle as Pickle
import json
if __name__ == '__main__':
    result = alpha_runner.run_alpha(alpha=ALPHA)
    pprint.pprint(result)


import itertools
import sys
from collections import deque
from heapq import heappush, heappop
from math import sqrt

input = sys.stdin

def bfs():
    while q:
        x, y, cost = q.popleft()
        for dx, dy in (-1, 0), (1, 0), (0, -1), (0, 1):
            nx, ny = x + dx, y + dy
            if nx < 0 or nx >= n or ny < 0 or ny >= m or visited[nx][ny] or board[nx][ny] == 0: continue
            visited[nx][ny] = True
            q.append((nx, ny, cost + 1))
            dist[nx][ny] = dist[x][y] + 1

if __name__ == '__main__':
    n, m = map(int, input.readline().split())
    board = [[int(x) for x in input.readline().split()] for _ in range(n)]
    q = deque()
    visited = [[False] * m for _ in range(n)]
    dist = [[0] * m for _ in range(n)]
    for i in range(n):
        for j in range(m):
            if board[i][j] == 2:
                q.append((i, j, 0))
                visited[i][j] = True

    bfs()
    for i in range(n):
        for j in range(m):
            if board[i][j] == 1 and dist[i][j] == 0:
                print(-1, end=" ")
            elif board[i][j] == 0:
                print(0, end=" ")
            else:
                print(dist[i][j], end=" ")
        print("")


from odoo import api, fields, models

class ResPartner(models.Model):
    _name = 'res.partner'
    _inherit = ['res.partner', 'se.binding']

    @api.model
    def _get_default_index_id(self):
        return self.env['se.index'].search(
            [('model_id.model', '=', 'res.partner')])

    index_id = fields.Many2one(
        'se.index',
        default=_get_default_index_id)


from typing import Awaitable
from aiogram import Router, Bot, types, F
from aiogram.filters import Command
from aiogram.fsm.context import FSMContext
from aiogram.utils.keyboard import ReplyKeyboardBuilder

from utils.texts import TranslationTexts as texts
from tgtypes.db_user import DbUser

router = Router()

def create_default_keyboard():
    kb = ReplyKeyboardBuilder()
    kb.button(text=texts.HELLO_ADD_BOT_BUTTON.value)
    result_kb = kb.as_markup()
    result_kb.resize_keyboard = True
    result_kb.input_field_placeholder = texts.HELLO_HINT.value
    return result_kb

@router.message(Command(commands=["start"]))
async def command_start_handler(
    message: types.Message,
    state: FSMContext,
    bot: Bot,
    user: DbUser
) -> None:
    if not user.db.pm_referer and message.text and message.text.startswith("/start"):
        user.db.pm_referer = message.text[7:]
    kb = create_default_keyboard()
    await message.answer(texts.HELLO.value, reply_markup=kb)
    return


from time import sleep

import tweepy

from config import auth
from get_city_csv import get_city

api = tweepy.API(auth)

try:
    api.verify_credentials()
    print("Authentication OK")
    while True:
        tweet = get_city()
        print(tweet)
        api.update_status(tweet)
        sleep(3600)
except:
    print("Error during authentication")


import os
import shutil
import pwd
import grp
import sys
import errno
import shutil

from config_common import file_utils, utils, cfg_exceptions
from config_common.rhn_log import log_debug
from spacewalk.common.usix import raise_with_tb

class TargetNotFile(Exception): pass
class DuplicateDeployment(Exception): pass
class FailedRollback(Exception): pass

try:
    from selinux import lsetfilecon
except:
    def lsetfilecon(temp_file_path, sectx):
        # Do nothing RHEL 4
        return 0

BACKUP_PREFIX = '/var/lib/rhncfg/backups'
BACKUP_EXTENSION = '.rhn-cfg-backup'

class DeployTransaction:

    def __init__(self, transaction_root=None, auto_rollback=0):
        # rollback transaction immediately upon failure?
        self.auto_rollback = auto_rollback
        # prepend all given paths
        self.transaction_root = transaction_root

        self.files = []
        self.dirs  = []
        self.symlinks = []
        self.new_dirs = []
        self.backup_by_path = {}
        self.newtemp_by_path = {}
        self.changed_dir_info = {}

        self.deployment_cb = None

    def _generate_backup_path(self, path):
        return "%s%s%s" % (BACKUP_PREFIX, path, BACKUP_EXTENSION)

    def _rename_to_backup(self, path):
        """renames a file to it's new backup name"""
        # ensure we haven't attempted to back this file up before
        # (protect against odd logic coming from the server)
        if path in self.backup_by_path:
            raise DuplicateDeployment("Error: attempted to backup %s twice" % path)

        new_path = None

        if os.path.exists(path):
            # race
            if os.path.isfile(path) or os.path.islink(path):
                new_path = self._generate_backup_path(path)
                log_debug(6, "renaming %s to backup %s ..." % (path, new_path))
                # os.renames will fail if the path and the new_path are on different partitions
                # need to make sure to handle it if we catch a 'OSError: [Errno 18] Invalid cross-device link'
                try:
                    log_debug(9, "trying to use os.renames")
                    oumask = os.umask(int('022', 8))
                    os.renames(path, new_path)
                    os.umask(oumask)
                except OSError:
                    e = sys.exc_info()[1]
                    if e.errno == 18:
                        log_debug(9, "os.renames failed, using shutil functions")
                        path_dir, path_file = os.path.split(path)
                        new_path_dir, new_path_file = os.path.split(new_path)
                        if os.path.isdir(new_path_dir):
                            if os.path.islink(path):
                                log_debug(9, "copying symlink %s to %s"% (path,new_path_dir))
                                linkto = os.readlink(path)
                                if os.path.lexists(new_path):
                                    log_debug(9, "backup %s exists, removing it"% (new_path))
                                    os.unlink(new_path)
                                os.symlink(linkto,new_path)
                            else:
                                log_debug(9, "backup directory %s exists, copying %s to it" % (new_path_dir, new_path_file))
                                if os.path.lexists(new_path):
                                    log_debug(9, "backup %s exists, removing it"% (new_path))
                                    os.unlink(new_path)
                                shutil.copy(path, new_path)
                        else:
                            log_debug(9, "backup directory does not exist, creating the tree now")
                            shutil.copytree(path_dir, new_path_dir, symlinks=0)
                            shutil.copy(path, new_path)
                    else:
                        raise
                self.backup_by_path[path] = new_path
                log_debug(9, "backed up to %s" % new_path)
            else:
                raise TargetNotFile("Error: %s is not a valid file, cannot create backup copy" % path)
        return new_path

    def deploy_callback(self, cb):
        self.deployment_cb = cb

    def _chown_chmod_chcon(self, temp_file_path, dest_path, file_info, strict_ownership=1):
        if file_info['filetype'] != 'symlink':
            uid = file_info.get('uid')
            if uid is None:
                if 'username' in file_info:
                    # determine uid

                    try:
                        user_record = pwd.getpwnam(file_info['username'])
                        uid = user_record[2]
                    except Exception:
                        e = sys.exc_info()[1]
                        #Check if username is an int
                        try:
                            uid = int(file_info['username'])
                        except ValueError:
                            raise_with_tb(cfg_exceptions.UserNotFound(file_info['username']), sys.exc_info()[2])
                else:
                    #default to root (3.2 sats)
                    uid = 0

            gid = file_info.get('gid')
            if gid is None:
                if 'groupname' in file_info:
                    # determine gid
                    try:
                        group_record = grp.getgrnam(file_info['groupname'])
                        gid = group_record[2]
                    except Exception:
                        e = sys.exc_info()[1]
                        try:
                            gid = int(file_info['groupname'])
                        except ValueError:
                            raise_with_tb(cfg_exceptions.GroupNotFound(file_info['groupname']), sys.exc_info()[2])

                else:
                    #default to root (3.2 sats)
                    gid = 0

        try:
            if file_info['filetype'] != 'symlink':
                os.chown(temp_file_path, uid, gid)

                mode = '600'
                if 'filemode' in file_info:
                    if file_info['filemode'] is "":
                        mode='000'
                    else:
                        mode = file_info['filemode']

                mode = int(str(mode), 8)
                os.chmod(temp_file_path, mode)

            if 'selinux_ctx' in file_info:
                sectx = file_info.get('selinux_ctx')
                if sectx is not None and sectx is not "":
                    log_debug(1, "selinux context: " + sectx);
                    try:
                        if lsetfilecon(temp_file_path, sectx) < 0:
                            raise Exception("failed to set selinux context on %s" % dest_path)
                    except OSError:
                        e = sys.exc_info()[1]
                        raise_with_tb(Exception("failed to set selinux context on %s" % dest_path, e), sys.exc_info()[2])

        except OSError:
            e = sys.exc_info()[1]
            if e.errno == errno.EPERM and not strict_ownership:
                sys.stderr.write("cannonical file ownership and permissions lost on %s\n" % dest_path)
            else:
                raise

    def _normalize_path_to_root(self, path):
        if self.transaction_root:
            path = utils.normalize_path(self.transaction_root + os.sep + path)
        return path

    def add_preprocessed(self, dest_path, processed_file_path, file_info, dirs_created, strict_ownership=1):
        """preprocess the file if needed, and add the entry to the correct list"""
        dest_path = self._normalize_path_to_root(dest_path)
        log_debug(3, "preprocessing entry")

        # If we get any dirs that were created by mkdir_p, add them here
        if dirs_created:
            self.new_dirs.extend(dirs_created)

        # If the file is a directory, don't do all the file related work
        # Older servers will not return directories; if filetype is missing,
        # assume file
        if file_info.get('filetype') == 'directory':
            self.dirs.append(file_info)
        else:
            if "dest_path" in self.newtemp_by_path:
                raise DuplicateDeployment("Error:  %s already added to transaction" % dest_path)
            self.newtemp_by_path[dest_path] = processed_file_path
            self._chown_chmod_chcon(processed_file_path, dest_path, file_info, strict_ownership=strict_ownership)

    def add(self, file_info):
        """add a file to the deploy transaction"""
        for k in file_utils.FileProcessor.file_struct_fields:
            if k not in file_info:
                raise Exception("needed key %s mising from file structure" % k)

        file_info['path'] = self._normalize_path_to_root(file_info['path'])

        # Older servers will not return directories; if filetype is missing,
        # assume file
        if file_info.get('filetype') == 'directory':
            self.dirs.append(file_info)
        elif file_info.get('filetype') == 'symlink':
            self.files.append(file_info)
        else:
            self.files.append(file_info)

    def rollback(self):
        """revert the transaction"""
        log_debug(3, "rolling back")

        # restore old file from backup asap
        for path in self.backup_by_path.keys():
            log_debug(6, "restoring %s from %s ..." % (path, self.backup_by_path[path]))
            # os.rename will fail if the backup file and the old file are on different partitions
            # need to make sure to handle it if we catch a 'OSError: [Errno 18] Invalid cross-device link'
            try:
                os.rename(self.backup_by_path[path], path)
            except OSError:
                e = sys.exc_info()[1]
                if e.errno == 18:
                    log_debug(9, "os.rename failed, using shutil.copy")
                    shutil.copy(self.backup_by_path[path], path)
                else:
                    raise
            log_debug(9, "%s restored" % path)

        # remove the temp files that we created
        for tmp_file_path in self.newtemp_by_path.values():
            log_debug(6, "removing tmp file %s ..." % tmp_file_path)
            os.unlink(tmp_file_path)
            log_debug(9, "tmp file removed")

        #revert the owner/perms of any directories that we changed
        for d, val in self.changed_dir_info.items():
            log_debug(6, "reverting owner and perms of %s" % d)
            self._chown_chmod_chcon(d, d, val)
            log_debug(9, "directory reverted")

        #remove any directories created by either mkdir_p or in the deploy
        self.new_dirs.reverse()
        for i in range(len(self.new_dirs)):
            remove_dir = self.new_dirs[i]
            log_debug(6, "removing directory %s that was created during transaction ..." % remove_dir)
            if os.path.islink(remove_dir) == True:
                os.remove(remove_dir)
            else:
                os.rmdir(remove_dir)
            log_debug(9, "directory removed")

        log_debug(3, "rollback successful")

    def deploy(self):
        """attempt deployment; will rollback if auto_rollback is set"""
        fp = file_utils.FileProcessor()

        log_debug(3, "deploying transaction")

        for dep_file in self.files:
            if dep_file['filetype'] == 'symlink':
                self.symlinks.append(dep_file)

        # 0. handle any dirs we need to create first
        #    a) if the dir exists, then just change the mode and owners,
        #       else create it and then make sure the mode and owners are correct.
        #    b) if there are files, then continue
        # 1. write new version (tmp)
        #    a)  if anything breaks, remove all tmp versions and error out
        # 2. rename old version to backup
        #    a)  if anything breaks, rename all backed up files to original name,
        #        then do 1-a.
        # 3. rename tmp to target name
        #    a)  if anything breaks, remove all deployed files, then do 2-a.
        #
        # (yes, this leaves the backup version on disk...)

        try:

            # 0.
            if self.dirs:
                for directory in self.dirs:
                    dirname = self._normalize_path_to_root(directory['path'])
                    dirmode = directory['filemode']
                    if os.path.isfile(dirname):
                        raise cfg_exceptions.DirectoryEntryIsFile(dirname)
                    if os.path.isdir(dirname):
                        s = os.stat(dirname)
                        entry = { 'filemode': "%o" % (s[0] & int('07777', 8)),
                                  'uid': s[4],
                                  'gid': s[5],
                                  'filetype': 'directory',
                                }
                        self.changed_dir_info[dirname] = entry
                        log_debug(3, "directory found, chowning and chmoding to %s as needed: %s" % (dirmode, dirname))
                        self._chown_chmod_chcon(dirname, dirname, directory)
                    else:
                        log_debug(3, "directory not found, creating: %s" % dirname)
                        dirs_created = utils.mkdir_p(dirname, None, self.symlinks, self.files)
                        self.new_dirs.extend(dirs_created)
                        self._chown_chmod_chcon(dirname, dirname, directory)
                    if self.deployment_cb:
                        self.deployment_cb(dirname)

            log_debug(6, "changed_dir_info: %s" % self.changed_dir_info)
            log_debug(4, "new_dirs: ", self.new_dirs)

            if not self.newtemp_by_path and not self.files:
                log_debug(4, "directory creation complete, no files found to create")
                return
            else:
                log_debug(4, "done with directory creation, moving on to files")

            # 1.
            for dep_file in self.files:
                path = dep_file['path']

                log_debug(6, "writing new version of %s to tmp file ..." % path)
                # make any directories needed...
                #
                # TODO:  it'd be nice if this had a hook for letting me know
                # which ones are created... then i could clean created
                # dirs on rollback
                (directory, filename) = os.path.split(path)
                if os.path.isdir(path) and not os.path.islink(path):
                    raise cfg_exceptions.FileEntryIsDirectory(path)
                if not os.path.exists(directory):# and os.path.isdir(directory):
                    log_debug(7, "creating directories for %s ..." % directory)
                    dirs_created = utils.mkdir_p(directory, None, self.symlinks, self.files)
                    self.new_dirs.extend(dirs_created)
                    log_debug(7, "directories created and added to list for rollback")

                # write the new contents to a tmp file, and store the path of the
                # new tmp file by it's eventual target path
                self.newtemp_by_path[path], temp_new_dirs = fp.process(dep_file, os.path.sep)
                self.new_dirs.extend(temp_new_dirs or [])

                # properly chown and chmod it
                self._chown_chmod_chcon(self.newtemp_by_path[path], path, dep_file)
                log_debug(9, "tempfile written:  %s" % self.newtemp_by_path[path])

            #paths = map(lambda x: x['path'], self.files)
            paths = list(self.newtemp_by_path.keys())

            # 2.
            for path in paths:
                if os.path.isdir(path) and not os.path.islink(path):
                    raise cfg_exceptions.FileEntryIsDirectory(path)
                else:
                    self._rename_to_backup(path)
                    if path in self.backup_by_path:
                        log_debug(9, "backup file %s written" % self.backup_by_path[path])

            # 3.
            paths.sort(key = lambda s: s.count(os.path.sep))
            for path in paths:
                if self.deployment_cb:
                    self.deployment_cb(path)
                log_debug(6, "deploying %s ..." % path)
                os.rename(self.newtemp_by_path[path], path)
                # race
                del self.newtemp_by_path[path]
                log_debug(9, "new version of %s deployed" % path)

            log_debug(3, "deploy transaction successful")

        except Exception:
            #log_debug(1, traceback.format_exception_only(SyntaxError, e))
            #traceback.print_exc()
            if self.auto_rollback:
                self.rollback()
            raise


import heapq

class Solution:
    def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start_node: int, end_node: int) -> float:
        res = {}

        # Build the adjMap
        adjMap = {node: [] for node in range(n)}
        for idx, edge in enumerate(edges):
            src, dst = edge

            adjMap[src].append((dst, succProb[idx]))
            adjMap[dst].append((src, succProb[idx]))

        # build heap
        maxHeap = [(-1, start_node)]

        while maxHeap:
            currProb, currNode = heapq.heappop(maxHeap)
            if currNode in res:
                continue
            if end_node in res:
                break

            res[currNode] = currProb
            for nextNode, nextProb in adjMap[currNode]:
                heapq.heappush(maxHeap, (currProb * nextProb, nextNode))

        if end_node in res:
            return -1 * res[end_node]
        return 0


from __future__ import division
import ipywidgets as ipw
import ase
from ase.units import *

def get_start_widget(appbase, jupbase):

    def on_drop_changed(c):
        global factor
        lu, ru = drop.value.split(" <=> ")
        left.description = lu
        right.description = ru
        factor = eval("(%s) / (%s)"%(lu, ru))
        on_left_changed(None)

    def on_left_changed(c):
        right.value = left.value * factor

    def on_right_changed(c):
        left.value = right.value / factor

    left = ipw.FloatText(value=1.0)
    left.observe(on_left_changed, names="value")
    right = ipw.FloatText()
    right.observe(on_right_changed, names="value")

    options = ['Hartree <=> eV', 'Hartree <=> kcal/mol', 'Bohr <=> Angstrom']
    drop = ipw.Dropdown(options=options)
    drop.observe(on_drop_changed)

    on_drop_changed(None)

    return ipw.HBox([drop, left, right])

#EOF


from pprint import pprint

# Dummy LED class
class LED:
    def __init__(self):
        self.brightness = 0

    def __repr__(self):
        return str(self.brightness)

class LEDDisplay:
    def __init__(self, led_array=None):
        self.led_array = led_array if led_array is not None else [[LED() for _ in range(0, 16)] for x in range(0, 16)]
        self.size_y = len(self.led_array)
        self.size_x = len(self.led_array[0])
        #   Assertion tests:
        #   Test: array is even both vertically and horizontal
        assert self.size_y % 2 == 0 and self.size_x % 2 == 0
        for y in self.led_array:
            for led in y:
                assert isinstance(led, LED)

    def __repr__(self):
        pout = ""
        for y in range(0, self.size_y - 1):
            for x in range(0, self.size_x - 1):
                pout += f"{str(self.led_array[y][x])}  "
            pout += '\n'
        return pout

    @staticmethod
    def _swap_point_x(point_a: tuple, point_b: tuple) -> tuple:
        return (point_b[0], point_a[1]), (point_a[0], point_b[1])

    def draw_line(self, point_a: tuple, point_b: tuple, brightness: int = 1):
        """
        Draws a solid line using Bresenham's algorithm

        :param point_a: line starting point
        :param point_b: line end point
        :param brightness: brightness to set activated leds to
        :return:
        """
        if point_a[0] > point_b[0]:
            point_a, point_b = self._swap_point_x(point_a, point_b)

        dx = point_b[0] - point_a[0]
        dy = point_b[1] - point_a[1]
        slope = dy / dx if dx != 0 else None
        print(slope)
        if slope is None:
            for y in range(point_a[1], point_b[1]):
                x = point_a[0]
                self.led_array[y][x].brightness = brightness
        elif slope == 1:
            for y in range(point_a[1], point_b[1]):
                self.led_array[y][y].brightness = brightness
        elif slope > 1:
            for y in range(point_a[1], point_b[1] + 1):
                x = round(y / slope)
                self.led_array[y][x].brightness = brightness
        elif 0 < slope < 1:
            for x in range(point_a[0], point_b[0] + 1):
                self.led_array[round(x * slope)][x].brightness = brightness
        elif slope == -1:
            for y in range(point_b[1], point_a[1]):
                x = round(y / slope) + point_b[0] - 1
                self.led_array[y][x].brightness = brightness
        elif -1 < slope < 0:
            for x in range(point_a[0], point_b[0] + 1):
                y = round(x * slope)
                self.led_array[y][x].brightness = brightness

    def draw_smile(self, brightness: int = 1):
        #   Eyes
        for y in range(int((3 / 16) * self.size_y), int((9 / 16) * self.size_y) + 1):
            x = int((5 / 16) * self.size_x)
            self.led_array[y][x - 1].brightness = brightness
            self.get_led_mirror(y, x).brightness = brightness

    def invert(self):
        for y in range(0, self.size_y):
            for x in range(0, self.size_x):
                self.led_array[y][x].brightness = 1 - self.led_array[y][x].brightness

    def get_led_mirror(self, y_index: int, x_index: int):
        return self.led_array[y_index][len(self.led_array) - 1 - x_index]

    def reset(self):
        for y in range(0, self.size_y):
            for x in range(0, self.size_x):
                self.led_array[y][x].brightness = 0

    def fill(self, brightness: int = 1):
        for y in range(0, self.size_y):
            for x in range(0, self.size_x):
                self.led_array[y][x].brightness = brightness

def tests():
    # 16x16 array

    a = LEDDisplay()
    #   Test cases
    #   Slope of 1
    print("Slope of 1:")
    a.draw_line((0, 0), (5, 5))
    print(a)
    a.reset()
    #   Slope of -1
    print("Slope of -1:")
    a.draw_line((1, 5), (6, 0))
    print(a)
    a.reset()
    #   0 < slope < 1
    print("0 < Slope < 1: ")
    a.draw_line((0, 0), (5, 3))
    print(a)
    a.reset()
    #   -1 < slope < 0
    print("-1 < Slope < 0: ")
    a.draw_line((1, 5), (6, 1))
    print(a)
    a.reset()

if __name__ == "__main__":
    tests()


import pygame
import sys

from map import Map
from settings import AMOUNT_OF_ROWS, AMOUNT_OF_COLUMNS, BACKGROUND_COLOR, SCREEN_WIDTH, SCREEN_HEIGHT, FPS

clock = pygame.time.Clock()
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))

game_map = Map(AMOUNT_OF_ROWS, AMOUNT_OF_COLUMNS)

game_map.draw(screen)

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

    screen.fill(BACKGROUND_COLOR)

    game_map.update()
    game_map.draw(screen)

    clock.tick(FPS)


from datetime import datetime
import pandas as pd
from nltk.sentiment.vader import SentimentIntensityAnalyzer as SIA
import re
import matplotlib.pyplot as plt
import seaborn as sns

import nltk
nltk.download('vader_lexicon')

def date_time(df):
    df['tweet_date'] = df['tweet_dt'].apply(lambda x: datetime.strptime(x,'%Y-%m-%d'))
    df['dt'] = pd.to_datetime(df['tweet_date'])
    return df

def sia_analysis(df):

    sid = SIA()
    df['sentiments'] = df['body'].apply(lambda x: sid.polarity_scores(' '.join(re.findall(r'\w+',x.lower()))))
    df['Positive Sentiment'] = df['sentiments'].apply(lambda x: x['pos']+1*(10**-6))
    df['Neutral Sentiment']= df['sentiments'].apply(lambda x: x['neu']+1*(10**-6))
    df['Negative Sentiment']= df['sentiments'].apply(lambda x: x['neg']+1*(10**-6))

    df.drop(columns=['sentiments'],inplace=True)

    return df

def plot_sentiments(df, title):

    plt.figure(figsize=(20,10))
    plt.title('Distribution Of Sentiments Across Our Tweets about '+ title,fontsize=19,fontweight='bold')
    sns.kdeplot(df['Negative Sentiment'],bw_method=0.1,label = 'Negative')
    sns.kdeplot(df['Positive Sentiment'],bw_method=0.1,label = 'Positive')
    sns.kdeplot(df['Neutral Sentiment'],bw_method=0.1,label = 'Neutral')
    plt.xlabel('Sentiment scores')
    plt.legend()
    plt.show()

def create_df_sent(df):

    df_original = df.copy()
    # Saving the maximum values between the three sentiments and their respective class
    df_sentiment = pd.DataFrame()
    df_sentiment['Max_SentimentCol'] = df[['Negative Sentiment','Positive Sentiment','Neutral Sentiment']].idxmax(axis=1)
    df_sentiment['Max_SentimentValue'] = df[['Negative Sentiment','Positive Sentiment','Neutral Sentiment']].max(axis=1)
    # df_sentiment = df_sentiment.drop(['Negative Sentiment','Positive Sentiment','Neutral Sentiment'], axis=1)

    # Union of new dataframe and original one
    # df_new = df_sentiment.join(df_original)
    return df_sentiment

#TRASFORMANDO IN DATE LE STRINGHE PER POTER RAGGRUPARE LA MEDIA DEI VALORI MASSIMI DI SENTIMENT SCORE PER CATEGORIA (POS,NEG,NEUTRAL) E MESE
def plot_sent_distribution(df_new, title = 'no-title', no_plot = True):

    list_YM = [i.split(" ")[0][:-3] for i in  list(df_new['tweet_dt'])]
    list_Year = [i.split(" ")[0][0:4] for i in  list(df_new['tweet_dt'])]
    list_Month = [i.split(" ")[0][5:7] for i in  list(df_new['tweet_dt'])]

    df_new['YM'] = list_YM
    df_new['Year'] = list_Year
    df_new['Month'] = list_Month

    #create a monthly dataframe
    df_mean = df_new.groupby(['Max_SentimentCol', 'YM', 'Year', 'Month']).mean()
    df_mean = df_mean[['Max_SentimentValue']].reset_index()
    df_mean.sort_values(by='YM',inplace=True)

    if not no_plot:
        sns.set(rc={'figure.figsize':(40,10)})
        ax = sns.lineplot(data=df_mean, x = 'YM', y='Max_SentimentValue',hue='Max_SentimentCol',palette='viridis',legend='full',lw=3)
        xticks = ax.xaxis.get_major_ticks()
        for i in range(len(xticks)):
            if i%2==1:
                xticks[i].set_visible(False)

        plt.legend(bbox_to_anchor=(1, 1))
        plt.title('Distribution of the sentiment score over time by ' + title)
        plt.ylabel('Mean Sentiment Score')
        plt.xlabel('Year-Month')
        plt.xticks(rotation=45)
        plt.show()

    return


import os
import torch
import torch.nn as nn
import torch.optim
import torch.utils.data
import torchvision
import torchvision.transforms as transforms
import torchvision.datasets as datasets

from models.alexnet import our_alexnet

from util.utils import LogWriter, CIFAR10_MEAN, CIFAR10_STD
import socket
import numpy as np
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt

def log_hparam_and_backup_code(args, file_path):
    file_name = os.path.basename(file_path)
    logfile = LogWriter(os.path.join(args.result_path, "hparam.txt"))
    for k, v in args.__dict__.items():
        logfile.cprint(f"{k} : {v}")
    logfile.cprint("Numpy: {}".format(np.__version__))
    logfile.cprint("Pytorch: {}".format(torch.__version__))
    logfile.cprint("torchvision: {}".format(torchvision.__version__))
    logfile.cprint("Cuda: {}".format(torch.version.cuda))
    logfile.cprint("hostname: {}".format(socket.gethostname()))
    logfile.close()

    os.system(f'cp {file_path} {args.result_path}/{file_name}.backup')

def prepare_model(args):
    if args.arch == "our_alexnet":
        model = our_alexnet(dataset=args.dataset)
    else:
        raise Exception("Model not implemented")
    model.to(args.device)
    print(str(model))

    # optionally resume from a checkpoint
    if args.resume:
        if os.path.isfile(args.resume):
            print("=> loading checkpoint '{}'".format(args.resume))
            checkpoint = torch.load(args.resume, map_location=args.device)
            if 'best_prec1' in checkpoint:
                best_prec1 = checkpoint['best_prec1']
                print("best acc", best_prec1)
            if not ('state_dict' in checkpoint):
                sd = checkpoint
            else:
                sd = checkpoint['state_dict']
            # load with models trained on a single gpu or multiple gpus
            if 'module.' in list(sd.keys())[0]:
                sd = {k[len('module.'):]: v for k, v in sd.items()}
            model.load_state_dict(sd)
            print("=> loaded checkpoint '{}'"
                  .format(args.resume))
        else:
            print("=> no checkpoint found at '{}'".format(args.resume))

    return model

def prepare_dataset(args):
    if args.dataset == "cifar10":
        normalize = transforms.Normalize(mean=CIFAR10_MEAN,
                                         std=CIFAR10_STD)

        train_transform_list = []

        if args.horizontal_flip:
            train_transform_list.append(transforms.RandomHorizontalFlip())
        if args.random_crop:
            train_transform_list.append(transforms.RandomCrop(32, 4))

        train_transform_list.append(transforms.ToTensor())
        train_transform_list.append(normalize)
        print("train transform list: ", train_transform_list)
        train_transform = transforms.Compose(train_transform_list)

        train_set = datasets.CIFAR10(root='./datasets', train=True, transform=train_transform, download=True)
        val_set = datasets.CIFAR10(root='./datasets', train=False, download=True, transform=transforms.Compose([
                transforms.ToTensor(),
                normalize,
            ]))

    else:
        raise Exception("dataset [%s] not implemented" % args.dataset)

    train_loader = torch.utils.data.DataLoader(
        train_set,
        batch_size=args.batch_size, shuffle=True,
        num_workers=args.workers)

    val_loader = torch.utils.data.DataLoader(
        val_set,
        batch_size=args.batch_size, shuffle=False,
        num_workers=args.workers)
    return train_loader, val_loader

def save_checkpoint(state, filename='checkpoint.pth.tar'):
    """
    Save the training model
    """
    torch.save(state, filename)

class AverageMeter(object):
    """Computes and stores the average and current value"""
    def __init__(self):
        self.reset()

    def reset(self):
        self.val = 0
        self.avg = 0
        self.sum = 0
        self.count = 0

    def update(self, val, n=1):
        self.val = val
        self.sum += val * n
        self.count += n
        self.avg = self.sum / self.count

def accuracy(output, target, topk=(1,)):
    """Computes the precision@k for the specified values of k"""
    maxk = max(topk)
    batch_size = target.size(0)

    _, pred = output.topk(maxk, 1, True, True)
    pred = pred.t()
    correct = pred.eq(target.view(1, -1).expand_as(pred))

    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0)
        res.append(correct_k.mul_(100.0 / batch_size))
    return res


from PyQt5.QtWidgets import (
    QWidget, QGridLayout, QHBoxLayout, QVBoxLayout,
    QPushButton, QLabel, QLineEdit, QCheckBox, QSizePolicy
)
from PyQt5.QtCore import QThread, pyqtSignal
import xml.etree.ElementTree as ET
from time import sleep
import os
from TraditionalParamTuning.myPackage.func import mkdir
from TraditionalParamTuning.myPackage.set_btn_enable import set_btn_enable

class PushAndSaveBlock(QWidget):
    alert_info_signal = pyqtSignal(str, str)
    get_and_set_param_value_signal = pyqtSignal()
    capture_signal = pyqtSignal(str)
    push_to_camera_signal = pyqtSignal(bool, str)

    def __init__(self):
        super().__init__()
        self.setup_UI()
        self.setup_controller()

    def setup_UI(self):
        VLayout = QVBoxLayout(self)

        title_wraper = QHBoxLayout()
        label_title = QLabel("Push and Save")
        label_title.setStyleSheet("background-color:rgb(74, 115, 140);")
        # 設定水平大小策略為 Expanding
        label_title.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        # label_title.setStyleSheet("background-color:rgb(72, 72, 72);")
        title_wraper.addWidget(label_title)
        VLayout.addLayout(title_wraper)

        gridLayout = QGridLayout()

        label = QLabel("資料夾名稱")
        label.setToolTip("要存入的資料夾名稱，如果不填，預設會存在FIH-tool資料夾裡\n此設定只與下方的拍照按鈕功能有關")
        gridLayout.addWidget(label, 0, 0)

        self.lineEdits_dir_name = QLineEdit()
        gridLayout.addWidget(self.lineEdits_dir_name, 0, 1)

        label = QLabel("圖片檔名")
        label.setToolTip("要存入的圖片檔名(不須加上.jpg)，如果不填，預設會存成.jpg\n此設定只與下方的拍照按鈕功能有關")
        gridLayout.addWidget(label, 1, 0)

        self.lineEdits_img_name = QLineEdit()
        gridLayout.addWidget(self.lineEdits_img_name, 1, 1)

        VLayout.addLayout(gridLayout)

        self.btn_set_to_xml = QPushButton("寫入")
        self.btn_set_to_xml.setToolTip("將UI介面上的參數值寫入到project裡")
        VLayout.addWidget(self.btn_set_to_xml)

        self.btn_push_phone = QPushButton("推到手機")
        self.btn_push_phone.setToolTip("將project推到手機")
        VLayout.addWidget(self.btn_push_phone)

        self.btn_capture = QPushButton("拍照")
        self.btn_capture.setToolTip("讓手機拍照，並且存成上面設定的 資料夾名稱/圖片檔名")
        VLayout.addWidget(self.btn_capture)

        self.btn_push_phone_capture = QPushButton("寫入 + 推到手機 + 拍照")
        self.btn_push_phone_capture.setToolTip("將上面三種功能結合")
        VLayout.addWidget(self.btn_push_phone_capture)

        self.btn_input_param = QPushButton("使用文本框輸入參數")
        self.btn_input_param.setToolTip("可將csv的參數直接複製到此，輸入後點寫入按鈕，即可寫入到project")
        VLayout.addWidget(self.btn_input_param)

    def setup_controller(self):
        self.btn_set_to_xml.clicked.connect(self.get_and_set_param_value_signal.emit)
        self.btn_push_phone.clicked.connect(lambda: self.push_phone(is_capture=False, is_set_to_xml=False))
        self.btn_push_phone_capture.clicked.connect(lambda: self.push_phone(is_capture=True, is_set_to_xml=True))
        self.btn_capture.clicked.connect(self.do_capture)

    def get_saved_path(self):
        dir_name = self.lineEdits_dir_name.text()
        img_name = self.lineEdits_img_name.text()

        if dir_name=="": dir_name="."
        mkdir(dir_name)

        return "{}/{}".format(dir_name, img_name)

    def push_phone(self, is_capture, is_set_to_xml):
        saved_path = "./"
        if is_capture:
            saved_path = self.get_saved_path()
            if os.path.exists(saved_path+".jpg"):
                self.alert_info_signal.emit("檔名重複", "檔名\n"+saved_path+".jpg\n已存在，請重新命名")
                return
        if is_set_to_xml:
            self.get_and_set_param_value_signal.emit()

        self.push_to_camera_signal.emit(is_capture, saved_path)

    def set_all_enable(self, b):
        set_btn_enable(self.btn_set_to_xml, b)
        set_btn_enable(self.btn_capture, b)
        set_btn_enable(self.btn_push_phone, b)
        set_btn_enable(self.btn_push_phone_capture, b)
        set_btn_enable(self.btn_input_param, b)

    def do_capture(self):
        print("PushAndSaveBlock do_capture")
        saved_path = self.get_saved_path()
        if os.path.exists(saved_path+".jpg"):
            self.alert_info_signal.emit("檔名重複", "檔名\n"+saved_path+".jpg\n已存在，請重新命名")
            return
        self.capture_signal.emit(saved_path)