"""
Console output colorizer. pyreadline required( on windows )
"""
__author__ = "Jussi Toivola"
__license__ = "MIT License"

from SCons.Platform import win32, posix
import os
import subprocess as sp
import sys

#: Pyreadline console
CONSOLE = None
try:
    if os.name == "nt":
        import pyreadline
        CONSOLE = pyreadline.GetOutputFile()
except ImportError: #IGNORE:W0704
    pass

#: Color constants. TODO: Get from user settings.
class Colors( object ):
    WARNING = 14
    ERROR = 12
    NORMAL = 7
    COMMENT = 10

if sys.platform == "linux2":
    Colors.WARNING = 33
    Colors.ERROR = 31
    Colors.NORMAL = 0
    Colors.COMMENT = 32

#: Get initial color of the console
if CONSOLE is not None:
    Colors.NORMAL = CONSOLE.attr

#: Lines containing these strings are drawn in Colors.ERROR color
KEYWORD_ERRORS = [ __x.lower() for __x in [ "error:", " error ", "failed", " undefined ", "does not match", "illegal",
               "was expected", "The process cannot access",
               "No such file or directory", "*** ", "cannot be opened",
               "Cannot convert", "needed by", "explicit dependency" ] ]
KEYWORD_ERRORS.sort()

#: Excluded errors
KEYWORD_ERRORS_EXCLUDE = [ "error.c", "error.cpp", "error.h"  ]

#: Drawn with Colors.COMMENT
KEYWORD_COMMENT = [ __x.lower() for __x in [ "scons:", "note:", "copy(", "install file"] ]

#: Excluded comments
KEYWORD_COMMENT_EXCLUDE = []

#: Warning keywords. Drawn with Colors.WARNING
KEYWORD_WARNINGS = ["warning ", "warning:"]

#: Excluded warnings
KEYWORD_WARNINGS_EXCLUDE = ["-warning"]

#: Map colors to keywords.
KEYWORDMAP = [ ( KEYWORD_WARNINGS, KEYWORD_WARNINGS_EXCLUDE, Colors.WARNING ),
               ( KEYWORD_ERRORS, KEYWORD_ERRORS_EXCLUDE, Colors.ERROR ),
               ( KEYWORD_COMMENT, KEYWORD_COMMENT_EXCLUDE, Colors.COMMENT ) ]

class LineCounts( object ):
    def __init__( self ):
        self.Errors = 0
        self.Warnings = 0
        self.Others = 0
        self.reset()

    def reset( self ):
        self.Errors = 0
        self.Warnings = 0
        self.Others = 0

LINECOUNTS = LineCounts()

#: Original sys.stdout
savedstdout = sys.stdout
savedstderr = sys.stderr

def subsitute_env_vars( line, env ):
    """ Substitutes environment variables in the command line.

    E.g. dir %EPOCROOT% -> dir T:\

    The command line does not seem to do this automatically when launched
    via subprocess.
    """
    for key, value in env.items():
        line = line.replace( "%%%s%%" % key, value )
    return line

def _handle_posix_write(line,color):
    msg = "%02i" % color
    savedstdout.write( "\x1b[%sm" % ( msg ) )
    savedstdout.write( line )

    # Reset
    msg = "%02i" % 0
    savedstdout.write( "\x1b[%sm" % ( msg ) )

def write( line, color ):
    """Write line with color"""
    global CONSOLE

    if os.name == "posix" and sys.__stdout__.isatty():
        return _handle_posix_write( line, color )

    elif CONSOLE is not None:
        try:
            CONSOLE.write_color( line, color )
            CONSOLE.write_color( "", CONSOLE.attr )
            return

        except TypeError:
            # Occurs at least when redirecting data to a file
            # So disable the color support
            CONSOLE = None

    if color in [ Colors.ERROR, Colors.WARNING ]:
        savedstderr.write( line )
    else:
        savedstdout.write( line )

def comment( line ):
    "Util for comments"
    write( line + "\n", Colors.COMMENT )

def error( line ):
    "Util for errors"
    write( line, Colors.ERROR )

class ConsoleBase( object ):
    """Base class for colored console output"""

    def __init__( self ):
        self.savedstdout = sys.stdout
        self.savedstderr = sys.stderr

    def flush( self ):
        self.savedstderr.flush()
        self.savedstdout.flush()

    def read( self ):
        """Read both stdout and stderr and output the data with colors"""
        block = None
        result = ""

        while block != "":
            block = self.savedstdout.read()
            self.write( block )
            result += block

            block = self.savedstderr.read()
            self.write( block )
            result += block

        return result

    def write( self, text ):
        """Colorize each line based on the keywords"""

        lines = text.split( "\n" )

        for i in xrange( len( lines ) ):

            line = lines[i]
            lowcase = line.lower()

            detected = False
            for kws, excludes, color in KEYWORDMAP:
                # Check keywords and exclusion keywords
                if  len( [x for x in kws if x in lowcase] ) > 0 \
                and len( [x for x in excludes if x in lowcase] ) == 0:
                    write( line, color )
                    detected = True
                    break

            # Draw in normal color then
            if not detected:
                write( line, Colors.NORMAL )

            if i < ( len( lines ) - 1 ):
                write( "\n", Colors.NORMAL )
class OutputConsole( ConsoleBase ):
    """Handles spawning external processes and colors the console output.
    """
    def __init__( self ):
        ConsoleBase.__init__( self )

        self.savedspawn = os.spawnve

        sys.stdout = self
        sys.stderr = self

        win32.spawn = self.spawn
        posix.spawnvpe_spawn = self.spawn

    def spawn( self, sh, escape, cmd, args, env ): #IGNORE:W0613
        """
        Replaces SCons.Platform.spawn to colorize output of
        external processes
        """
        #import pdb;pdb.set_trace()
        #.replace( '"', '' )
        #FIXME: the " must be removed but not those with \ before them.
        tmp = []
        for x in args:
            x = x.replace(r'\"', '\???') # lets hope nobody wants to use \???
            x = x.replace(r'"', '')
            x = x.replace(r'\???', '"')
            tmp.append( subsitute_env_vars( x, env ) )
        args = tmp

        startupinfo = None
        if os.name == "nt":
            # Long command support <= 32766 for Windows
            startupinfo = sp.STARTUPINFO()
            startupinfo.dwFlags |= sp.STARTF_USESHOWWINDOW

        stdout = sp.PIPE
        #import pdb;pdb.set_trace()
        if ( os.name == "posix" and args[0] == "wine" ):
            stdout = None

        # We get unicode objects in the environment from somewhere, which makes
        # Popen unhappy. Force the environment to strings.
        # TODO(mika.raento): fix the source of the unicode.
        env = dict([ (k, str(v)) for (k, v) in env.iteritems() ])

        p = sp.Popen( args, bufsize = 1024,
                    stdout = stdout, stderr = sp.STDOUT,
                    startupinfo = startupinfo,
                    shell = False, env = env )
        result = None
        #import pdb;pdb.set_trace()
        if p.stdout is not None:
            while result is None:
                # This is slow on Linux with Wine!!
                line = p.stdout.read()
                self.write( line )
                result = p.poll()
            # Get the last lines
            line = p.stdout.readline()
            self.write( line )

        else:
            result = p.wait()

        return result

del __x


import smbus
import time
from mlx90614 import MLX90614
from Adafruit_BNO055 import BNO055

BNO_ADDR_A = 0x28
IR_ADDR = 0x5B
SLEEPTIME = 0.01
therm = MLX90614(IR_ADDR)
IMU_Nose = BNO055.BNO055(None, BNO_ADDR_A)
bus = smbus.SMBus(1)

def medianFilter(data):
    data.sort
    return data[2]

def filteredData():
    rawTemp = []
    noseX = []
    noseY = []
    noseZ = []
    accel = []
    for x in range(0, 5):
        try:
            rawTemp.append(therm.get_obj_temp_C())
        except IOError:
            rawTemp.append(0)
        try:
            noseOrientation = IMU_Nose.read_euler()
        except IOError:
            noseOrientation = [0, 0, 0]
        noseX.append(noseOrientation[0])
        noseY.append(noseOrientation[1])
        noseZ.append(noseOrientation[2])
        try:
            acceleration = IMU_Nose.read_linear_acceleration()
            accel.append(acceleration[0])
        except IOError:
            accel.append(0)

        time.sleep(SLEEPTIME)
    temp = medianFilter(rawTemp)
    x = medianFilter(noseX)
    y = medianFilter(noseY)
    z = medianFilter(noseZ)
    acc = medianFilter(accel) * 3.281
    return (temp, x, y, z, acc)

if __name__ == '__main__':
    IMU_Nose.begin()
    while True:
        data = filteredData()
        print("%.2f C" % data[0])
        print("%.2f\t" % data[1], "%.2f\t" % data[2], "%.2f\t" % data[3])
        print("%.2f m/s^2" % data[4])
        time.sleep(0.05)


from cozmohttpclient import CozmoHttpClient
import cozmo
import asyncio

class CozmoAlexa:

    def __init__(self):
        self._client = CozmoHttpClient()

    async def run(self, coz_conn:cozmo.conn.CozmoConnection):
        self._robot = await coz_conn.wait_for_robot()
        self._robot.set_robot_volume(1.0)

        await self.sayToAlexa("Alexa")
        await self.sayToAlexa("Open a.i. rivalry")
        await asyncio.sleep(5)
        await self.sayToAlexa("I am better a.i. than you")
        await self.listenToResponse()
        await self._robot.play_anim_trigger(cozmo.anim.Triggers.FailedToRightFromFace).wait_for_completed()

    async def sayToAlexa(self, msg):
        await self._robot.say_text(msg,
                                   use_cozmo_voice=False,
                                   duration_scalar=1.1,
                                   voice_pitch=0).wait_for_completed()

    async def listenToResponse(self):
        # mock waiting time, wait for reaction
        r = self._client.getMessage()
        t = len(r) * 0.1
        print("Wait time ", t)
        await asyncio.sleep(t)

def main():
    ca = CozmoAlexa()
    cozmo.setup_basic_logging()
    cozmo.connect(ca.run)

if __name__ == '__main__':
    main()


from time import sleep
import argparse
import os
import re
import ntpath
import glob
import sys
import fileinput
from shutil import copyfile
import json

def parse_args():
    """Uses argparse to enable user to customize script functionality"""
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('-in_dir', '--input_directory', help='path to directory containing input files')
    parser.add_argument('-in_file', '--input_file_path', help='path to input file')
    parser.add_argument('-out', '--output_directory', default='./', help='directory to which the output directory "/.HaplotypeCaller/" will be written to')
    parser.add_argument('-n', '--num_cores', default='1', help='slurm job submission option')
    parser.add_argument('-cn', default="1", help='number of cores for Cromwell jobs')
    parser.add_argument('-t', '--runtime', default='2-00:00:00', help='slurm job submission option')
    parser.add_argument('-ct', default="3000", help='cromwell run time; please specify as number of minutes')
    parser.add_argument('-p', '--queue', default='long', help='slurm job submission option')
    parser.add_argument('--mem_per_cpu', default='15G', help='slurm job submission option')
    parser.add_argument('-cm', default='5000', help='cromwell cpu memory per core')
    parser.add_argument('--mail_type', default='FAIL', help='slurm job submission option')
    parser.add_argument('--mail_user', default='victor_mao@hms.harvard.edu', help='slurm job submission option')
    parser.add_argument('-cromwell', '--cromwell_path', default='/n/shared_db/singularity/hmsrc-gatk/cromwell-43.jar', help='path to cromwell.jar file')
    parser.add_argument('-r', default='/home/mk446/BiO/Install/GATK-bundle/2.8/b37/human_g1k_v37_decoy.fasta')
    parser.add_argument('-gatk', default='/home/mk446/BiO/Install/GATK4.1.2.0//gatk', help='path to software')
    parser.add_argument('-reference_name', default='b37', help='hg19, b37, etc.')
    parser.add_argument('-picard', default='/home/mk446/BiO/Install/picard-tools-2.5.0/picard.jar')
    parser.add_argument('-intervals', default='/n/data1/hms/dbmi/park/victor/references/Homo_sapiens_assembly19/interval_list.txt')

    return parser.parse_args()

def main():
    args = parse_args()
    clean_arg_paths(args)

    dirname = os.path.dirname(os.path.abspath(__file__))
    overrides = os.path.join(dirname, 'Overrides.config')
    wdl = os.path.join(dirname, 'Germline_workflow.wdl')
    json = os.path.join(dirname, 'Germline_workflow.json')

    input_files = return_input_files(args, 'bam') if args.input_directory is not None else [args.input_file_path]
    input_files = sort_by_size(input_files)

    for input_file in input_files:
        if not os.path.isfile(input_file): continue
        sample = os.path.basename(input_file).split('.')[0]
        sample_dir = os.path.join(args.output_directory,'.HaplotypeCaller/' + sample + '/')
        os.makedirs(sample_dir, exist_ok=True)

        input_json, input_config, input_wdl = generate_cromwell_inputs(args, input_file, json, wdl, overrides)
        slurm_command = return_slurm_command(args)
        output_file_name = gen_output_file_name(args, input_file)
        primary_command = return_primary_command(args, output_file_name, input_file, input_json, input_config, input_wdl)

        sh_file_name = gen_sh_file_name(args, output_file_name)
        write_out(args, slurm_command, primary_command, sh_file_name)

        sample_name = ntpath.basename(sh_file_name).split('.')[0] + '.vcf'
        sample_dir = os.path.join(ntpath.basename(sh_file_name).split('.')[0], sample_name)
        path_to_vcf = os.path.join(ntpath.dirname(ntpath.dirname(ntpath.dirname(sh_file_name))), sample_dir)
        #print(path_to_vcf)
        if not os.path.isfile(path_to_vcf):
            submit_job(sh_file_name)

def clean_arg_paths(args):
    """Modifies all user-inputted directory paths such that they end with a '/'"""
    d = vars(args)
    for arg in d.keys():
        if 'input_directory' in arg and d[arg]=='./': d[arg] = os.getcwd()
        if 'output_directory' in arg and d[arg]=='./': d[arg] = os.getcwd()
        if 'directory' in arg and d[arg] is not None and d[arg][-1] != '/': d[arg] += '/'

    output_dir = re.sub(" ", "", d["output_directory"])
    if output_dir[len(output_dir) - 1] is not "/":
        d["output_directory"] = output_dir + "/"

def return_input_files(args, ext):
    input_bams = [os.path.realpath(file) for file in glob.glob(args.input_directory + '*.' + ext)]
    return input_bams

def sort_by_size(input_files):
    for i in range(len(input_files)):
        input_files[i] = (input_files[i], os.path.getsize(input_files[i]))
    input_files.sort(key=lambda filename: filename[1])
    for i in range(len(input_files)):
        input_files[i] = input_files[i][0]
    return input_files

def generate_cromwell_inputs(args, input_file, json_file, wdl, overrides):
    dir = args.output_directory + '.HaplotypeCaller/' + '.' + os.path.basename(input_file).split('.')[0] + '/'
    os.makedirs(dir, exist_ok=True)

    bam_dir = os.path.dirname(input_file)
    bam_sample = os.path.basename(input_file)

    bai_suffix = '.bai'
    path = os.path.join(bam_dir, re.sub('.bam', '.bam.bai', bam_sample))
    if not (os.path.isfile(path) and os.access(path, os.R_OK)):
        path = os.path.join(bam_dir, re.sub('.bam', '.bai', bam_sample))

    copyfile(json_file, dir + 'Input.json')

    dict_path = os.path.dirname(args.r)
    ref = os.path.basename(args.r).split('.fa')[0]

    with open(dir + 'Input.json') as f:
        data = f.read()
        d = json.loads(data)
        d["HaplotypeCallerGvcf_GATK4.input_bam"] = input_file
        d["HaplotypeCallerGvcf_GATK4.input_bam_index"] = path
        d["HaplotypeCallerGvcf_GATK4.output_directory"] = os.path.join(args.output_directory,'.HaplotypeCaller/' + bam_sample.split('.')[0] + '/')
        d["HaplotypeCallerGvcf_GATK4.ref_dict"] = os.path.join(dict_path, ref + '.dict')
        d["HaplotypeCallerGvcf_GATK4.ref_fasta"] = args.r
        d["HaplotypeCallerGvcf_GATK4.ref_fasta_index"] = args.r + '.fai'
        d["HaplotypeCallerGvcf_GATK4.gatk_path"] = args.gatk
        d["HaplotypeCallerGvcf_GATK4.picard_path"] = args.picard
        d["HaplotypeCallerGvcf_GATK4.bam_directory"] = os.path.dirname(input_file)
        d["HaplotypeCallerGvcf_GATK4.scattered_calling_intervals_list"] = args.intervals

        if args.reference_name.lower() is not "b37":
            d["HaplotypeCallerGvcf_GATK4.reference"] = args.reference_name

    with open(dir + 'Input.json', 'w') as f:
        f.write(json.dumps(d))

    copyfile(overrides, dir + 'Overrides.config')

    with fileinput.FileInput(dir + 'Overrides.config', inplace=True) as file:
        for line in file:
            print(line.replace(
            "medium", args.queue).replace("!@#$", args.ct).replace("%^&*", args.cm).replace("Int cpus = 1", "Int cpus = " + args.cn), end='')

    if args.queue == 'park' or args.queue == 'priopark':
        f = open(dir + 'Overrides.config', "r")
        contents = f.readlines()
        f.close()

        contents.insert(95, "            --account=${account_name} \\\n")

        f = open(dir + 'Overrides.config', "w")
        contents = "".join(contents)
        f.write(contents)
        f.close()

    copyfile(wdl, os.path.join(dir, 'workflow.wdl'))

    return os.path.join(dir,'Input.json'), os.path.join(dir, 'Overrides.config'), os.path.join(dir, 'workflow.wdl')

def return_slurm_command(args):
    """Returns slurm command given args provided"""
    slurm_command = '#!/bin/bash\n' + \
                '#SBATCH -n ' + args.num_cores + '\n' + \
                '#SBATCH -t ' + args.runtime + '\n' + \
                '#SBATCH -p ' + args.queue + '\n' + \
                '#SBATCH --mem-per-cpu=' + args.mem_per_cpu + '\n' + \
                '#SBATCH --mail-type=' + args.mail_type + '\n' + \
                '#SBATCH --mail-user=' + args.mail_user + '\n' + \
        '#SBATCH --exclude=compute-p-17-[34-46]' + '\n'
    if args.queue in ['park', 'priopark']:
        slurm_command += '#SBATCH --account=park_contrib' + '\n'
    slurm_command += 'module load gcc/6.2.0 java/jdk-1.8u112 bcftools/1.9' + '\n'
    return slurm_command

def gen_output_file_name(args, input_file):
    sample = os.path.basename(input_file).split('.')[0]
    output_file_name = args.output_directory + '.HaplotypeCaller/' + '.' + sample + '/' + sample
    return output_file_name

def return_primary_command(args, output_file_name, input_file, input_json, input_config, input_wdl):
    primary_command = 'java -Dconfig.file=' + input_config + ' -jar ' + args.cromwell_path + ' run ' + input_wdl + ' -i ' + input_json
    return primary_command

def gen_sh_file_name(args, output_file_name):
    """Generates sh file name"""
    sh_file_name = os.path.dirname(output_file_name) + '/.sh/' + os.path.basename(output_file_name) + '.sh'
    return sh_file_name

def write_out(args, slurm_command, primary_command, sh_file_name):
    """"""
    os.makedirs(os.path.dirname(sh_file_name), exist_ok=True)
    with open(sh_file_name, 'w') as file:
        file.write(slurm_command + primary_command)

def submit_job(sh_file_name):
    os.chdir(os.path.dirname(sh_file_name))
    os.system('chmod +x ' + os.path.basename(sh_file_name))
    os.system('sbatch ./' + os.path.basename(sh_file_name))

if __name__ == "__main__":
    main()


import torch
import sys

from vision.nn.mobilenet import MobileNetV1
from extract_tf_weights import read_weights

def fill_weights_torch_model(weights, state_dict):
    for name in state_dict:
        if name == 'classifier.weight':
            weight = weights['MobilenetV1/Logits/Conv2d_1c_1x1/weights']
            weight = torch.tensor(weight, dtype=torch.float32).permute(3, 2, 0, 1)
            assert state_dict[name].size() == weight.size()
            state_dict[name] = weight
        elif name == 'classifier.bias':
            bias = weights['MobilenetV1/Logits/Conv2d_1c_1x1/biases']
            bias = torch.tensor(bias, dtype=torch.float32)
            assert state_dict[name].size() == bias.size()
            state_dict[name] = bias
        elif name.endswith('BatchNorm.weight'):
            key = name.replace("features", "MobilenetV1").replace(".", "/").replace('BatchNorm/weight', 'BatchNorm/gamma')
            weight = torch.tensor(weights[key], dtype=torch.float32)
            assert weight.size() == state_dict[name].size()
            state_dict[name] = weight
        elif name.endswith('BatchNorm.bias'):
            key = name.replace("features", "MobilenetV1").replace(".", "/").replace('BatchNorm/bias', 'BatchNorm/beta')
            bias = torch.tensor(weights[key], dtype=torch.float32)
            assert bias.size() == state_dict[name].size()
            state_dict[name] = bias
        elif name.endswith('running_mean'):
            key = name.replace("features", "MobilenetV1").replace(".", "/").replace('running_mean', 'moving_mean')
            running_mean = torch.tensor(weights[key], dtype=torch.float32)
            assert running_mean.size() == state_dict[name].size()
            state_dict[name] = running_mean
        elif name.endswith('running_var'):
            key = name.replace("features", "MobilenetV1").replace(".", "/").replace('running_var', 'moving_variance')
            running_var = torch.tensor(weights[key], dtype=torch.float32)
            assert running_var.size() == state_dict[name].size()
            state_dict[name] = running_var
        elif name.endswith('depthwise.weight'):
            key = name.replace("features", "MobilenetV1").replace(".", "/")
            key = key.replace('depthwise/weight', 'depthwise/depthwise_weights')
            weight = torch.tensor(weights[key], dtype=torch.float32).permute(2, 3, 0, 1)
            assert weight.size() == state_dict[name].size()
            state_dict[name] = weight
        else:
            key = name.replace("features", "MobilenetV1").replace(".", "/").replace('weight', 'weights')
            weight = torch.tensor(weights[key], dtype=torch.float32).permute(3, 2, 0, 1)
            assert weight.size() == state_dict[name].size()
            state_dict[name] = weight

if __name__ == '__main__':
    if len(sys.argv) < 3:
        print("Usage: python translate_tf_modelnetv1.py <tf_model.pb> <pytorch_weights.pth>")
    tf_model = sys.argv[1]
    torch_weights_path = sys.argv[2]
    print("Extract weights from tf model.")
    weights = read_weights(tf_model)

    net = MobileNetV1(1001)
    states = net.state_dict()
    print("Translate tf weights.")
    fill_weights_torch_model(weights, states)
    torch.save(states, torch_weights_path)


# -*- coding: utf-8 -*-
"""
Created on Fri Jul 10 19:17:58 2020

@author: SOPHIE
"""
from wordcloud import WordCloud
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
from lxml import etree
from nltk.tokenize import word_tokenize

#导入数据
data = pd.read_csv('Market_Basket_Optimisation.csv',header=None)

trainsaction = []
for i in range(0,data.shape[0]):
    temp = []
    for j in range(0,data.shape[1]):
        item = str(data.values[i,j])
        if item!='nan':
            temp.append(item)
    trainsaction.append(temp)

# 生成词云
def create_word_cloud(f):
	print('根据词频，开始生成词云!')
	cut_text = word_tokenize(f)
	cut_text = " ".join(cut_text)
	wc = WordCloud(
		max_words=100,
		width=2000,
		height=1200,
    )
	wordcloud = wc.generate(cut_text)
	# 写词云图片
	wordcloud.to_file("wordcloud.jpg")
	# 显示词云文件
	plt.imshow(wordcloud)
	plt.axis("off")
	plt.show()

all_word = ' '.join('%s' %item for item in trainsaction)
# 生成词云
create_word_cloud(all_word)


#####################################
#### PART 9: FUNCTION EXERCISES #####
#####################################

# Complete the tasks below by writing functions! Keep in mind, these can be
# really tough, its all about breaking the problem down into smaller, logical
# steps. If you get stuck, don't feel bad about having to peek to the solutions!

#####################
## -- PROBLEM 1 -- ##
#####################

# Given a list of integers, return True if the sequence of numbers 1, 2, 3
# appears in the list somewhere.

# For example:

# arrayCheck([1, 1, 2, 3, 1]) → True
# arrayCheck([1, 1, 2, 4, 1]) → False
# arrayCheck([1, 1, 2, 1, 2, 3]) → True

def arrayCheck(nums):
    for i, n in enumerate(nums):
        if (i + 2) < len(nums):
            if nums[i] == 1 and nums[i+1] == 2 and nums[i+2] == 3:
                return True
    return False
num_list1 = [1,2,5]
num_list2 = [5,3,1,2,3,5,7]
num_list3 = [4,4,3,3,2,2,1,1]
num_list4 = [1,1,2,2,3,3,4,4,5,5]

print(arrayCheck(num_list1))    # should be False
print(arrayCheck(num_list2))    # should be True
print(arrayCheck(num_list3))    # should be False
print(arrayCheck(num_list4))    # should be False

#####################
## -- PROBLEM 2 -- ##
#####################

# Given a string, return a new string made of every other character starting
# with the first, so "Hello" yields "Hlo".

# For example:

# stringBits('Hello') → 'Hlo'
# stringBits('Hi') → 'H'
# stringBits('Heeololeo') → 'Hello'

def stringBits(str):
  return str[::2]

print(stringBits("Super Computer")) # should print: SprCmue

#####################
## -- PROBLEM 3 -- ##
#####################

# Given two strings, return True if either of the strings appears at the very end
# of the other string, ignoring upper/lower case differences (in other words, the
# computation should not be "case sensitive").
#
# Note: s.lower() returns the lowercase version of a string.
#
# Examples:
#
# end_other('Hiabc', 'abc') → True
# end_other('AbC', 'HiaBc') → True
# end_other('abc', 'abXabc') → True

def end_other(a, b):
    i = 0
    long_str_end = ''
    if len(a) <= len(b):
        while i < len(a):
            add_to_string = b[-len(a)+i]
            long_str_end += add_to_string
            i += 1
        if a.lower() == long_str_end.lower():
            return True
        else:
            return False
    elif len(a) >= len(b):
        while i < len(b):
            add_to_string = a[-len(b)+i]
            long_str_end += add_to_string
            i += 1
        if b.lower() == long_str_end.lower():
            return True
        else:
            return False

print(end_other("hello", 'hello goodbye')) # should return False
print(end_other('hello', 'goodbye hello')) # should return True
print(end_other('abc', 'xyzabc')) # should return True
print(end_other('abcdeflmnop', 'lmnop')) # should return True
print(end_other('abcd', 'qrxbcd')) # should return False because 'a' is missing
print(end_other('AbC', 'HiaBc')) # should return True

#####################
## -- PROBLEM 4 -- ##
#####################

# Given a string, return a string where for every char in the original,
# there are two chars.

# doubleChar('The') → 'TThhee'
# doubleChar('AAbb') → 'AAAAbbbb'
# doubleChar('Hi-There') → 'HHii--TThheerree'

def doubleChar(str):
    dub_Str = ''
    for char in str:
        add_char = char
        dub_Str += char + add_char
    return dub_Str

print(doubleChar("hello"))
print(doubleChar('AAbcCddEEf'))
print(doubleChar('Hi-There'))

#####################
## -- PROBLEM 5 -- ##
#####################

# Read this problem statement carefully!

# Given 3 int values, a b c, return their sum. However, if any of the values is a
# teen -- in the range 13-19 inclusive -- then that value counts as 0, except 15
# and 16 do not count as a teens. Write a separate helper "def fix_teen(n):"that
# takes in an int value and returns that value fixed for the teen rule.
#
# In this way, you avoid repeating the teen code 3 times (i.e. "decomposition").
# Define the helper below and at the same indent level as the main no_teen_sum().
# Again, you will have two functions for this problem!
#
# Examples:
#
# no_teen_sum(1, 2, 3) → 6
# no_teen_sum(2, 13, 1) → 3
# no_teen_sum(2, 1, 14) → 3

def no_teen_sum(a, b, c):
    return fix_teen(a) + fix_teen(b) + fix_teen(c)

def fix_teen(n):
    teen_range = list(range(13,20))
    if n != 15 and n != 16:
        for num in teen_range:
            if n == num:
                return 0
    return n

print(no_teen_sum(1, 2, 3)) # should be 6
print(no_teen_sum(2, 13, 1)) # should be 3
print(no_teen_sum(2, 1, 17)) # should be 3
print(no_teen_sum(55,15,14)) # should be 70

#####################
## -- PROBLEM 6 -- ##
#####################

# Return the number of even integers in the given array.
#
# Examples:
#
# count_evens([2, 1, 2, 3, 4]) → 3
# count_evens([2, 2, 0]) → 3
# count_evens([1, 3, 5]) → 0

def count_evens(nums):
    count = 0
    for i in nums:
        if i%2 == 0:
            count += 1
    return count

print(count_evens([2, 1, 2, 3, 4])) # should be 3
print(count_evens([2, 2, 0])) # should be 3
print(count_evens([1, 3, 5])) # should be 0
print(count_evens([2,42,5,6,7,8,8,8,22,53,77])) # should be 7


import json
from pathlib import Path

not_show = []
with Path("智库website_all-website_list.txt", mode="r", encoding="utf-8").open() as f:
    for line in f:
        not_show.append(line.strip())

off_line = []
with Path("下线excel.txt", mode="r", encoding="utf-8").open() as f:
    for line in f:
        off_line.append(line.strip())

print(len(set(not_show)), len(set(off_line)))

print(list(set(not_show) - set(off_line)))

print(len(set(not_show) & set(off_line)))

print(set(off_line) - set(not_show))


# -*- coding: utf-8 -*-
'''
Manage Kibana objects.

.. code-block:: yaml

    kibana:
      kibana_url: 'https://es.host.com:9200'
      kibana_index: '.kibana'

.. code-block:: yaml

    Ensure minimum dashboard is managed:
      kibana_objects.present:
        - name: 'Logs'
        - kibana_content: <JSON object>
        - kibana_type: 'dashboard'

'''

# Import Python libs
import requests

# Import Salt libs
from salt.utils.dictdiffer import DictDiffer

def __virtual__():
    '''Always load the module.'''
    return True

def present(name, kibana_content=None, kibana_type=None):
    '''
    Ensure the Kibana object exists in the database.

    name
        Name of the object

    kibana_content
        Content in JSON

    kibana_type
        String
    '''
    ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}

    if not kibana_content:
        ret['result'] = False
        ret['comment'] = 'Content is not set'
        return ret

    url, index = _get_parameters(name, kibana_type)
    if not url:
        ret['result'] = False
        ret['comment'] = index
        return ret

    try:
        headers = {'Content-type': 'application/json'}
        response = requests.put(url, headers=headers, json=kibana_content)
    except requests.exceptions.RequestException as exc:
        ret['result'] = False
        ret['comment'] = ("Failed to create Kibana object {0}\n"
                          "Got exception: {1}").format(name, exc)
    else:
        if response.ok:
            ret['comment'] = 'Kibana object {0} has been created'.format(name)
            ret['changes']['new'] = 'Kibana objects created'
        else:
            ret['result'] = False
            ret['comment'] = ("Failed to post Kibana object {0}\n"
                              "Response: {1}").format(name, response)

    return ret

def absent(name, kibana_type=None):
    '''
    Ensure the Kibana object is not present in the database.

    name
        Name of the object

    kibana_type
        String
    '''
    ret = {'name': name, 'result': True, 'comment': '', 'changes': {}}

    url, index = _get_parameters(name, kibana_type)
    if not url:
        ret['result'] = False
        ret['comment'] = index
        return ret

    try:
        response = requests.delete(url)
    except requests.exceptions.RequestException as exc:
        ret['result'] = False
        ret['comment'] = ("Failed to delete Kibana object {0}\n"
                          "Got exception: {1}").format(name, exc)
    else:
        if response.ok:
            ret['comment'] = "Kibana object {0} has been deleted".format(name)
        elif response.status_code == 404:
            ret['comment'] = "Kibana object {0} was not present".format(name)
        else:
            ret['result'] = False
            ret['comment'] = ("Failed to delete Kibana object {0}\n"
                              "Response: {1}").format(name, response)

    return ret

def _get_parameters(name, kibana_type):
    '''
    Retrieve parameters from profile.
    '''

    if not kibana_type:
        return False, 'Type is not set'

    profile = __salt__['config.option']('kibana')

    url = profile.get('kibana_url')
    if not url:
        return False, 'Cannot get URL needed by Kibana client'

    index = profile.get('kibana_index')
    if not index:
        return False, 'Cannot get the index needed by Kibana client'

    url = "http://{0}/{1}/{2}/{3}".format(url, index, kibana_type, name)
    return url, index


import os
import sys
# from typing import Sequence
sys.path.insert(0,os.getcwd())
import copy
import argparse
import shutil
import time
import numpy as np
import random

import torch
# import torch.backends.cudnn as cudnn
import torch.optim as optim
from torch.utils.data import DataLoader
from torch.nn.parallel import DataParallel

from utils.history import History
from utils.dataloader import Mydataset, collate
from utils.train_utils import train, validation, print_info, file2dict, init_random_seed, set_random_seed, resume_model
from utils.inference import init_model
from core.optimizers import *
from models.build import BuildNet

def parse_args():
    parser = argparse.ArgumentParser(description='Train a model')
    parser.add_argument('config', help='train config file path')
    parser.add_argument('--resume-from', help='the checkpoint file to resume from')
    parser.add_argument('--seed', type=int, default=None, help='random seed')
    parser.add_argument('--device', help='device used for training. (Deprecated)')
    parser.add_argument(
        '--gpu-id',
        type=int,
        default=0,
        help='id of gpu to use '
        '(only applicable to non-distributed training)')
    parser.add_argument(
        '--split-validation',
        action='store_true',
        help='whether to split validation set from training set.')
    parser.add_argument(
        '--ratio',
        type=float,
        default=0.2,
        help='the proportion of the validation set to the training set.')
    parser.add_argument(
        '--deterministic',
        action='store_true',
        help='whether to set deterministic options for CUDNN backend.')
    parser.add_argument('--local-rank', type=int, default=0)
    args = parser.parse_args()
    if 'LOCAL_RANK' not in os.environ:
        os.environ['LOCAL_RANK'] = str(args.local_rank)
    return args

def main():
    # 读取配置文件获取关键字段
    args = parse_args()
    model_cfg,train_pipeline,val_pipeline,data_cfg,lr_config,optimizer_cfg = file2dict(args.config)
    print_info(model_cfg)

    # 初始化
    meta = dict()
    dirname = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime())
    save_dir = os.path.join('logs',model_cfg.get('backbone').get('type'),dirname)
    meta['save_dir'] = save_dir

    # 设置随机数种子
    seed = init_random_seed(args.seed)
    set_random_seed(seed, deterministic=args.deterministic)
    meta['seed'] = seed

    # 读取训练&制作验证标签数据
    total_annotations   = "datas/train.txt"
    with open(total_annotations, encoding='utf-8') as f:
        total_datas = f.readlines()
    if args.split_validation:
        total_nums = len(total_datas)
        # indices = list(range(total_nums))
        if isinstance(seed, int):
            rng = np.random.default_rng(seed)
            rng.shuffle(total_datas)
        val_nums = int(total_nums * args.ratio)
        folds = list(range(int(1.0 / args.ratio)))
        fold = random.choice(folds)
        val_start = val_nums * fold
        val_end = val_nums * (fold + 1)
        train_datas = total_datas[:val_start] + total_datas[val_end:]
        val_datas = total_datas[val_start:val_end]
    else:
        train_datas = total_datas.copy()
        test_annotations    = 'datas/test.txt'
        with open(test_annotations, encoding='utf-8') as f:
            val_datas   = f.readlines()

    # 初始化模型,详见https://www.bilibili.com/video/BV12a411772h
    if args.device is not None:
        device = torch.device(args.device)
    else:
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    print('Initialize the weights.')
    model = BuildNet(model_cfg)
    if not data_cfg.get('train').get('pretrained_flag'):
        model.init_weights()
    if data_cfg.get('train').get('freeze_flag') and data_cfg.get('train').get('freeze_layers'):
        freeze_layers = ' '.join(list(data_cfg.get('train').get('freeze_layers')))
        print('Freeze layers : ' + freeze_layers)
        model.freeze_layers(data_cfg.get('train').get('freeze_layers'))

    if device != torch.device('cpu'):
        model = DataParallel(model,device_ids=[args.gpu_id])

    # 初始化优化器
    optimizer = eval('optim.' + optimizer_cfg.pop('type'))(params=model.parameters(),**optimizer_cfg)

    # 初始化学习率更新策略
    lr_update_func = eval(lr_config.pop('type'))(**lr_config)

    # 制作数据集->数据增强&预处理,详见https://www.bilibili.com/video/BV1zY4y167Ju
    train_dataset = Mydataset(train_datas, train_pipeline)
    val_pipeline = copy.deepcopy(train_pipeline)
    val_dataset = Mydataset(val_datas, val_pipeline)
    train_loader = DataLoader(train_dataset, shuffle=True, batch_size=data_cfg.get('batch_size'), num_workers=data_cfg.get('num_workers'),pin_memory=True, drop_last=True, collate_fn=collate)
    val_loader = DataLoader(val_dataset, shuffle=False, batch_size=data_cfg.get('batch_size'), num_workers=data_cfg.get('num_workers'), pin_memory=True,
    drop_last=True, collate_fn=collate)

    # 将关键字段存储，方便训练时同步调用&更新
    runner = dict(
        optimizer         = optimizer,
        train_loader      = train_loader,
        val_loader        = val_loader,
        iter              = 0,
        epoch             = 0,
        max_epochs       = data_cfg.get('train').get('epoches'),
        max_iters         = data_cfg.get('train').get('epoches')*len(train_loader),
        best_train_loss   = float('INF'),
        best_val_acc     = float(0),
        best_train_weight = '',
        best_val_weight   = '',
        last_weight       = ''
    )
    meta['train_info'] = dict(train_loss = [],
                              val_loss = [],
                              train_acc = [],
                              val_acc = [])

    # 是否从中断处恢复训练
    if args.resume_from:
        model,runner,meta = resume_model(model,runner,args.resume_from,meta)
    else:
        os.makedirs(save_dir)
        shutil.copyfile(args.config,os.path.join(save_dir,os.path.split(args.config)[1]))
        model = init_model(model, data_cfg, device=device, mode='train')

    # 初始化保存训练信息类
    train_history =History(meta['save_dir'])

    # 记录初始学习率，详见https://www.bilibili.com/video/BV1WT4y1q7qN
    lr_update_func.before_run(runner)

    # 训练
    for epoch in range(runner.get('epoch'),runner.get('max_epochs')):
        lr_update_func.before_train_epoch(runner)
        train(model,runner, lr_update_func, device, epoch, data_cfg.get('train').get('epoches'), meta)
        validation(model,runner, data_cfg.get('test'), device, epoch, data_cfg.get('train').get('epoches'), meta)

        train_history.after_epoch(meta)

if __name__ == "__main__":
    main()


import random
import turtle as t
import math

"""
Othello board game

Author: George Krlevski
"""

def initialiseBoard(n):
    n1 =int((n/2)-1)
    n2= int(n/2)
    #[x][y] co-ord

    b= [[0 for j in range(n)]for i in range(n)]

    b[n1][n1]=1
    b[n2][n2]= 1
    #Black
    b[n1][n2]= -1
    b[n2][n1]= -1
    #White
    return b

def drawBoard(b):
    #set up window
    t.setup(600,600)
    t.bgcolor("dark green")

    #turtle settings
    t.hideturtle()
    t.speed(0)

    num=len(b)
    side=600/num
    xcod=-300
    ycod=-300
    for x in b:
        for y in x:
            if(y> 0):
                drawsquare(xcod,ycod,side,'black')
            if(y< 0):
                drawsquare(xcod,ycod,side,'white')
            if(y==0):
                drawsquare(xcod,ycod,side,'dark green')

            xcod=xcod+side
        xcod=-300
        ycod=ycod+side

def drawsquare(x,y,length,col):
    t.penup()
    t.setposition(x,y)
    t.pendown()
    t.begin_fill()
    t.color(col)
    t.pencolor('yellow')
    for x in range(0,4,1):
        t.forward(length)
        t.left(90)
    t.end_fill()

def move(b,m,p):
    for x in range(len(m[2])):
        r= m[0]
        c= m[1]
        b[r][c]=p

        if p==1:
            r+=m[2][x][0]
            c+=m[2][x][1]

            while b[r][c] < 0:
                b[r][c] = toChange(b[r][c],p)
                r+= m[2][x][0]
                c+= m[2][x][1]

        if p==-1:
            r+=m[2][x][0]
            c+=m[2][x][1]

            while b[r][c] > 0:
                b[r][c] = toChange(b[r][c],p)
                r+= m[2][x][0]
                c+= m[2][x][1]

    return b

def toChange(val,p):
    #changes value
    x= val
    if x == 0:
        pass
    elif p ==1:
        x= (abs(x) +1)
    elif p==-1:
        x=(abs(x)*-1)-1
    return x

def legalDirection(r,c,b,p,u,v):

    i= r
    j=c
    f=0

    while True:
        #left
        if  v ==-1:
            j+=-1
            if j< 0:
                break
        #right
        if v==1:
            j +=1
            if  j>(len(b)-1):
                break
        #down
        if u==-1:
            i+=-1
            if i<0 :
                break
        #up
        if u == 1:
            i+=1
            if  i> (len(b)-1):
                break

        if b[i][j] ==0:
            break

        #checks opposite
        if b[i][j]*p <0:
            f= 1

        #same and opposite
        if b[i][j]*p >0 and f == 1:

            return True

    return False

def legalMove(r,c,b,p):
    #returns all moves that are legal
    moves=[]
    for u in[-1,0,1]:
        for v in[-1,0,1]:
            if [u,v] ==[0,0]:
                continue
            if legalDirection(r,c,b,p,u,v)!=False:
                moves.append((u,v))
    return moves

def moves(b,p):
    #lists all possible moves for player p on board b.
    moves=[]
    for r in range(len(b)):
        for c in range(len(b)):
            if b[r][c]==0:
                if len(legalMove(r,c,b,p)) > 0:
                    moves.append((r,c,(legalMove(r,c,b,p))))
    return moves

def selectMove(ms,b,p):
    #ms= moves(b,p)
    strategy=  randomChoice(ms)

    #error case
    if strategy == []:
        return 0

    return strategy

def randomChoice (ms):
    # returns choice chosen at random
    y= [i for i,x in enumerate(ms)]
    choice = random.randint(0, len(y)-1)
    z= y[choice]

    return ms[z]

def scoreBoard(b):
    black, white=0,0
    #initialising variables

    for i in range(len(b)):
        for j in range (len(b)):
            piece= b[i][j]
            if(b[i][j]<0):
                white+=-piece
            if(b[i][j] >0):
                black+=piece

    return (black,abs(white))

def find(b):
    for x in b:
        for y in x:
            if y == 0:
                continue

def main():
    """ propmts user for player, board size and it conducts the game"""

    print('Welcome to Othello')
    print()
    x= str(input("Enter Player: Black or White: " ))
    x.strip().lower()
    if x == "black":
        p=1
    else:
        p =-1

    #computer
    comp = p*(-1)#opposite p
    n= int(input("Enter board size: "))
    b= initialiseBoard(n)
    drawBoard(b)

    while True:
        #user
        print("Your move.")
        toMove= moves(b,p)
        if toMove == []:
            break
        possibleMoves =[]
        for x in toMove:
                possibleMoves.append((x[0],x[1]))
        print("Possible moves: ", possibleMoves)

        print("Enter move: ")
        r=int(input("row: "))
        c=int(input("column: "))

        #make move
        for x in toMove:
            if r == x[0] and c ==x[1]:
                b= move(b,x,p)
        drawBoard(b)

        #comp
        print("Computer's move.")
        ms= moves(b, comp)
        if ms ==[]:
            break
        m= selectMove(ms,b,p)
        #no available moves
        if m==0:
            break

        b = move(b,m,comp)
        drawBoard(b)

        # if board is full
        find(b)

    print("************Game Ended!************")
    score= scoreBoard(b)
    print('Score: ', score)
    input("Hit enter to finish: ")


import json
import re
from gensim.models import LdaModel
from gensim.corpora import Dictionary
from nltk.corpus import stopwords
from textblob import TextBlob
import os
import json

folder_path = "reddit_posts"

combined_data = []

for filename in os.listdir(folder_path):
    if filename.endswith(".json"):
        file_path = os.path.join(folder_path, filename)
        with open(file_path, "r") as file:
            data = json.load(file)
            combined_data.extend(data)

print(f"Total number of posts in combined dataset: {len(combined_data)}")
# total number of comments in combined dataset
total_comments = sum(len(post["comments"]) for post in combined_data)
print(f"Total number of comments in combined dataset: {total_comments}")

def preprocess_text(text):
    text = re.sub(r'\W', ' ', text)
    text = re.sub(r'\s+', ' ', text)
    text = text.lower()
    words = text.split()
    stopword_extended = stopwords.words("english")
    stopword_extended.extend(["http", "https", "www", "com", "org", "net", "edu", "reddit", "redditcom", "redditcomr", "redditcomrall", "en"])
    words = [word for word in words if word not in stopword_extended]
    return words

def extract_topics(corpus, num_topics=20):
    dictionary = Dictionary(corpus)
    doc_term_matrix = [dictionary.doc2bow(doc) for doc in corpus]
    lda = LdaModel(doc_term_matrix, num_topics=num_topics, id2word=dictionary, passes=50)
    return lda.print_topics()

def sentiment_analysis(text):
    text_str = ' '.join(text)
    analysis = TextBlob(text_str)
    sentiment = analysis.sentiment.polarity

    return sentiment

minimum_karma = 50

with open('banned_words.json', 'r') as file:
    banned_words = json.load(file)

credible_data = [post for post in combined_data if post["author"]["karma"] >= minimum_karma]
# exclude posts that are about looking for jobs/offering jobs/hiring
data = [post for post in credible_data if not any(word in post["title"].lower() for word in banned_words)]

print(f"Total number of posts in credible dataset: {len(data)}")
# total number of comments in credible dataset
total_comments = sum(len(post["comments"]) for post in data)
print(f"Total number of comments in credible dataset: {total_comments}")

preprocessed_titles = [preprocess_text(post["title"] + " " + post["text"]) for post in data]
preprocessed_comments = [preprocess_text(comment["text"]) for post in data for comment in post["comments"]]

topics = extract_topics(preprocessed_titles + preprocessed_comments)

sentiments = [sentiment_analysis(text) for text in preprocessed_titles + preprocessed_comments]
positive_count = sum(1 for sentiment in sentiments if sentiment > 0)
negative_count = sum(1 for sentiment in sentiments if sentiment < 0)
neutral_count = sum(1 for sentiment in sentiments if sentiment == 0)

results = {
    "topics": topics,
    "sentiments": {
        "positive": positive_count,
        "negative": negative_count,
        "neutral": neutral_count
    }
}

# Save the results to a JSON file
with open("results.json", "w") as outfile:
    json.dump(results, outfile, indent=4)


#!/usr/bin/env python3
import os
import sys
sys.path.append("../")
import utils
import imu
import time
from math import sqrt
import threading

stop_thread = threading.Event()
acc_data = []
imu_thread = threading.Thread(target=imu.imu_thread_func,args=(acc_data,stop_thread,))
imu_thread.start()

try:
    while True:
        time.sleep(0.075)
        if len(acc_data) > 0:
            os.system("clear")
            try:
                ax = round(acc_data[-1][0],3)
                ay = round(acc_data[-1][1],3)
                az = round(acc_data[-1][2],3)
            except:
                utils.brint("Missed data point",color="BOLD_RED")
            print(ax,ay,az)

except KeyboardInterrupt:
    imu.write_to_file(acc_data)
    stop_thread.set()


#Espinoza Castillo Alejandro
#Muestra unos mensajes en las pantallas LCD para mostrar su funcionamiento

from machine import Pin
from time import sleep_ms
from lcd import LCD

figura_1 = (0x0A,0x0A,0x0A,0x00,0x11,0x11,0x0E,0x00)
figura_2 = (0x0A,0x0A,0x0A,0x00,0x0E,0x11,0x11,0x00)
figura_3 = (0x00,0x0A,0x1F,0x1F,0x1F,0x0E,0x04,0x00)
figura_4 = (0x04,0x11,0x0E,0x04,0x04,0x0A,0x11,0x00)
figura_5 = (0x04,0x0E,0x1F,0x04,0x04,0x04,0x04,0x00)
figura_6 = (0x0E,0x0A,0x11,0x11,0x11,0x1F,0x1F,0x00)
figura_7 = (0x04,0x0E,0x04,0x04,0x15,0x15,0x0E,0x00)
figura_8 = (0x1F,0x11,0x0A,0x04,0x0A,0x11,0x1F,0x00)

lcd = LCD(0,1,2,3,4,5)                          # RS, E, D4, D5, D6, D7
lcd.cgram_init()                                # Accede a la CGRAM para guardar caracteres especiales
lcd.cgram_create_char(0, figura_1)              # Guarda los caracteres especiales en las posiciones 0 a 7 de la CGRAM
lcd.cgram_create_char(1, figura_2)
lcd.cgram_create_char(2, figura_3)
lcd.cgram_create_char(3, figura_4)
lcd.cgram_create_char(4, figura_5)
lcd.cgram_create_char(5, figura_6)
lcd.cgram_create_char(6, figura_7)
lcd.cgram_create_char(7, figura_8)
lcd.cgram_close()                               # Sale de la CGRAM
lcd.clear()                                     # Limpia la pantalla LCD

while True:
    lcd.move_to(4,0)
    lcd.putstr("LCD 16x2")
    lcd.move_to(3,1)
    lcd.putstr("Modo 4 Bits")
    lcd.blink()
    sleep_ms(3000)
    lcd.no_blink()
    lcd.clear()
    sleep_ms(200)

    lcd.move_to(0,0)
    lcd.putstr("Hola Que Tal")
    sleep_ms(1000)
    lcd.move_to(0,1)
    lcd.putstr("Excelente Dia")
    sleep_ms(2000)
    lcd.clear()
    sleep_ms(200)

    lcd.move_to(0,0)
    lcd.putstr("Electronica")
    lcd.move_to(0,1)
    lcd.putstr("y Circuitos")
    sleep_ms(1000)
    for x in range(15):
        lcd.shift_right()
        sleep_ms(300)
    for x in range(15):
        lcd.shift_left()
        sleep_ms(300)
    sleep_ms(500)
    lcd.clear()
    sleep_ms(200)

    lcd.move_to(0,0)
    lcd.putstr("CGRAM Characters")
    lcd.move_to(0,1)
    lcd.cgram_putc(0)
    lcd.move_to(2,1)
    lcd.cgram_putc(1)
    lcd.move_to(4,1)
    lcd.cgram_putc(2)
    lcd.move_to(6,1)
    lcd.cgram_putc(3)
    lcd.move_to(8,1)
    lcd.cgram_putc(4)
    lcd.move_to(10,1)
    lcd.cgram_putc(5)
    lcd.move_to(12,1)
    lcd.cgram_putc(6)
    lcd.move_to(14,1)
    lcd.cgram_putc(7)
    sleep_ms(3000)
    lcd.clear()
    sleep_ms(200)

    lcd.move_to(4,0)
    lcd.putstr("Contador")
    lcd.move_to(4,1)
    lcd.putstr("V: ")
    for x in range(101):
        lcd.move_to(7,1)
        lcd.putstr(str(x))
        sleep_ms(150)
    sleep_ms(2000)
    lcd.clear()
    sleep_ms(4000)


import sqlite3
from datetime import datetime

conn = sqlite3.connect('crud.db')
cursor = conn.cursor()

def main():
        print ("Qual tabela gostaria de acessar? ")
        print ("Para acessar postagens, escreva POST" )
        print ("Para acessar comentarios, escreva COMMENT ")
        table = input("-> ")

        if table.lower() == "post" or table.lower() == "comment":
                crud(table)
        else:
                print("Informe um nome válido.")

def crud(table):
        x = input("Qual ação deseja realizar: Create(C), Read(R), Update(U) ou Delete(D)?")
        xLower = x.lower()
        if table.lower() == "post":
                if xLower == "c":
                        c_post()
                elif xLower == "r":
                        r_post()
                elif xLower == "u":
                        u_post()
                elif xLower == "d":
                        d_post()
                else:
                        print("Insira uma ação válida!!")
        else:
                if xLower == "c":
                        c_comment()
                elif xLower == "r":
                        r_comment()
                elif xLower == "u":
                        u_comment()
                elif xLower == "d":
                        d_comment()
                else:
                        print("Insira uma ação válida!!")

def c_post():
        title = input("Qual o titulo da postagem? ")
        created = datetime.now()
        text = input("Qual vai ser o conteúdo? ")
        cursor.execute("INSERT INTO post (Title, Created, Text) VALUES (?, ?, ?)", (title, created, text))
        conn.commit()
        print("Sucesso :)")

def c_comment():
        postIdAdd = input("Insira o ID da postagem ")
        textAdd = input("Qual será o comentário? ")
        created = datetime.now()
        userAdd = input("Qual é o nome do usuario? ")
        cursor.execute("""
        SELECT PostID FROM post WHERE PostID == ?;
        """, postIdAdd)
        postId = cursor.fetchone()

        if postId == None:
                print("Algo deu errado :( ")

        else:
                cursor.execute("INSERT INTO comment (PostID, Text, Created, User) VALUES (?, ?, ?, ?)", (postId[0], textAdd, created, userAdd))

                conn.commit()

                print("Sucesso :)")

def r_post():
        cursor.execute("""
        SELECT * FROM post;
        """)

        for line in cursor.fetchall():
                print(line)

def r_comment():
        cursor.execute("""
        SELECT * FROM comment;
        """)

        for line in cursor.fetchall():
                print(line)

def u_post():
        update = input("Qual é o ID da postagem que quer alterar? ")

        cursor.execute("""
        SELECT PostID FROM post
        WHERE PostID == ?
        """, update)
        checkPost = cursor.fetchone()

        if checkPost == None:
                print("Não foi possivel encontrar esse ID ")

        else:
                data = input("Informe o que deseja alterar (titulo, texto) ")

                if data.lower() == "titulo":
                        newData = input("Insira o novo titulo ")

                        cursor.execute("""
                        UPDATE post SET Title = ?
                        WHERE PostID = ?
                        """, (newData, update))

                        conn.commit()

                        print("Sucesso :) ")

                elif data.lower() == "texto":
                        newData = input("Insira qual é a edição: ")

                        cursor.execute("""
                        UPDATE post SET Text = ?
                        WHERE PostID
                        """, (newData, update))

                        conn.commit()

                        print("Sucesso :) ")

                else:
                        print("Invalido")

def u_comment():
        update = input("Qual é o ID do comentario que quer alterar? ")

        cursor.execute("""
        SELECT CommentID FROM comment
        WHERE CommentID == ?
        """, update)
        checkComment = cursor.fetchone()

        if checkComment == None:
                print("Não foi possivel encontrar esse ID ")

        else:
                data = input("Informe o que deseja alterar (Texto, usuario) ")

                if data.lower() == "text":
                        newData = input("Insira o novo texto ")

                        cursor.execute("""
                        UPDATE comment SET Text = ?
                        WHERE CommentID = ?
                        """, (newData, update))

                        conn.commit()

                        print("Sucesso :) ")

                elif data.lower() == "usuario":
                        newData = input("Insira qual é o usuario: ")

                        cursor.execute("""
                        UPDATE comment SET User = ?
                        WHERE CommentID = ?
                        """, (newData, update))

                        conn.commit()

                        print("Sucesso :) ")

                else:
                        print("Invalido")

def d_post():
        delete = input("Qual é o ID do post a ser excluido? ")

        cursor.execute("""
        SELECT PostID from post
        WHERE PostID == ?
        """, delete)
        checkPost = cursor.fetchone()

        if checkPost == None:
                print("ID invalido ")
        else:
                cursor.execute("""
                DELETE FROM post
                WHERE PostID == ?
                """, delete)

                cursor.execute("""
                DELETE FROM comment
                WHERE PostID == ?
                """, delete)

                conn.commit()

                print("A postagem foi deletada com sucesso :)")

def d_comment():
        delete = input("Qual é o ID do comentario? ")

        cursor.execute("""
        SELECT CommentID FROM comment
        WHERE CommentID == ?
        """, delete)
        checkComment = cursor.fetchone()

        if checkComment == None:
                print("Não foi possivel encontrar esse comentario ")
        else:
                cursor.execute("""
                DELETE FROM comment
                WHERE CommentID == ?
                """, delete)

                conn.commit()

                print("Sucesso :)")

main()


"""Ülesanne: Funktsiooni mõiste"""

import math
from math import sqrt

def print_helloworld():
    print("Hello")

def get_hello():
    return print_helloworld()
#
def ask_name_and_greet_user():
    nimi = input("Sisesta nimi: ")
    cap_name = nimi.capitalize()
    if cap_name == "Thanos":
        print("Get out of here Thanos!!!")
    else:
        print("Hi, " + cap_name + ". Would you like a hamburger.")

ask_name_and_greet_user()

print(" ")

# ülesanne 2

def calculate_hypotenuse_length(a, b):
    c = math.sqrt(a**2 + b**2)
    return c

func_result = calculate_hypotenuse_length(5, 4)
print(func_result)

print(" ")

# Teise kaateti leidmine ühe kaateti ja hüpotenuusi abil

def calculate_cathetus_length(a: int, b: int):
    c = math.sqrt(a**2 - b**2)
    return c

    print(float(c))

print(calculate_cathetus_length(6.4, 4))


import sys
import re

seed = ""

try:
  N = int(sys.argv[1])

  if len(sys.argv) > 2:
    seed = str(sys.argv[2])

except:

  print("usage: look_n_say.py N [--seed]")

  print("\npositional arguments:\n N\t number of iterations.")
  print("\noptional arguments:\n --seed\t starting seed.")
  sys.exit()

if seed == "":
  seed = "1"

word = seed

for _ in range(N):

  print(word)

  length = len(word)

  current_amount = 0
  current_number = word[0]
  new_word = ""

  for number in word:

    if number == current_number:
      current_amount += 1
    else:
      new_word += str(current_amount)
      new_word += current_number
      current_number = number
      current_amount = 1

  new_word += str(current_amount)
  new_word += current_number

  word = new_word


from fastai.vision.all import *

url = 'https://github.com/deep-diver/fastai-course/raw/master/data/oxford-iiit-pet-tiny.tar.gz'
path = untar_data(url)

block = DataBlock(blocks=(ImageBlock, CategoryBlock),
                  get_items=get_image_files,
                  get_y=lambda f: f.name[0].isupper(),
                  splitter  = RandomSplitter(),
                  item_tfms = [Resize(224)])

dls = block.dataloaders(path/'images', bs=4)
dls.show_batch()


A = 0
B = 0
C = 0
D = 0

array = [A, B, C, D]
equal = True

for i in range(2**(len(array))):
    b = bin(i)
    b = str(b).split('b')[1]
    b = list(b)
    b = list(map(lambda x: int(x), b))
    b = (len(array)-len(b))*[0]+b
    print(b)
    A, B, C, D = b
    eval1 = not A and ((B or (not C and D)) or C and B)
    eval2 = not A and ((A or B) or not C and D)

    equal = equal and eval1 == eval2

print("Same condition: "+str(equal))


#!/usr/bin/env python
# lint_ignore=E501
# ***** BEGIN LICENSE BLOCK *****
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
# ***** END LICENSE BLOCK *****
""" updates.py

A script publish a release to Balrog.

"""

import os
import sys
from datetime import datetime, timedelta

sys.path.insert(1, os.path.dirname(os.path.dirname(sys.path[0])))
from mozharness.base.vcs.vcsbase import MercurialScript
from mozharness.mozilla.buildbot import BuildbotMixin
from mozharness.base.log import FATAL

# PublishBalrog {{{1

class PublishBalrog(MercurialScript, BuildbotMixin):

    def __init__(self, require_config_file=True):
        super(PublishBalrog, self).__init__(
            all_actions=[
                'clobber',
                'pull',
                'submit-to-balrog',
            ],
            default_actions=[
                'clobber',
                'pull',
                'submit-to-balrog',
            ],
            config={
                'buildbot_json_path': 'buildprops.json',
                'credentials_file': 'oauth.txt',
            },
            require_config_file=require_config_file
        )

    def _pre_config_lock(self, rw_config):
        super(PublishBalrog, self)._pre_config_lock(rw_config)
        # override properties from buildbot properties here as defined by
        # taskcluster properties
        self.read_buildbot_config()
        if not self.buildbot_config:
            self.warning("Skipping buildbot properties overrides")
            return
        # TODO: version and appVersion should come from repo
        props = self.buildbot_config["properties"]
        for prop in ['product', 'version', 'build_number', 'channels',
                     'balrog_api_root', 'schedule_at', 'background_rate',
                     'publish_bz2_blob']:
            if props.get(prop):
                self.info("Overriding %s with %s" % (prop, props[prop]))
                self.config[prop] = props.get(prop)

    def query_abs_dirs(self):
        if self.abs_dirs:
            return self.abs_dirs
        self.abs_dirs = super(PublishBalrog, self).query_abs_dirs()
        self.abs_dirs["abs_tools_dir"] = os.path.join(
            self.abs_dirs['abs_work_dir'], self.config["repo"]["dest"])
        return self.abs_dirs

    def query_channel_configs(self):
        """Return a list of channel configs.
        For RC builds it returns "release" and "beta" using
        "enabled_if_version_matches" to match RC.

        :return: list
         """
        return [(n, c) for n, c in self.config["update_channels"].items() if
                n in self.config["channels"]]

    def query_repos(self):
        """Build a list of repos to clone."""
        return [self.config["repo"]]

    def pull(self):
        super(PublishBalrog, self).pull(
            repos=self.query_repos())

    def submit_to_balrog(self):
        for _, channel_config in self.query_channel_configs():
            self._submit_to_balrog(channel_config)
        if 'publish_bz2_blob' in self.config and \
                self.config['publish_bz2_blob']:
            for _, channel_config in self.query_channel_configs():
                self._submit_to_balrog_bz2(channel_config)

    def _submit_to_balrog(self, channel_config):
        dirs = self.query_abs_dirs()
        auth = os.path.join(os.getcwd(), self.config['credentials_file'])
        cmd = [
            sys.executable,
            os.path.join(dirs["abs_tools_dir"],
                         "scripts/build-promotion/balrog-release-shipper.py")]
        cmd.extend([
            "--api-root", self.config["balrog_api_root"],
            "--credentials-file", auth,
            "--username", self.config["balrog_username"],
            "--version", self.config["version"],
            "--product", self.config["product"],
            "--build-number", str(self.config["build_number"]),
            "--verbose",
        ])
        for r in channel_config["publish_rules"]:
            cmd.extend(["--rules", str(r)])
        if channel_config.get("schedule_asap"):
            # RC releases going to the beta channel have no ETA set for the
            # RC-to-beta push. The corresponding task is scheduled after we
            # resolve the push-to-beta human decision task, so we can schedule
            # it ASAP plus some additional 30m to avoid retry() to fail.
            schedule_at = datetime.utcnow() + timedelta(minutes=30)
            cmd.extend(["--schedule-at", schedule_at.isoformat()])
        elif self.config.get("schedule_at"):
            cmd.extend(["--schedule-at", self.config["schedule_at"]])
        if self.config.get("background_rate"):
            cmd.extend(["--background-rate", str(self.config["background_rate"])])

        self.retry(lambda: self.run_command(cmd, halt_on_failure=True),
                   error_level=FATAL)

    def _submit_to_balrog_bz2(self, channel_config):
        dirs = self.query_abs_dirs()
        # Use env varialbe instead of command line to avoid issues with blob
        # names starting with "-", e.g. "-bz2"
        env = {"BALROG_BLOB_SUFFIX": channel_config["bz2_blob_suffix"]}
        auth = os.path.join(os.getcwd(), self.config['credentials_file'])
        cmd = [
            sys.executable,
            os.path.join(dirs["abs_tools_dir"],
                         "scripts/build-promotion/balrog-release-shipper.py")]
        cmd.extend([
            "--api-root", self.config["balrog_api_root"],
            "--credentials-file", auth,
            "--username", self.config["balrog_username"],
            "--version", self.config["version"],
            "--product", self.config["product"],
            "--build-number", str(self.config["build_number"]),
            "--suffix", channel_config["bz2_blob_suffix"],
            "--verbose",
        ])
        for r in channel_config["bz2_publish_rules"]:
            cmd.extend(["--rules", str(r)])
        if channel_config.get("schedule_asap"):
            # RC releases going to the beta channel have no ETA set for the
            # RC-to-beta push. The corresponding task is scheduled after we
            # resolve the push-to-beta human decision task, so we can schedule
            # it ASAP plus some additional 30m to avoid retry() to fail.
            schedule_at = datetime.utcnow() + timedelta(minutes=30)
            cmd.extend(["--schedule-at", schedule_at.isoformat()])
        elif self.config.get("schedule_at"):
            cmd.extend(["--schedule-at", self.config["schedule_at"]])
        if self.config.get("background_rate"):
            cmd.extend(["--background-rate", str(self.config["background_rate"])])

        self.retry(lambda: self.run_command(cmd, halt_on_failure=True, env=env),
                   error_level=FATAL)

# __main__ {{{1
if __name__ == '__main__':
    PublishBalrog().run_and_exit()


# This example demonstrates simple PCA-computation using CUDA-Solver library.

import pycuda.autoinit
from pycuda import gpuarray
import numpy as np
from skcuda import linalg

vals = [np.float32([10, 0, 0, 0, 0, 0, 0, 0, 0, 0]), np.float32([0, 10, 0, 0, 0, 0, 0, 0, 0, 0])]

for i in range(3000):
    vals.append(vals[0] + 0.001 * np.random.randn(10))
    vals.append(vals[1] + 0.001 * np.random.randn(10))
    vals.append(0.001 * np.random.randn(10))

vals = np.float32(vals)
vals = vals - np.mean(vals, axis=0)
v_gpu = gpuarray.to_gpu(vals.T.copy())

U_d, s_d, V_d = linalg.svd(v_gpu, lib='cusolver')

u = U_d.get()
s = s_d.get()
v = V_d.get()

print(s**2)
print(u[:,0])
print(u[:,1])


from selenium.webdriver.common.by import By
from traceback import print_stack
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import *
import utilities.custom_logger as cl
import logging
import time
import os

class SeleniumDriver():

    log = cl.customLogger(logging.DEBUG)

    def __init__(self, driver):
        self.driver = driver

    def getByType(self, locatorType):
        """
        returns Bytype
        """

        locatorType = locatorType.lower()

        if locatorType == "id":
            return By.ID
        elif locatorType == "name":
            return By.NAME
        elif locatorType == "xpath":
            return By.XPATH
        elif locatorType == "css":
            return By.CSS_SELECTOR
        elif locatorType == "class":
            return By.CLASS_NAME
        elif locatorType == "link":
            return By.LINK_TEXT
        else:
            self.log.info("Locator type " + locatorType +
                          " is not correct")
        return False

    def getElement(self, locator, locatorType="id"):

        element = None
        try:
            locatorType = locatorType.lower()
            byType = self.getByType(locatorType)
            element = self.driver.find_element(byType, locator)
            self.log.info("Succesfully found element with locator: " + locator +
                          " and  locatorType: " + locatorType)
        except:
            self.log.info("Unable to find Element with locator: " + locator +
                          " and  locatorType: " + locatorType)
        return element

    def elementClick(self, locator, locatorType="id"):

        try:
            element = self.getElement(locator, locatorType)
            element.click()
            self.log.info("Successfully clicked the element with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Unable to click on the element with locator: " + locator +
                          " locatorType: " + locatorType)
            print_stack()

    def sendKeys(self, data, locator, locatorType="id"):
        try:
            element = self.getElement(locator, locatorType)
            element.send_keys(data)
            self.log.info("Succssfully Sent data with locator: " + locator +
                          " locatorType: " + locatorType)
        except:
            self.log.info("Unable to send data with locator: " + locator +
                  " locatorType: " + locatorType)
            print_stack()

    def waitForElement(self, locator, locatorType="id",
                               timeout=10, pollFrequency=0.5):
        element = None
        try:
            byType = self.getByType(locatorType)

            wait = WebDriverWait(self.driver, 10, poll_frequency=1,
                                 ignored_exceptions=[NoSuchElementException,
                                                     ElementNotVisibleException,
                                                     ElementNotSelectableException])
            element = wait.until(EC.element_to_be_clickable((byType,locator)))

            self.log.info("Successfully Element appeared on the web page")
        except:
            self.log.info("Unable to find Element on the web page")
            print_stack()
        return element

    def webScroll(self, direction="up"):

        if direction == "up":
            self.driver.execute_script("window.scrollBy(0, -1000);")

        if direction == "down":
            self.driver.execute_script("window.scrollBy(0, 900);")

    def getText(self, locator="", locatorType="id"):

        try:
            element = self.getElement(locator, locatorType)
            text = element.text
            if len(text) != 0:
                text = text.strip()

        except:
            self.log.error("Failed to get text on element ")
            print_stack()
            text = None
        return text

    def screenShot(self, resultMessage):

        fileName = resultMessage + "." + str(round(time.time() * 1000)) + ".png"
        screenshotDirectory = "../screenshots/"
        relativeFileName = screenshotDirectory + fileName
        currentDirectory = os.path.dirname(__file__)
        destinationFile = os.path.join(currentDirectory, relativeFileName)
        destinationDirectory = os.path.join(currentDirectory, screenshotDirectory)

        try:
            if not os.path.exists(destinationDirectory):
                os.makedirs(destinationDirectory)
            self.driver.save_screenshot(destinationFile)
            self.log.info("Screenshot save to directory: " + destinationFile)
        except:
            self.log.error("### Exception Occurred when taking screenshot")
            print_stack()


import numpy as np
from tensorflow.keras.preprocessing import sequence
from .build_features import create_HoTS_output

class DataGeneratorDTI(object):
    """

    """
    def __init__(self, train_drug, train_protein, train_label=None, batch_size=32,
                 protein_encoder=None, compound_encoder=None, train=True, grid_size=10, protein_max_len=2500):
        self.__batch_size = batch_size
        self.protein_encoder = protein_encoder
        self.compound_encoder = compound_encoder
        self.train = train
        self.n = len(train_drug)
        self.__grid_size = grid_size
        self.protein_max_len = protein_max_len
        if train:
            permute_index = np.random.permutation(range(self.n))
        else:
            permute_index = range(self.n)
        self.__drugs = [train_drug[i] for i in permute_index]
        self.__compound_type = compound_encoder.get_type()
        self.__proteins = [train_protein[i] for i in permute_index]
        if self.train:
            self.__label = [train_label[i] for i in permute_index]
        else:
            self.__label = None
        self.num = 0

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        if (self.num+1)*self.__batch_size >= self.n:
            start_ind = self.num*self.__batch_size
            end_ind = self.n
        elif self.num*self.__batch_size <= self.n:
            start_ind = self.num*self.__batch_size
            end_ind = (self.num+1)*self.__batch_size
        else:
            raise StopIteration()
        self.num += 1
        drugs = self.__drugs[start_ind:end_ind]
        proteins = self.__proteins[start_ind:end_ind]
        max_len = max([len(seq) for seq in proteins])
        units = self.__grid_size
        max_len = min(int(np.ceil(max_len/units)*units), self.protein_max_len)
        protein_features = self.protein_encoder.pad(proteins, max_len=max_len)
        mask = np.zeros(shape=(end_ind - start_ind, int(np.ceil(max_len / self.__grid_size)) + 1))
        for i, protein in enumerate(proteins):
            mask[i, 0: int(np.ceil(len(protein) / self.__grid_size)) + 1] = 1
        if self.__compound_type.split("_")[0]=="SMILES":
            smiles_max_len = max([len(smiles) for smiles in drugs])
            smiles_max_len = int(np.ceil(smiles_max_len/units)*units)
            drugs = self.compound_encoder.pad(drugs, smiles_max_len)
            if self.train:
                labels = self.__label[start_ind: end_ind]
                labels = np.array(labels)
                return [drugs, protein_features], labels
            else:
                return [drugs, protein_features]
        else:
            drugs = np.stack(drugs)
            if self.train:
                labels = self.__label[start_ind: end_ind]
                labels = np.array(labels)
                return [drugs, protein_features, mask], labels

            else:
                return [drugs, protein_features, mask]

class DataGeneratorChemicalLibrary(object):
    """

    """
    def __init__(self, chemical_library, target_protein, batch_size=32, protein_encoder=None, compound_encoder=None, grid_size=10, protein_max_len=2500):
        self.__batch_size = batch_size
        self.protein_encoder = protein_encoder
        self.compound_encoder = compound_encoder
        self.__grid_size = grid_size
        self.protein_max_len = protein_max_len
        self.max_len = min(int(np.ceil(target_protein / self.__grid_size) * self.__grid_size), self.protein_max_len)
        self.protein_feature = self.protein_encoder.encode()
        self.num = 0
        self.chemical_library = chemical_library

        self.chemical_library = open(chemical_library, 'r')
        self.stop_condition = False

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        if self.stop_condition:
            raise StopIteration
        drugs = []
        for i in range(self.__batch_size):
            smiles = self.chemical_library.readline().strip()
            if not smiles:
                self.chemical_library.close()
                self.stop_condition = True
                break
            else:
                drugs.append(smiles)
        protein_features = self.protein_encoder.pad([self.protein_feature]*len(drugs), max_len=self.max_len)
        mask = np.ones(shape=(len(drugs), self.max_len))

        if self.__compound_type.split("_")[0]=="SMILES":
            smiles_max_len = max([len(smiles) for smiles in drugs])
            smiles_max_len = int(np.ceil(smiles_max_len/self.__grid_size)*self.__grid_size)
            drugs_features = self.compound_encoder.pad([self.compound_encoder.encode(drug) for drug in drugs], smiles_max_len)
            return [drugs_features, protein_features, drugs]
        else:
            drugs_features = self.compound_encoder.pad([self.compound_encoder.encode(drug) for drug in drugs])
            drugs_features = np.stack(drugs_features)
            return [drugs_features, protein_features, mask, drugs]

class DataGeneratorHoTS(object):
    """

    """
    def __init__(self, protein, ind_label=False, ligand=False, name=False, anchors=False,
                 batch_size=32, shuffle=True, train=True, protein_encoder=None, compound_encoder=None, n_cores=10,
                 grid_size=25):
        self.__batch_size = batch_size
        self.shuffle = shuffle
        self.train = train
        self.n = len(protein)
        if self.shuffle:
            permute_index = np.random.permutation(range(self.n))
        else:
            permute_index = range(self.n)
        self.__dti_label = np.array([1]*self.n)
        '''
        if self.train:
            protein, ligand, name, ind_label, dti_label = self.sample_negative(protein, ligand, name, ind_label)

            self.__dti_label = [dti_label[i] for i in permute_index]
        '''
        if ind_label:
            self.__ind_label = [ind_label[i] for i in permute_index]
        else:
            self.__ind_label = None
        self.__ligand = [ligand[i] for i in permute_index]
        if name:
            self.__name = [name[i] for i in permute_index]
        else:
            self.__name = None
        self.__protein = [protein[i] for i in permute_index]
        self.anchors = anchors
        self.num = 0
        self.__protein_encoder = protein_encoder
        self.__compound_encoder = compound_encoder
        self.__compound_type = self.__compound_encoder.get_type()
        self.__grid_size = grid_size
    '''
    def jaccard_similarity(self, list1, list2):
        intersection = len(list(set(list1).intersection(list2)))
        union = (len(list1) + len(list2)) - intersection
        return float(intersection) / union

    def sample_negative(self, proteins, ligands, names, ind_labels):
        pos_size = len(proteins)
        train_tuples = [(protein, ligand, ind_label) for protein, ligand, ind_label in zip(proteins, ligands, ind_labels)]
        neg_proteins = []
        neg_ligands = []
        neg_names = ["%d_negative"%i for i in range(pos_size)]
        neg_inds = []
        dti_labels = [1]*pos_size + [0]*pos_size
        for protein, ligand, ind_label in train_tuples:
            rand_ind = np.random.randint(0, pos_size)
            neg_ligand_selected = ligands[rand_ind]
            rand_val = np.random.random_sample()
            if rand_val > (1-self.jaccard_similarity(ligand, neg_ligand_selected)):
                n_inds = np.ceil(len(ind_label)*rand_val)
                rand_inds = [ind_label[i] for i in np.random.randint(0, len(ind_label), size=int(n_inds))]
                neg_inds.append(rand_inds)
            else:
                neg_inds.append([])
            neg_proteins.append(protein)
            neg_ligands.append(neg_ligand_selected)
        sampled_proteins = proteins + neg_proteins
        neg_ligands = np.stack(neg_ligands)
        sampled_ligands = np.concatenate([ligands, neg_ligands], axis=0)
        if names:
            sampled_names = names + neg_names
        else:
            sampled_names = names
        sampled_ind_label = ind_labels + neg_inds
        return sampled_proteins, sampled_ligands, sampled_names, sampled_ind_label, dti_labels
    '''

    def __iter__(self):
        return self

    def __next__(self):
        return self.next()

    def next(self):
        if (self.num+1)*self.__batch_size >= self.n:
            start_ind = self.num*self.__batch_size
            end_ind = self.n
        elif self.num*self.__batch_size <= self.n:
            start_ind = self.num*self.__batch_size
            end_ind = (self.num+1)*self.__batch_size
        else:
            raise StopIteration()
        self.num += 1
        sequences = self.__protein[start_ind:end_ind]
        max_len = max([len(seq) for seq in sequences])
        units = self.__grid_size
        max_len = int(np.ceil(max_len/units)*units)
        returning_sequence = self.__protein_encoder.pad(self.__protein[start_ind:end_ind], max_len=max_len)
        queried_ligands = self.__ligand[start_ind:end_ind]
        mask = np.zeros(shape=(end_ind - start_ind, int(np.ceil(max_len / self.__grid_size)) + 1))
        for i, protein in enumerate(sequences):
            mask[i, 0: int(np.ceil(len(protein) / self.__grid_size)) + 1] = 1
        #print(self.__compound_type)
        if self.__compound_type.split("_")[0]=="SMILES":
            smiles_max_len = max([len(smiles) for smiles in queried_ligands])
            smiles_max_len = int(np.ceil(smiles_max_len/units)*units)
            queried_ligands = self.__compound_encoder.pad(queried_ligands, smiles_max_len)
        else:
            queried_ligands = np.stack(queried_ligands)
        entry_names = None
        if self.__name:
            entry_names = self.__name[start_ind:end_ind]
        if self.__ind_label:
            queried_indice = np.array(self.__ind_label[start_ind:end_ind], dtype=object)
            queried_dtis = np.array(self.__dti_label[start_ind:end_ind])
            hots_outputs = [create_HoTS_output(indice, i, self.anchors, max_len=max_len,
                                               train=self.train, grid_len=self.__grid_size)
                            for i, indice in enumerate(queried_indice)]
            hots_grid_outputs = np.stack([hots_output[0] for hots_output in hots_outputs], axis=0)
            hots_indice = [hots_output[1] for hots_output in hots_outputs]
            return returning_sequence, hots_grid_outputs, mask, hots_indice, queried_ligands, queried_dtis, entry_names
        else:
            return returning_sequence, mask, queried_ligands


# encoding=<Encoding.LATIN1: 0>

import os
from shutil import copy2, move
from pydub import AudioSegment

import mutagen
from mutagen import mp4, easymp4, mp3, aiff

class AifMetaData:
  def __init__(self, fl):
    self.title = str(fl.get('TIT2', None))
    self.artist = str(fl.get('TPE1', None))
    self.albumArtist = str(fl.get('TPE2', None))
    self.composer = str(fl.get('TCOM', None))
    self.album = str(fl.get('TALB', None))
    self.trackNo = str(fl.get('TRCK', None)[0]).split('/')[0]
    self.tracks = str(fl.get('TRCK', None)[0]).split('/')[1]
    self.diskNo = str(fl.get('TPOS', None)[0]).split('/')[0]
    self.disks = str(fl.get('TPOS', None)[0]).split('/')[1]
    self.genre = str(fl.get('TCON', None))
    self.year = str(fl.get('TDRC', None))

  def summary(self):
    varsCopy = vars(self).copy()
    return varsCopy

walk_path = os.path.join('G:', 'My Drive', 'Music', 'aif by Album')

for source_dir, _, files in os.walk(walk_path):

    try:
      print(source_dir)
    except:
      continue

    for file in files:

        fileName = file.split('.')[:-1]
        fileExt = file.split('.')[-1]
        print(fileName, fileExt)
        quit()

        if not file.lower().endswith(('aif')):
          continue

        source_path = os.path.join(source_dir, file)

        mut = aiff.AIFF(source_path)
        metaData = AifMetaData(mut)

        aif = AudioSegment.from_file(source_path)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import torch
import numpy as np

from models.losses import FocalLoss, RegL1Loss, RegLoss, RegWeightedL1Loss, BinRotLoss, AutoShape_Position_loss, RegWeightedL1Loss2
from models.utils import _sigmoid
from .base_trainer import BaseTrainer

class AutoShapeLoss(torch.nn.Module):
    def __init__(self, opt):
        super(AutoShapeLoss, self).__init__()
        self.crit = FocalLoss()
        self.crit_hm_hp = torch.nn.MSELoss() if opt.mse_loss else FocalLoss()
        self.crit_kp = RegWeightedL1Loss() if not opt.dense_hp else \
            torch.nn.L1Loss(reduction='sum')
        self.crit_p3d = RegWeightedL1Loss2()
        self.crit_reg = RegL1Loss() if opt.reg_loss == 'l1' else \
            RegLoss() if opt.reg_loss == 'sl1' else None
        self.crit_rot = BinRotLoss()
        self.opt = opt
        is_kitti = False
        if 'kitti' in opt.dataset: is_kitti = True
        self.position_loss = AutoShape_Position_loss(opt, is_kitti)

    def forward(self, outputs, batch, phase=None):

        opt = self.opt
        hm_loss, wh_loss, off_loss = 0, 0, 0
        hp_loss, off_loss, hm_hp_loss, hp_offset_loss = 0, 0, 0, 0
        dim_loss, rot_loss, prob_loss = 0, 0, 0
        p3d_loss = 0
        coor_loss =0
        box_score=0
        output = outputs[0]
        output['hm'] = _sigmoid(output['hm'])
        if opt.hm_hp and not opt.mse_loss:
            output['hm_hp'] = _sigmoid(output['hm_hp'])
        hm_loss = self.crit(output['hm'], batch['hm'])
        hp_loss = self.crit_kp(output['hps'],batch['hps_mask'], batch['ind'], batch['hps'],batch['dep'])
        if opt.wh_weight > 0:
            wh_loss = self.crit_reg(output['wh'], batch['reg_mask'],batch['ind'], batch['wh'])
        if opt.dim_weight > 0:
            dim_loss = self.crit_reg(output['dim'], batch['reg_mask'],batch['ind'], batch['dim'])
            p3d_loss += self.crit_reg(output['p3d'], batch['reg_mask'],
                                     batch['ind'], batch['p3d'])
        if opt.rot_weight > 0:
            rot_loss = self.crit_rot(output['rot'], batch['rot_mask'], batch['ind'], batch['rotbin'], batch['rotres'])
        if opt.reg_offset and opt.off_weight > 0:
            off_loss = self.crit_reg(output['reg'], batch['reg_mask'], batch['ind'], batch['reg'])
        if opt.reg_hp_offset and opt.off_weight > 0:
            hp_offset_loss = self.crit_reg(output['hp_offset'], batch['hp_mask'], batch['hp_ind'], batch['hp_offset'])
        if opt.hm_hp and opt.hm_hp_weight > 0:
            hm_hp_loss = self.crit_hm_hp(output['hm_hp'], batch['hm_hp'])
        coor_loss, prob_loss, box_score = self.position_loss(output, batch,phase)
        loss_stats = {'loss': box_score, 'hm_loss': hm_loss, 'hp_loss': hp_loss,
                      'hm_hp_loss': hm_hp_loss, 'hp_offset_loss': hp_offset_loss,
                      'wh_loss': wh_loss, 'off_loss': off_loss, 'dim_loss': dim_loss,
                      'rot_loss': rot_loss, 'prob_loss': prob_loss, 'box_score': box_score, 'coor_loss': coor_loss,
                      'p3d_loss': p3d_loss
                      }

        return loss_stats, loss_stats

class AutoShapeTrainer(BaseTrainer):
    def __init__(self, opt, model, optimizer=None):
        super(AutoShapeTrainer, self).__init__(opt, model, optimizer=optimizer)

    def _get_losses(self, opt):
        loss_states = ['loss', 'hm_loss', 'hp_loss', 'hm_hp_loss',
                       'hp_offset_loss', 'wh_loss', 'off_loss', 'dim_loss', 'rot_loss', 'prob_loss', 'coor_loss',
                       'box_score',
                       'p3d_loss'
                       ]
        loss = AutoShapeLoss(opt)
        return loss_states, loss

    def debug(self, batch, output, iter_id):
        pass

    def save_result(self, output, batch, results):
        pass


class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        num = []
        for i in nums:
            if i not in num:
                num.append(i)
        num.sort()
        if len(num) <=2:
            return max(num)
        elif len(num) >=3:
            return num[-3]


#!/usr/bin/python3

import os
import sys
import time
from multiprocessing import Value, Queue, Process

import cv2
import numpy as np

from observer import Camera
from observer.cam_defs import *

__all__ = ['do_setup']

# keys
KEY_RETURN = 13
KEY_ESC = 27

# windows
CONTROL = "Control"
DELTA = "Delta"
DILATE = "Dilate"

# trackbars
THRESH_MIN = "Thr min"
THRESH_MAX = "Thr max"

CONT_MIN = "Cntr min"
CONT_MAX = "Cntr max"

FOCUS_TB = "Focus"

thresh_min = Value("i", 25)
thresh_max = Value("i", 255)

cont_min = Value("i", 2000)
cont_max = Value("i", 30000)

working_f = Value("i", 1)
working_f.value = True

focus_v = Value("i", 0)

HEIGHT = 480
WIDTH = 640

DET_H = 90
DET_W = 160

def grabber_loop(cam_id, frames, working, t_min, t_max, c_min, c_max, focus):
    saved_focus = -1

    cam_h = cv2.VideoCapture(int(cam_id))
    # cam_h.set(cv2.CAP_PROP_ZOOM, 0)
    cam_h.set(cv2.CAP_PROP_FOURCC, MJPG_CODEC)
    cam_h.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
    cam_h.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    # cam_h.set(cv2.CAP_PROP_FPS, 30.0)
    print("FPS {:s}".format(str(cam_h.get(cv2.CAP_PROP_FPS))))
    print("H {:s}".format(str(cam_h.get(cv2.CAP_PROP_FRAME_HEIGHT))))
    print("W {:s}".format(str(cam_h.get(cv2.CAP_PROP_FRAME_WIDTH))))

    rec_t = time.time()
    last_f = None

    while working.value and cam_h.isOpened():
        if focus.value != saved_focus:
            saved_focus = focus.value
            cam_h.set(cv2.CAP_PROP_FOCUS, saved_focus/100)

        cur_t = time.time()
        # check_t = cur_t
        rec_t_c = cur_t - rec_t

        if rec_t_c >= REC_TMT:
            rec_t = rec_t_c

            ret, frame = cam_h.read()
            if not ret:
                time.sleep(REC_TMT_SHIFT)
                continue

            cur = cv2.resize(frame, (WIDTH, HEIGHT))
            # cur = Camera.mirroring_img(frame)

            if last_f is not None:
                # frame_last = Camera.process_denoise(last_f)
                frame_last = Camera.process_for_detect(last_f, DEF_GAUSS_BLUR_KERN_SIZE, DEF_GAUSS_BLUR_KERN_SIZE)
                # frame_cur = Camera.process_denoise(cur)
                frame_cur = Camera.process_for_detect(cur, DEF_GAUSS_BLUR_KERN_SIZE, DEF_GAUSS_BLUR_KERN_SIZE)

                delta = cv2.absdiff(frame_last, frame_cur)

                thresh = Camera.accept_threshold(delta, t_min.value, t_max.value)

                dilate = Camera.get_dilate(thresh)

                detected, with_contours = Camera.check_contours(thresh, cur.copy(), c_min.value, c_max.value)

                frames.put_nowait((dilate, with_contours))

            last_f = cur
        else:
            time.sleep(REC_TMT_SHIFT)

    cam_h.release()

def change_thresh_min(x):
    if x < thresh_max.value:
        thresh_min.value = x
    else:
        cv2.setTrackbarPos(THRESH_MIN, CONTROL, thresh_min.value)

def change_thresh_max(x):
    if x > thresh_min.value:
        thresh_max.value = x
    else:
        cv2.setTrackbarPos(THRESH_MAX, CONTROL, thresh_max.value)

def change_cont_min(x):
    if x < cont_max.value:
        cont_min.value = x
    else:
        cv2.setTrackbarPos(CONT_MIN, CONTROL, cont_min.value)

def change_cont_max(x):
    if x > cont_min.value:
        cont_max.value = x
    else:
        cv2.setTrackbarPos(CONT_MAX, CONTROL, cont_max.value)

def change_focus_v(x):
    if x != focus_v.value:
        focus_v.value = x

def init_windows():
    cv2.namedWindow(DILATE)
    cv2.moveWindow(DILATE, 0, 0)
    cv2.namedWindow(CONTROL)
    cv2.moveWindow(CONTROL, 800, 0)

def init_trackbars():
    cv2.createTrackbar(THRESH_MIN, CONTROL, 0, 255, change_thresh_min)
    cv2.setTrackbarMin(THRESH_MIN, CONTROL, 0)
    cv2.setTrackbarMax(THRESH_MIN, CONTROL, 255)
    cv2.setTrackbarPos(THRESH_MIN, CONTROL, thresh_min.value)

    cv2.createTrackbar(THRESH_MAX, CONTROL, 0, 255, change_thresh_max)
    cv2.setTrackbarMin(THRESH_MAX, CONTROL, 0)
    cv2.setTrackbarMax(THRESH_MAX, CONTROL, 255)
    cv2.setTrackbarPos(THRESH_MAX, CONTROL, thresh_max.value)

    cv2.createTrackbar(CONT_MIN, CONTROL, 0, 50000, change_cont_min)
    cv2.setTrackbarMin(CONT_MIN, CONTROL, 0)
    cv2.setTrackbarMax(CONT_MIN, CONTROL, 50000)
    cv2.setTrackbarPos(CONT_MIN, CONTROL, cont_min.value)

    cv2.createTrackbar(CONT_MAX, CONTROL, 0, 50000, change_cont_max)
    cv2.setTrackbarMin(CONT_MAX, CONTROL, 0)
    cv2.setTrackbarMax(CONT_MAX, CONTROL, 50000)
    cv2.setTrackbarPos(CONT_MAX, CONTROL, cont_max.value)

    cv2.createTrackbar(FOCUS_TB, CONTROL, 0, 100, change_focus_v)
    cv2.setTrackbarMin(FOCUS_TB, CONTROL, 0)
    cv2.setTrackbarMax(FOCUS_TB, CONTROL, 100)
    cv2.setTrackbarPos(FOCUS_TB, CONTROL, focus_v.value)

def init_parameters(cam):
    global CONTROL, thresh_max, thresh_min, cont_max, cont_min
    CONTROL = "{:s} - {:s}".format(CONTROL, str(cam.cam_name))

    t_min, t_max = cam.threshold
    c_min, c_max = cam.contours

    if (t_min is None
        or t_max is None
        or c_min is None
        or c_max is None):
        return False

    thresh_min.value = t_min
    thresh_max.value = t_max

    cont_min.value = c_min
    cont_max.value = c_max

    return True

def accept_params(cam):
    global thresh_max, thresh_min, cont_max, cont_min

    cam.threshold = (thresh_min.value, thresh_max.value)
    cam.contours = (cont_min.value, cont_max.value)

def do_setup(cam):
    ret_val = False

    if not init_parameters(cam):
        print("Bad camera parameters.")
        sys.exit(1)

    init_windows()
    init_trackbars()

    # start process
    frames = Queue()
    grabber_pr = Process(target=grabber_loop,
                         args=(cam.cam_id,
                               frames,
                               working_f,
                               thresh_min,
                               thresh_max,
                               cont_min,
                               cont_max,
                               focus_v))
    grabber_pr.start() # todo uncomment

    while (1):
        while not frames.empty():
            dilate, with_contours = frames.get_nowait()

            cv2.imshow(CONTROL, with_contours)
            cv2.imshow(DILATE, dilate)

        k = cv2.waitKey(1) & 0xFF
        if k == KEY_ESC:
            break
        elif k == KEY_RETURN:
            accept_params(cam)
            ret_val = True
            break

    working_f.value = False
    grabber_pr.terminate()

    cv2.destroyAllWindows()

    return ret_val


def containsDuplicate(nums):
    num_S = set(nums)
    if len(num_S) == len(nums):
        return False
    return True

print(containsDuplicate([1,2,3,4,1]))
#or
def cd(nums):
    num_s = set()
    for i in range(len(nums)):
        if nums[i] in num_s:
            return True
        else:
            num_s.add(nums[i])
    return False

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


#!/usr/bin/env python3

import matplotlib.dates as mdates
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick_ohlc
import pandas as pd
import sys
from heikinashi import HA

if len(sys.argv) < 3:
    print('Usage: {} [CryptoInscriber CSV] [Interval (eg. 1Min)]'.format(sys.argv[0]))
    exit(1)

# Sample: ID, Epoch Timestamp, Price, Amount, Side
# 12713989,1510506649000,696594.73102,0.1805,buy

"""Sample backtrader btfeed.GenericCSVData
data = btfeed.GenericCSVData(
    dataname='mydata.csv',

    fromdate=datetime.datetime(2000, 1, 1),
    todate=datetime.datetime(2017, 12, 31),

    nullvalue=0.0,

    dtformat=('%Y-%m-%d %H:%M:%S'),

    datetime=0,
    open=1,
    high=2,
    low=3,
    close=4,
    volume=-1,
    openinterest=-1
)
"""

# Load Raw Trade Feed CSV
df = pd.read_csv(
    sys.argv[1],
    names=['timestamp', 'price', 'amount', 'side'],
    usecols=[1, 2, 3, 4],
    index_col=0
)
print(df.head())

# Convert Epoch Timestampe to Datetime
df.index = pd.to_datetime(df.index, unit='ms')
print(df.head())

# Resample to Specific Interval and Convert to OHLC
ohlc = df['price'].resample(sys.argv[2]).ohlc()
ohlc.to_csv('out.csv')
print(ohlc.head())


def dfs(l):
    global res
    if l==n: #맨 마지막 지점 도달
        sum = max(money)-min(money)
        if sum<res: #최솟값 갱신
             tmp = set() #세 개가 다 다른 값 조건 -> 집합 & len을 통해 처리
             for x in money:
                tmp.add(x)
                if len(tmp)==3: #3가지 값이 다르다는 조건
                    res=sum

    else:
        for i in range(3):
            money[i]+=ls[l] #더해주고
            dfs(l+1) #내려가고
            money[i]-=ls[l] #백트래킹할 때 다시 빼주고

n = int(input())
ls =[]
for _ in range(n):
    ls.append(int(input()))
money = [0]*3 #a,b,c
res = 2147000000 #차의 최소 갱신
dfs(0)
print(res) #마지막에 출력

섹션7/05. 동전분배하기.py

05. 동전분배하기.py