import scipy.io
import pyproj
import numpy as np
import pickle
import matplotlib.pyplot as plt
from tqdm import tqdm

def AMPS_wind(polygons,fname,icemask):
    mat = scipy.io.loadmat(fname)
    projection = pyproj.Proj("epsg:3031")
    lons,lats = np.meshgrid(mat["ERA_lon"],mat["ERA_lat"])
    x,y = projection.transform(lons,lats)
    zonal_winds = mat["zonal_winds_AMPS"]
    zonal_winds = np.nanmean(zonal_winds[:,:,:,:2],axis=3)
    #zonal_winds = zonal_winds[:,:,[10,11,0,1],1]#np.nanmean(zonal_winds,axis=3)
    #zonal_winds = zonal_winds[:,:,[10,11,0,1],1]#np.nanmean(zonal_winds,axis=3)
    zonal_winds = np.nanmean(zonal_winds,axis=2)
    merid_winds = mat["merid_winds_AMPS"]
    merid_winds = merid_winds[:,:,[6,7,8,9],2]#np.nanmean(merid_winds,axis=3)
    merid_winds = np.nanmean(merid_winds,axis=2)
    winds_by_shelf = {}
    for k in tqdm(polygons.keys()):
        centroid = list(polygons[k][0].centroid.coords)[0]
        dist = np.sqrt((x- centroid[0])**2 + (y- centroid[1])**2)
        radius=250*10**3
        z = np.nanmean(zonal_winds[dist<radius])
        m = np.nanmean(merid_winds[dist<radius])
        a = np.arctan2(m,z)
        winds_by_shelf[k] = z#np.degrees(a)#np.nanmean(np.degrees(a))
    return winds_by_shelf


"""
These are old scripts that I haven't tested or used in a very long while.
"""
import pymysql
import re
import os
import urllib
import sqlite3
import glob
from Bio import SeqIO

# from urllib.request import urlopen  # Python3
import xml.etree.ElementTree as etree
from collections import defaultdict

translation_dict_dna={'A':'T','C':'G','T':'A','G':'C','N':'N'}
valid_fasta_file_extensions=['.fa','.fasta']
valid_gb_file_extensions=['.gb','.genbank','.gbk']

def comp(seq,dictionary=translation_dict_dna):
    """ Standard complement sequence function.

        Returns: the complement sequence
    """
    seq=seq.upper()
    comp=[None]*len(seq)
    for i in range(0,len(seq)):
        comp[i]=dictionary[seq[i]]
    return ''.join(comp)

def revcomp(seq,dictionary=translation_dict_dna):
    """ Standard reverse complement function.

        Returns: the reverse complement
    """
    seq=seq.upper()
    comp=[None]*len(seq)
    for i in range(0,len(seq)):
        comp[len(seq)-1-i]=dictionary[seq[i]]
    return ''.join(comp)

def gc(seq):
    """ Standard GC Content calculator.

        Returns: the GC Content (as a percentage integer) of the sequence
    """
    count=0
    for letter in seq:
        if letter.upper()=='C' or letter.upper()=='G':
            count=count+1
    return (count/float(len(seq)))*100

def get_ext(my_file):
    """
    Just helps determine whether or not a file extension is a
    "FASTA" one or a "GENBANK" one.
    Returns: either "fasta" or "genbank"
    """
    if os.path.splitext(my_file)[1] in valid_fasta_file_extensions:
        return 'fasta'
    elif os.path.splitext(my_file)[1] in valid_gb_file_extensions:
        return 'genbank'

def query_genbank(infile):
    """
    Returns a record given a genbank file.
    The function assumes the file is valid and that it has the fields:
        LOCUS, ACCESSION, ORGANISM, CDS, ORIGIN and SEQUENCE
    If these fields are blank or nonexistent, it will return the record
    with a blank for those fields.

    Args:
        infile: The genbank file

    Returns:
        A dictionary (record) containing:
        {locus, accession, organism, features, sequence}
    """
    sequence=""
    locus_id=""
    accession=""
    organism=""
    features=defaultdict(list)
    records=[]
    seq_flag=False
    warn=False
    regex=re.compile("[atcg]",re.IGNORECASE)
    with open(infile) as f:
        for line in f:
            if line[:5]=="LOCUS":
                locus_id=line[12:12+line[12:].find(' ')]
            elif line[:9]=="ACCESSION":
                accession=line[12:12+line[12:].find('\n')]
            elif line[2:10]=="ORGANISM":
                organism=line[12:12+line[12:].find('\n')]
            elif line[5:8]=="CDS":
                cds=[int(line[21:21+line[21:].find('..')]),
                int(line[21+line[21:].find('..')+2:line.find('\n')])]
                features['cds'].append(cds)
            elif line[0:6]=="ORIGIN":
                seq_flag=True
            if seq_flag==True and line[0:6]!="ORIGIN":
                sequence=sequence+''.join(regex.findall(line))
            if line[:2]=="//":
                if accession not in records:
                    records.append({'locus':locus_id,
                                        'accession':accession,
                                        'organism':organism,
                                        'features':features,
                                        'sequence':sequence.upper()})
                else:
                    warn=True
                features=defaultdict(list)
                sequence=""
                seq_flag=False
    if warn==True:
        print("Warning: duplicate accession numbers found.")
    return records

def get_sequence_from_das(my_db,chromosome,start,end):
    """
    Queries the UCSC DAS server given the database, chromosome and position
    Returns the sequence if it is given valid coordinates, else an empty
    string.

    Args:
        my_db: the database name (can be hg38, etc.)
        chromosome: given as "chr1," "chr2," etc.
        start: the raw start position from the beginning of the chromosome
        end: The raw end position

    Returns:
        Sequence from the DAS

    See:
        http://stackoverflow.com/questions/22328319/python-fetch-sequence-from-das-by-coordinates
    """
    sequence=''
    base = "http://genome.ucsc.edu/cgi-bin/das/%s/dna?segment="%my_db
    url = base + chromosome + ':' + str(start) + ',' + str(end)
    # xml = urlopen(url).read() # Python3
    xml = urllib.urlopen(url).read() # Python2 module
    if xml != '':
        w = open('temp.xml', 'w')
        w.write(xml)
        w.close()
        doc = etree.parse('temp.xml',parser=etree.XMLParser())
        if doc != '':
            # should only return one sequence, right???
            sequence = doc.findall('./SEQUENCE/DNA')[0].text.replace('\n','')
        else:
            print('THE SEQUENCE DOES NOT EXIST FOR GIVEN COORDINATES')
    return sequence

def query_refseq_ucsc(refseq_query,exon_specific=False,my_db="hg38",my_user="genome",
                      my_host="genome-mysql.cse.ucsc.edu"):
    """
    Returns a record of the gene associated with the refseq accession number
    (ie. NM_000000). The record contains information about the gene, including:
        name, accession, cds_start, cds_end, sequence, strand, chromosome

    Args:
        refseq_query: a refseq accession number string
        exon_specific: sometimes we don't need the sequence, but rather
            the exons to avoid targeting sequences that don't exist prior
            to processing. Setting this flag to True ensures a return of
            an array rather than a string in the dictionary.
        my_db: Defaults to the latest human hg38 database. Can be any
            database in UCSC
        my_user: Defaults to "genome" so unless you're a superstar,
            don't change it.
        my_host: Defaults to "genome-mysql.cse.ucsc.edu."
    Returns:
        A dictionary containing:
            name, accession, cds_start, cds_end, sequence, strand, chromosome
            If "exon_specific" is True, the 'sequence' will be an array
            containing individual exons instead of a sequence string.
    """
    myDB = pymysql.connect(host=my_host,user=my_user,db=my_db)
    cur = myDB.cursor()
    record = dict()
    seq = ""
    refseq_query = refseq_query[:refseq_query.find('.')] # we are unconcerned with versions
    try:
        cur.execute("select r.chrom, r.exonCount, r.exonStarts, r.exonEnds, \
                     r.strand, \
                     c.name, \
                     f.geneName \
                      from cds c\
                       join gbCdnaInfo i on c.id = i.cds \
                       join refGene r on r.name = i.acc \
                       join refFlat f on f.name = i.acc \
                    where i.acc = '%s'"%refseq_query)
        result = cur.fetchone()
        if result is None:
            return -1
        if result[5] != 'n/a':
            cds_start = int(result[5][:result[5].find('..')])
            cds_end = int(result[5][(result[5].find('..')+2):])
        else:
            cds_start = 0
            cds_end = 0
        num_exons = result[1]
        exon_arr = [0 for i in range(num_exons)]
        exon_start = result[2].split(',')
        exon_end = result[3].split(',')
        strand = 0
        if result[4] == '-':
            strand = -1
            for i in range(0,num_exons):
                exon = revcomp(get_sequence_from_das(my_db,result[0],
                               (int(exon_start[num_exons-(i+1)])+1),
                                exon_end[num_exons-(i+1)]).upper())
                exon_arr[i] = exon
                seq=seq+exon
        else:
            strand = 1
            for i in range(0,num_exons):
                exon = get_sequence_from_das(my_db,result[0],(int(exon_start[i])+1),
                                  exon_end[i]).upper()
                exon_arr[i] = exon
                seq=seq + exon
        if (exon_specific):
            record={'name':result[6],'accession':refseq_query,'cds_start':cds_start,
                'cds_end':cds_end,'chromosome':result[0],
                'sequence':exon_arr,'strand':strand}
        else:
            record={'name':result[6],'accession':refseq_query,'cds_start':cds_start,
                'cds_end':cds_end,'chromosome':result[0],
                'sequence':seq,'strand':strand}
    except IndexError:
        print("cannot find sequence!")
    return record

def get_closest_exon(chromosome,pos1,pos2,db="ensembl.sql"):
    """
    Gets the closest exons (max 100kb away) from the position specified.
    It uses (and creates if necessary)
    """

    gene_start = pos1 if pos1 < pos2 else pos2
    gene_end = pos2 if pos2 > pos1 else pos1

    con = sqlite3.connect(db)
    cur = con.cursor()
    cur.execute("SELECT * FROM exons WHERE chromosome = '{0}' AND \
                ({1} BETWEEN exon_start-100000 AND exon_end+100000 OR \
                {2} BETWEEN exon_start-100000 AND exon_end+100000)".format(
        chromosome,gene_start,gene_end
    ))
    ret = cur.fetchall()

    min_dist = 100000
    min_gene = ""

    for i in range(0,len(ret)):
        exon_start = int(ret[i][4])
        exon_end = int(ret[i][5])
        gene = ret[i][2]
        if((exon_start <= gene_start <= exon_end) or (exon_start <= gene_end <= exon_end)):
            return 0, gene # not SUPER accurate, we avoid alternative transcripts
        else:
            dist = min(abs(gene_end-exon_start),abs(gene_start-exon_end))
            if(dist < min_dist):
                min_dist = dist
                min_gene = gene
    return min_dist, min_gene

def create_refseq_exon_sqlite(infile, db="ensembl.sql"):
    """
    Creates the exon sqlite table from results downloaded from biomart.
    To get this data, go to: http://www.biomart.org/biomart/martview/
    and select your species and dataset. I selected attributes:
        Ensembl Gene ID,
        Exon Chr Start (bp)
        Exon Chr End (bp)
        Associated Gene Name
        Chromosome Name
        Strand

    Args:
        infile: file downloaded (tab-delimited) from biomart that includes
        exon position information
        db: name of the sql file to be created
    """
    con = sqlite3.connect(db)
    cur = con.cursor()
    try:
        # create the exon table
        cur.execute("""CREATE TABLE exons(key INTEGER PRIMARY KEY AUTOINCREMENT, \
                gene_id CHARACTER(20), \
                gene_name TEXT COLLATE NOCASE, \
                chromosome CHARACTER(5), \
                exon_start INTEGER(20), \
                exon_end INTEGER(20), \
                strand INTEGER(1))""")
        con.commit()

        with open(infile,'rb') as p:
            for line in p:
                line = line.decode(encoding='UTF-8',errors='strict')
                line = line.replace("\n","").split('\t')

                try:
                    cur.execute("""INSERT INTO exons( \
                            gene_id,gene_name,chromosome,exon_start,exon_end,strand) \
                            VALUES(?,?,?,?,?,?)""", \
                            (line[0],line[4],line[3],line[1],line[2],line[5]))
                except sqlite3.IntegrityError:
                    print("choking on line:")
                    print(line)
        con.commit()
        print("Done creating the exon sqlite tables.")
    except sqlite3.OperationalError:
        pass
        # print("Tables already made!")

def mutate_sequence(sequence,mismatch):
    """
    Returns the reference given mismatches (as formatted by standard
    Bowtie Output). The Bowtie mismatch string follows the
    "offset:reference-base>read-base" format, and assumes the given
    sequence is the read string.

    Args:
        sequence: The unadulterated read sequence
        mismatch: The mismatch pattern

    Returns:
        sequence after mismatch pattern is applied
    """
    if(not mismatch): # if there is no mismatch, return original sequence!
        return sequence

    mismatch = mismatch.split(',') # parse mismatch pattern
    new_sequence = ['']*len(sequence) # empty placeholder for new sequence
    positions = {} # dictionary that ultimately holds offset:character

    # find mismatches and add to dictionary
    for i in range(0,len(mismatch)):
        positions[int(mismatch[i][:mismatch[i].find(':')])] = \
        mismatch[i][mismatch[i].find(':')+1:mismatch[i].find('>')]

    for i in range(0,len(sequence)):
        if i in positions:
            new_sequence[i] = positions[i]
        else:
            new_sequence[i] = sequence[i]
    new_sequence = "".join(new_sequence)
    return new_sequence

def fix_fasta_headers(infile, outfile, regex_pattern):
    """
    Formats a fasta file header using regex pattern.
    So instead of the normal header, new headers are just
    the first found instance of the regex capture.

    Parameters
    ----------
    infile : basestring
    outfile : basestring
    regex_pattern : basestring

    Returns
    -------

    """

    o = open(outfile, 'w')
    with open(infile,'r') as f:
        for line in f:
            if line[0] == '>':
                o.write(">{0}\n".format(re.findall(regex_pattern, line)[0]))
            else:
                o.write(line)

def append_fasta(some_path, out_file, ext='fa'):
    """
    Appends/concatenates fasta files in a path to each other.

    Parameters
    ----------
    some_path : basestring
    out_file : basestring
    ext : basestring
        default: 'fa'
    Returns
    -------

    """
    o = open(out_file, 'w')
    for fasta_file in glob.glob(some_path+"*.{}".format(ext)):
        print(fasta_file)
        if fasta_file != out_file:
            with open(fasta_file, 'r') as f:
                for line in f:
                    o.write(line)

def get_seq_dict_from_file(f, seq_ids=[], file_type='fasta', equal=True):
    """
    Returns dictionary of {name : sequence}

    Parameters
    ----------

    f : basestring
        file location of a fasta file
    seq_ids : list
        list of sequence ids to search. Empty field returns all sequences
    equal : bool
        True if seq_id needs to be identical
        False if we just have partial identifier
    file_type : basestring
        default "fasta" type file
    Returns
    -------
    records : dict
        {name:sequence}
    """
    records = {}
    for record in SeqIO.parse(f, file_type):
        if len(seq_ids) > 0:
            for name in seq_ids:
                if equal:
                    if name == record.id:
                        records[record.id] = record.seq
                else:
                    if name in record.id:
                        records[record.id] = record.seq
        else:
            records[record.id] = record.seq
    return records

def get_seq_sizes(f, seq_ids=[], file_type='fasta', equal=True):
    """
    Returns dictionary of {name : seqsize}

    Parameters
    ----------
    f
    seq_ids
    equal
    file_type

    Returns
    -------

    """
    lengths = {}
    records = get_seq_dict_from_file(f, seq_ids, file_type, equal)

    for seq_id, sequence in records.iteritems():
        lengths[seq_id] = len(sequence)
    return lengths

def write_chrom_sizes(
        infile, outfile, seq_ids=[], file_type='fasta', equal=True
):
    """
    Writes a chrom sizes file, useful for any software that requires
    a chrom.sizes tabbed file on custom genomes.

    Parameters
    ----------
    infile : basestring
    outfile : basestring
    seq_ids : list
    file_type : basestring
    equal : bool

    Returns
    -------

    """
    chrom_sizes = get_seq_sizes(infile, seq_ids, file_type, equal)
    with open(outfile, 'w') as o:
        for chrom, length in chrom_sizes.iteritems():
            o.write("{}\t{}\n".format(chrom, length))


#coding=utf-8
import httplib2

from apiclient.discovery import build
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.file import Storage
from oauth2client.tools import run

TOKEN_FILE_NAME = 'analytics.dat'

class GAAPI(object):

    def __init__(self, client_id, client_secret, redirect_uri='http://localhost:8080/oauth2',
                 user_agent='analytics-api-v3-awesomeness'):

        flow = OAuth2WebServerFlow(
            client_id=client_id,
            client_secret=client_secret,
            scope='https://www.googleapis.com/auth/analytics.readonly',
            redirect_uri=redirect_uri,
            user_agent=user_agent
        )

        storage = Storage(TOKEN_FILE_NAME)
        self.credentials = storage.get()

        if not self.credentials or self.credentials.invalid:
          self.credentials = run(flow, storage)

        self.service = self._initialize_service()

        self.profile_id = self.get_first_profile_id()

    def _initialize_service(self):
        http = self.credentials.authorize(httplib2.Http())
        return build('analytics', 'v3', http=http)

    def get_first_profile_id(self):
        # Get a list of all Google Analytics accounts for this user
        accounts = self.service.management().accounts().list().execute()

        if accounts.get('items'):
            # Get the first Google Analytics account
            firstAccountId = accounts.get('items')[0].get('id')

            # Get a list of all the Web Properties for the first account
            webproperties = self.service.management().webproperties().list(accountId=firstAccountId).execute()

            if webproperties.get('items'):
                # Get the first Web Property ID
                firstWebpropertyId = webproperties.get('items')[0].get('id')

                # Get a list of all Views (Profiles) for the first Web Property of the first Account
                profiles = self.service.management().profiles().list(
                    accountId=firstAccountId,
                    webPropertyId=firstWebpropertyId).execute()

                if profiles.get('items'):
                    # return the first View (Profile) ID
                    return profiles.get('items')[0].get('id')

        return None

    def callAPI(self, date_from, date_to, metrics='ga:sessions', dimensions=None, sort=None, filters=None,
                segment=None, sampling_level=None, start_index=None, max_results=None, output=None, fields=None):

        if self.profile_id is None:
            return None

        params = {
            "ids": 'ga:' + self.profile_id,                 # айдишники профилей
            "start_date": date_from.strftime("%Y-%m-%d"),   # дата начала
            "end_date": date_to.strftime("%Y-%m-%d"),       # дата конца
            "metrics": metrics,
        }

        dimensions is not None and params.update({"dimensions": dimensions})
        sort is not None and params.update({"sort": sort})
        filters is not None and params.update({"filters": filters})
        segment is not None and params.update({"segment": segment})
        sampling_level is not None and params.update({"samplingLevel": sampling_level})
        start_index is not None and params.update({"start-index": start_index})
        max_results is not None and params.update({"max-results": max_results})
        output is not None and params.update({"output": output})
        fields is not None and params.update({"fields": fields})

        return self.service.data().ga().get(**params).execute()


import player as p
import ui
import Country as c
import data

data.playernum = input('플레이어 몇 명이서 싸울지 입력 하세요(기본값:100)>>')
data.min_hp = input('최소 hp를 입력 하세요(기본값:10)>>')
data.max_hp = input('최대 hp를 입력 하세요(기본값:100)>>')
data.min_atk = input('최소 공격력을 입력 하세요(기본값:1)>>')
data.max_atk = input('최대 공격력을 입력 하세요(기본값:30)>>')
data.min_left_heal = input('최소 구급상자 개수를 입력 하세요(기본값:0)>>')
data.max_left_heal = input('최대 구급상자 개수를 입력 하세요(기본값:5)>>')
data.guild = input('길드 창립을 허용하시려면 y를 입력하세요(기본값:창립 불가)>>')

try:
    if data.guild.lower() == 'y':
        data.guild = True

    data.playernum, data.min_hp, data.max_hp, data.min_atk, data.max_atk, data.min_left_heal, data.max_left_heal \
        = int(data.playernum), int(data.min_hp), int(data.max_hp), int(data.min_atk), int(data.max_atk), int(data.min_left_heal), int(
        data.max_left_heal)
    data.players = p.randomize_players(data.playernum, data.min_hp, data.max_hp, data.min_atk, data.max_atk, data.min_left_heal, data.max_left_heal)
except ValueError:
    print('잘못된 값이 있습니다. 모든 값을 기본값으로 설정합니다.')
    data.players = p.randomize_players()

before_orged_player = None
before_orged_guilds = None

while True:
    orged_guilds = c.organize_guild(data.guilds)
    orged_players = p.organize_players(data.players)

    ui.print_rank(orged_players, before_orged_player)
    print('-' * 20)
    ui.print_guild(orged_guilds, before_orged_guilds)

    print(f'총 플레이어 명수 : {len(data.players)}, 길드 개수 : {len(data.guilds)}, 길드 창립 허용 여부 : {data.guild}')

    input('다음 턴을 실행 하려면 엔터>>')

    data.kings.append(orged_players[-1].copy())

    before_orged_player = orged_players.copy()
    before_orged_guilds = orged_guilds.copy()

    average_hp = p.get_average(data.players, 'hp')
    average_atk = p.get_average(data.players, 'atk')

    for i in data.players:
        i.select(average_hp, average_atk, data.players, data.guilds, orged_players[-10:],  data.guild)

    if len(data.players) == 1:
        print(f'{data.players[0].id}번 플레이어님이 승리하셨습니다!')
        break
    elif len(data.players) == 0:
        print('아무도 승자가 되지 못했습니다...')
        break

    print('\n')

if input('역대 1등 목록을 보시려면 y를 입력하고, 아니면 그냥 엔터를 눌러주세요>>').lower() == 'y':
    for i in data.kings:
        i.print_info()
        print()
    print(f'최종 승지 : {data.players[0].id}번 플레이어')
    data.players[0].print_info()


def order(sentence):
  # code here
    temp = sentence.split(" ")
    lst = []
    result = ""
    for i in temp:
        for char in i:
            if char.isnumeric():
                if int(char) > 0:
                    lst.append((int(char), i))
    lst.sort()
    for i in lst:
        result += i[1] + " "

    return result[:-1]


# Write a program that prints out the following list:
#
# ['a', 'bb', 'ccc', 'dddd', 'eeeee', 'ffffff', ...]
# Output data format
# The program should print the specified list.
#
# Note. The last item in the list consists of 26 z characters.
alphabet = 'abcdefghijklmnopqrstuvwxyz'
list_alphabet = []
count = 1
for i in alphabet:
    list_alphabet.append(i * count)
    count += 1
print(list_alphabet)


from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import (ascii, bytes, chr, dict, filter, hex, input, int, map, next, oct, open, pow, range, round, str, super, zip)

import os
import unittest

import json

import foostache

class FoostacheTestCase(unittest.TestCase):

    def setUp(self):
        here = os.path.abspath(os.path.dirname(__file__))
        with open(os.path.join(here, "language", "examples", "sample1.fs"), encoding="utf_8") as f:
            self.sample1fs = f.read()
        with open(os.path.join(here, "language", "examples", "sample1.json"), "rb") as f:
            self.sample1json = json.load(f)
        with open(os.path.join(here, "language", "examples", "sample1.output"), encoding="utf_8") as f:
            self.sample1output = f.read()
        self.maxDiff = None

    def test_sample1(self):
        template = foostache.Template(self.sample1fs)
        output = template.render(self.sample1json)
        self.assertEqual(self.sample1output, output)

if __name__ == "__main__":
    unittest.main()


#!/usr/bin/python

import sys
from tweety import find_post
from algorithms.kmp import kmp
from algorithms.boyer_moore import boyer_moore
from algorithms.regex import regex

def main(algorithm, userid, keyword):
    """
    get post and flag spam
    :param algorithm: choice of algorithm, 1:kmp, 2:boyer moore, 3:regex
    :param username: username of twitter to parse
    :param keyword: keyword to search in post
    """
    posts = find_post(userid)
    flags = []

    if algorithm == '1':                              # kmp
        for i in range(len(posts)):
            idx = kmp(posts[i], keyword)
            if idx != -1:
                flags.append([])
                flags[len(flags) - 1].append(i)
                flags[len(flags) - 1].append(idx)
                flags[len(flags) - 1].append(idx + len(keyword))

    elif algorithm == '2':                            # boyer_moore
        for i in range(len(posts)):
            try:
                idx = int(boyer_moore(posts[i], keyword))
                if idx != -1:
                    flags.append([])
                    flags[len(flags) - 1].append(i)
                    flags[len(flags) - 1].append(idx)
                    flags[len(flags) - 1].append(idx + len(keyword))
            except:
                i = i

    else:                            # regex
        for i in range(len(posts)):
            idx = regex(posts[i], keyword)
            if idx != -1:
                flags.append([])
                flags[len(flags) - 1].append(i)
                flags[len(flags) - 1].append(idx)
                flags[len(flags) - 1].append(idx + len(keyword))

    # flagging spam
    for flag in flags:
        posts[flag[0]] = posts[flag[0]][:flag[1]] + '' + posts[flag[0]][flag[1]:flag[2]] + '' + \
                         posts[flag[0]][flag[2]:]

    for post in posts:
        if 'strong' in post:
            p = '[spam] ' + post
            p = p.encode("utf8")
            print(p)
        else:
            post = post.encode("utf8")
            print(post)

if __name__ == '__main__':
    main(sys.argv[1], sys.argv[2], sys.argv[3])


def solution(babbling):
    answer = 0
    speak = ["aya", "ye", "woo", "ma"]
    for i in babbling:
        for j in speak:
            if j*2 not in i:
                i = i.replace(j,'')
        if i.strip() == '':
            answer += 1
    return answer


class NegativeException(Exception):
    pass

def simple_function(x):
    if x>0:
        return x
    else:
        raise NegativeException

def cascade_function(x):
    try:
        simple_function(x)
    except NegativeException:
        raise ValueError

assert simple_function(2) == 2

raised = False
try:
    simple_function(-2)
except NegativeException:
    raised = True

def finally_function(x):
    try:
        cascade_function(x)
    except ValueError:
        return True

assert raised

negative_raised = False
value_raised = False
try:
    cascade_function(-2)
except NegativeException:
    negative_raised = True
except ValueError:
    value_raised = True

assert not negative_raised
assert value_raised

assert finally_function(-5)


from exploits.bombs.fork import fork_bombs
from test.exploits.dummy_output import DummyOutput

def test_file_formats():
    file_formats = ['bash', 'bat', 'c', 'cc', 'cs', 'erl', 'fasm', 'go',
                    'hs', 'html', 'java', 'js', 'lsp', 'lua', 'mdb', 'php',
                    'pl', 'py', 'r', 'rb', 'rs', 's', 'scm', 'sh', 'vbs']

    for f in file_formats:
        output = DummyOutput()
        fork_bombs.options['file_format'] = f
        fork_bombs.run(output)
        assert len(output) == 1


import boto3
import json
from django.core.serializers.json import DjangoJSONEncoder

import xml.etree.cElementTree as et

from django.conf import settings

def is_svg(f):
    tag = None
    try:
        for event, el in et.iterparse(f.open(mode='r'), ('start',)):
            tag = el.tag
            break
    except et.ParseError:
        pass
    return tag == '{http://www.w3.org/2000/svg}svg'

class DynamoDbModuleUtility:
    """
        Get Module permission from Dynamo db and access.
    """

    @staticmethod
    def get_module_permissions(airport_code):
        if settings.AIRPORT_PLAN_ENABLE:
            if airport_code not in settings.AIRPORT_PLANS:
                DynamoDbModuleUtility.fetch_module_permissions(airport_code)

    @staticmethod
    def fetch_module_permissions(airport_code):
        """
            Used to return all module permissions to save in session
        """
        if settings.AIRPORT_PLAN_ENABLE:
            dynamodb = boto3.resource('dynamodb', region_name=settings.AWS_DEFAULT_REGION)
            airport_table = dynamodb.Table(settings.APP_PREFIX + 'airport')
            airport_key = '{0}_{1}'.format(airport_code, settings.BACKEND_ID)
            airport_object = airport_table.get_item(Key={"id": airport_key})
            if 'Item' in airport_object.keys() and 'plan' in airport_object['Item']:
                settings.AIRPORT_PLANS[airport_code] = json.loads(json.dumps(
                    airport_object['Item']['plan'], cls=DjangoJSONEncoder))
            else:
                settings.AIRPORT_PLANS[airport_code] = {}

    @staticmethod
    def return_module_attribute(airport_code, module_key, attribute):
        """
            Check if the module key exists in dynamodb data
        """
        DynamoDbModuleUtility.get_module_permissions(airport_code)
        if settings.AIRPORT_PLAN_ENABLE and airport_code in settings.AIRPORT_PLANS:
            plan = settings.AIRPORT_PLANS[airport_code]
            for module in plan['modules']:
                if module['key'] == module_key:
                    if 'attributes' in module.keys() and attribute in module['attributes'].keys():
                        return module['attributes'][attribute]
        return None

    @staticmethod
    def get_plan_data(airport_code):
        """
            Return module based on module permissions
        """
        DynamoDbModuleUtility.get_module_permissions(airport_code)
        if settings.AIRPORT_PLAN_ENABLE:
            if airport_code in settings.AIRPORT_PLANS:
                return settings.AIRPORT_PLANS[airport_code]
            return {}
        else:
            return {}

    @staticmethod
    def has_module_permissions(airport_code, module_key):
        """
            Return module based on module permissions
        """
        DynamoDbModuleUtility.get_module_permissions(airport_code)
        if settings.AIRPORT_PLAN_ENABLE:
            if airport_code in settings.AIRPORT_PLANS:
                plan = settings.AIRPORT_PLANS[airport_code]
                for module in plan['modules']:
                    if module['key'] == module_key and module.get('enabled', 'false') == 'true':
                        return True
                return False
            return False
        else:
            return True

    @staticmethod
    def has_sources_permissions(airport_code, source_key):
        """
            Return source based on sources permissions
        """
        DynamoDbModuleUtility.get_module_permissions(airport_code)
        if settings.AIRPORT_PLAN_ENABLE:
            if airport_code in settings.AIRPORT_PLANS:
                plan = settings.AIRPORT_PLANS[airport_code]
                for source in plan['sources']:
                    if source['key'] == source_key and source.get('enabled', 'false') == 'true':
                        return True
                return False
            return False
        else:
            return True


# You are going to be given an array of integers. Your job is to take that
# array and find an index N where the sum of the integers to the left of N
# is equal to the sum of the integers to the right of N. If there is no index
# that would make this happen, return -1.

def find_even_index(arr):  # define the function
    for i in range(len(arr)):
        # For loop uses the RANGE function to go from 0 to the length of the array.
        if sum(arr[:i]) == sum(arr[i + 1:]):
            # sum() is an inbuilt function in python that adds
            # all the elements in list,set and tuples and returns
            # the value
            # the [:i] will get all of the elements of the array from the start  UP TO BUT NOT INC position i
            # the [i+1] will get all of the elements of the array from the number FROM BUT NOT INC poistion i+1

            return i
    return -1

find_even_index([1, 2, 3, 4, 3, 2, 1])


from asyncio.windows_events import NULL
import json
import numpy as np
import cv2
import colorsys
import random
import os
import shutil
from sklearn.neighbors import RadiusNeighborsClassifier

"""This runs with traincolors.json and testcolors.json which depends on the train and test folders
    hexcolors.json are the colors I webscrapped converted to rgb """

def train_color_data():
    """hsv values are H: 0-179, S: 0-255, V:0-255
    dictionary of bounds : [color]: [array of np.array]
    generating train data by collect points within the multiple ranges"""

    dic_lowerbounds = {"red": [np.array([0, 138, 60],np.uint8), np.array([171, 138, 60],np.uint8)], "orange": [np.array([10, 150, 165],np.uint8)], \
                    "yellow": [np.array([24, 138, 130],np.uint8)], "green": [np.array([37, 138, 60],np.uint8)], "blue": [np.array([90, 138, 60],np.uint8)],\
                    "purple": [np.array([130, 138, 60],np.uint8)], "gray": [np.array([0, 0, 60],np.uint8)], \
                    "black": [np.array([0, 0, 0],np.uint8)], "white": [np.array([0, 0, 214],np.uint8)], "brown": [np.array([9,78,60],np.uint8)]
                    }

    dic_upperbounds = {"red": [np.array([9, 255, 255],np.uint8), np.array([179, 255, 255],np.uint8)], "orange": [np.array([23, 255, 255],np.uint8)], \
                    "yellow": [np.array([30, 255, 255],np.uint8)], "green": [np.array([77, 255, 255],np.uint8)], "blue": [np.array([115, 255, 255],np.uint8)],\
                    "purple": [np.array([165, 255, 255],np.uint8)], "gray": [np.array([179, 50, 130],np.uint8)], \
                    "black": [np.array([179, 255, 45],np.uint8)], "white": [np.array([179, 26, 255],np.uint8)], "brown": [np.array([23,255,160])]}

    img_h, img_w, img_c = (100,100,3)
    dirct = 'train'
    wrtcdataf = dirct + "colors.json"
    mydata ={}

    '''recreating hsv database'''

    for color in dic_lowerbounds:
        #enter train folder
        if os.path.exists(dirct) is False:
            os.makedirs(dirct)
        os.chdir(dirct)

        #delete old color folder make new folder
        if os.path.exists(color) is True:
            shutil.rmtree(color)

        os.makedirs(color)
        os.chdir(color)

        mydata[color] = []
        for datagen in range(0,200):
            #for multiple thresholds

            for sett in range(0,len(dic_lowerbounds[color])):
                H = float(random.randint(dic_lowerbounds[color][sett][0],dic_upperbounds[color][sett][0])/179  )
                S = float(random.randint(dic_lowerbounds[color][sett][1],dic_upperbounds[color][sett][1])/255  )
                V = float(random.randint(dic_lowerbounds[color][sett][2],dic_upperbounds[color][sett][2])/255  )

                r,g,b = colorsys.hsv_to_rgb(H,S,V)
                R,G,B = int(r*255),int(g*255),int(b*255)
                mydata[color].append([R,G,B])

                newcolorshade = np.full((img_h,img_w,img_c), [B,G,R],dtype = np.uint8)
                cv2.imwrite(str([R,G,B]) + ".jpg" ,newcolorshade)

        os.chdir(os.path.abspath(os.pardir))

    json_object = json.dumps(mydata)
    with open(wrtcdataf, "w") as outfile:
        outfile.write(json_object)

"""will update the datafile based on the uploaded rgb images in the color folder"""
def update_colordatafile(dirct):
    tst_data = {}
    colorsdirect = ["red", "orange", "yellow", "green", "blue", "purple", "brown", "gray", "white", "black"]
    wrtcdataf = dirct + "colors.json"

    for clrlabel in colorsdirect:
        #enter test or train directory
        if os.path.exists(dirct) is True:
            os.chdir(dirct)
            if os.path.exists(clrlabel) is True:
                tst_data[clrlabel] = []
                l=os.listdir(clrlabel)
                filesnoext=[x.split('.')[0] for x in l]

                for filenam in filesnoext:
                    colorval = json.loads(filenam)
                    tst_data[clrlabel].append(colorval)

            os.chdir(os.path.abspath(os.pardir))

    json_object = json.dumps(tst_data)
    with open(wrtcdataf, "w") as outfile:
        outfile.write(json_object)

"""classifying data and running an accuracy check based on test data """
def color_rknn_classify(traindatafile,testdatafile):

  shadesofcolordata = json.load(open(traindatafile))
  testdata = json.load(open(testdatafile))

  xtest = []
  ylabeltest = []
  xdata = []
  ylabel = []

  kradius = 100
  for colorlabel in shadesofcolordata:
    for shadevalue in shadesofcolordata[colorlabel]:
      xdata.append(shadevalue)
      ylabel.append(colorlabel)

  colorneigh = RadiusNeighborsClassifier(radius = kradius, weights = "distance",outlier_label = "gray")
  colorneigh.fit(xdata, ylabel)

  for colorlabel in testdata:
     xtest = []
     ylabeltest = []
     for shadevalue in testdata[colorlabel]:
      xtest.append(shadevalue)
      ylabeltest.append(colorlabel)

     ypredict = colorneigh.predict(xtest)
     print(f"{colorlabel}:  {colorneigh.score(xtest, ylabeltest)}")

if __name__ == "__main__":

    newTraindata = False
    newdatadirct = NULL
    knnTest = True

    if newTraindata is True:
        train_color_data()
    if newdatadirct is not NULL:
        print(newdatadirct)
        update_colordatafile(newdatadirct)
    if knnTest is True:
        color_rknn_classify("traincolors.json","testcolors.json")


import random

from utlis import run_time

class HeapSort(object):

    @staticmethod
    def less(array, i, j):
        """
        比较array中i和j索引位置对象的大小
        :param array: 待比较数组array
        :param i: array索引
        :param j: array索引
        :return: True/False
        """
        return array[i] < array[j]

    @staticmethod
    def exch(array, m, n):
        """
        交换array中索引m和索引n处的值
        :param m: array索引
        :param n: array索引
        :return: None
        """
        array[m], array[n] = array[n], array[m]

    def is_sorted(self, array):
        """
        判断array是否有序，有序返回True，无序返回False
        :param array: 可迭代对象
        :return: True/False
        """
        for i in range(2, len(array)):
            if self.less(array, i, i - 1):
                return False
        return True

    def sink(self, array, k, n):
        while 2 * k <= n:
            child = 2 * k
            if 2 * k + 1 <= n and self.less(array, child, child + 1):
                child += 1
            if not self.less(array, k, child):
                break
            self.exch(array, k, child)
            k = child

    @run_time
    def sort(self, array):
        length = len(array) - 1
        for i in range(1, int(length / 2) + 1)[::-1]:
            self.sink(array, i, length)
        while length > 1:
            self.exch(array, 1, length)
            length -= 1
            self.sink(array, 1, length)

if __name__ == '__main__':
    heap_sort = HeapSort()
    # data = [''] + ['S', 'O', 'R', 'T', 'E', 'X', 'A', 'M', 'P', 'L', 'E']
    # data = [random.choice('ABCDEFGHIJKLMNOPQRSTUVWXYZ') for i in range(10000)]
    data = [''] + [random.random() for i in range(100000)]
    # print(data)
    heap_sort.sort(data)
    print(heap_sort.is_sorted(data))
    # print(data)


import pandas as pd

if __name__ == "__main__":
    # create a dictionary of our data:
    data = {
        "calories": [420, 380, 390],
        "duration": [50, 40, 45]
    }

    # load data into a DataFrame object:
    df = pd.DataFrame(data)

    # print dataframe
    print(df)


from flask import Flask
import datetime

app = Flask(__name__)

@app.route('/get_time/now')
def get_time():
    time = datetime.datetime.now()
    return f"Точное время: {time}"

if __name__ == "__main__":
    app.run(port=5555, debug=True)


#!/usr/bin/env python3
import sys, os, getopt
import biocell

COMMAND_PROCESS_XML_TEMPLATE = 'command-process-xml-template'
COMMAND_PROCESS_XML_MODEL = 'command-process-xml-model'
COMMAND_COMPILE_CPP_MODEL = 'command-compile-cpp-model'
COMMAND_RUN_MODEL = 'command-run-model'
COMMAND_ALL_COMMANDS = 'command-all-commands'
TEMPLATE_FILE = 'template-file'
XML_FILE = 'xml-file'
PARMS = 'parms'
MODEL = 'model'
MODEL_DIR = 'model-dir'
BUILD_DIR = 'build-dir'
CPP_DIR   = 'cpp-dir'
CMD_TIMEOUT = 'cmd-timeout'

def reassign_paths( args ):
    args[ TEMPLATE_FILE ] = os.path.join( args[ MODEL_DIR] , args[ MODEL ] + '-template.xml' )
    args[ XML_FILE ] = os.path.join( args[ MODEL_DIR] , args[ MODEL ] + '.xml' )
    return

def usage( argv, args ):
    print( """
%s: run biological models described with XML using the biocellion agent based simulation system.
    The XML model description file may be specified directly via the --xml-file option, or
    it make be created from a template XML file using the --template-file option and repeated use
    of the --parm option.
""" % ( argv[ 0 ], ) )
    print( "usage: %s -A -T -X -C -R -p var=val -t template-file -x xml-file -m model-name -d model-dir -c cpp-dir -b build-dir -o cmd-timeout" % (argv[0], ) )
    print( )
    print( "Choose one or more commands." )
    print( "----------------------------" )
    print( "-A | --all-commands              # process all starting with template xml model file, ending with running model; default: %s" % ( str( args[ COMMAND_ALL_COMMANDS ] ) , ) )
    print( "-T | --process-xml-template      # process template xml model file into xml model file; default: %s" % ( str( args[ COMMAND_PROCESS_XML_TEMPLATE ] ) , ) )
    print( "-X | --process-xml-model         # process xml model file into cpp model files; default: %s" % ( str( args[ COMMAND_PROCESS_XML_MODEL ] ) , ) )
    print( "-C | --compile-cpp-model         # compile cpp model files into model library file; default: %s" % ( str( args[ COMMAND_COMPILE_CPP_MODEL ] ) , ) )
    print( "-R | --run-model                 # run the model; default: %s" % ( str( args[ COMMAND_RUN_MODEL ] ) , ) )
    print( )
    print( "Command options" )
    print( "---------------" )
    print( "XML specifications" )
    print( "-t | --template-file file-name   # name of input model template XML file; default: %s" % (args[ TEMPLATE_FILE ], ) )
    print( "-p | --parm parm=value           # name and value of parameter for the model; may be specified more than once; default: %s" % ( str( args[ PARMS ] ) , ) )
    print( "-x | --xml-file file-name        # name of output model XML file; default: %s" % (args[ XML_FILE ], ) )
    print( "-m | --model-name model-name     # descriptor for model; default: %s" % (args[ MODEL ], ) )
    print( "-d | --model-dir model-dir       # location of template and model files; default: %s" % (args[ MODEL_DIR ], ) )
    print( "Use -t and -x OR -m and -d.  Don't mix them." )
    print( "-c | --cpp-dir cpp-dir           # location of cpp model library files; default: %s" % (args[ CPP_DIR ], ) )
    print( "-b | --build-dir build-dir       # directory to create with c++ code; default: %s" % (args[ BUILD_DIR ], ) )
    print( "-o | --command-timeout seconds   # seconds to let the subprocess run the simulation; default: %s" % (args[ CMD_TIMEOUT ], ) )
    print( "-h | -? | --help                 # show this message and quit" )
    print( )
    print( "Arguments received: " + " ".join( argv ) )
    print( )
    return

def read_args( argv, args ):
    args[ COMMAND_PROCESS_XML_TEMPLATE ] = False
    args[ COMMAND_PROCESS_XML_MODEL ] = False
    args[ COMMAND_COMPILE_CPP_MODEL ] = False
    args[ COMMAND_RUN_MODEL ] = False
    args[ COMMAND_ALL_COMMANDS ] = False
    args[ CMD_TIMEOUT ] = 120
    args[ PARMS ] = { }
    args[ MODEL_DIR ] = "examples"
    args[ MODEL ] = "sorting"
    reassign_paths( args )
    args[ BUILD_DIR ] = "sorting_cpp"

    parts = argv[ 0 ].split( "/" )[ 0 : -1 ]
    parts.append( "biocell_cpp" )
    if argv[ 0 ][ 0 ] == os.sep:
        args[ CPP_DIR ] = os.sep
    else:
        args[ CPP_DIR ] = ""
    for p in parts:
        args[ CPP_DIR ] = os.path.join( args[ CPP_DIR ], p )

    try:
        short_opts = "ATXCRp:t:x:m:d:c:b:o:h?"
        long_opts = [ "all-commands", "process-xml-template", "process-xml-model", "compile-cpp-model", "run-model", "parm=", "template-file=", "xml-file=", "model-name=", "model-dir=", "cpp-dir=", "build-dir=", "command-timeout=", "help" ]

        do_help = False
        opts, r_args = getopt.getopt( argv[1:], short_opts, long_opts )
        for o, a in opts:
            if o in ('-A', '--all-commands'):
                args[ COMMAND_ALL_COMMANDS ] = True
            elif o in ('-T', '--process-xml-template'):
                args[ COMMAND_PROCESS_XML_TEMPLATE ] = True
            elif o in ('-X', '--process-xml-model'):
                args[ COMMAND_PROCESS_XML_MODEL ] = True
            elif o in ('-C', '--compile-cpp-model'):
                args[ COMMAND_COMPILE_CPP_MODEL ] = True
            elif o in ('-R', '--run-model'):
                args[ COMMAND_RUN_MODEL ] = True
            elif o in ('-t', '--template-file'):
                args[ TEMPLATE_FILE ] = a
            elif o in ('-x', '--xml-file'):
                args[ XML_FILE ] = a
            elif o in ('-m', '--model-name'):
                args[ MODEL ] = a
                reassign_paths( args )
            elif o in ('-d', '--model-dir'):
                args[ MODEL_DIR ] = a
                reassign_paths( args )
            elif o in ('-c', '--cpp-dir'):
                args[ CPP_DIR ] = a
            elif o in ('-b', '--build-dir'):
                args[ BUILD_DIR ] = a
            elif o in ('-o', '--command-timeout'):
                args[ CMD_TIMEOUT ] = int( a )
            elif o in ('-p', '--parm'):
                var, val = a.split( '=' )
                var = var.strip( )
                val = float( val.strip( ) )
                args[ 'parms' ][ var ] = val
            elif o in ('-h', '-?', '--help'):
                do_help = True
            else:
                print("Unhandled option: '%s:%s'" % (o, a))
                do_help = True
        if do_help:
            usage( argv, args )
            sys.exit( 1 )

    except getopt.GetoptError as err:
        print( str( err ) )
        usage( argv, args )
        sys.exit( 1 )

    except ValueError as err:
        print( "Parameters must have float values" )
        print( str( err ) )
        usage( argv, args )
        sys.exit( 1 )

    return

def main( argv ):

    args = { }
    read_args( argv, args )

    if args[ COMMAND_ALL_COMMANDS ]:
        biocell.create_xml_model_from_xml_model_template( args[ TEMPLATE_FILE ], args[ XML_FILE ], args[ PARMS ] )
        biocell.create_cpp_model_from_xml_model( args[ XML_FILE ], args[ CPP_DIR ], args[ BUILD_DIR ] )
        biocell.compile_cpp_model( args[ BUILD_DIR ] )
        biocell.run_compiled_model( args[ BUILD_DIR ], args[ CMD_TIMEOUT ] )
    else:
        if args[ COMMAND_PROCESS_XML_TEMPLATE ]:
            biocell.create_xml_model_from_xml_model_template( args[ TEMPLATE_FILE ], args[ XML_FILE ], args[ PARMS ] )
        if args[ COMMAND_PROCESS_XML_MODEL ]:
            biocell.create_cpp_model_from_xml_model( args[ XML_FILE ], args[ CPP_DIR ], args[ BUILD_DIR ] )
        if args[ COMMAND_COMPILE_CPP_MODEL ]:
            biocell.compile_cpp_model( args[ BUILD_DIR ] )
        if args[ COMMAND_RUN_MODEL ]:
            biocell.run_compiled_model( args[ BUILD_DIR ], args[ CMD_TIMEOUT ] )
    return

if __name__ == "__main__":
    main( sys.argv )


#Listas

#append(valor) agrega un elemento al final de la lista
#extend([]) agrega contenido lista2 al final de la lista
#insert(posicion, valor) agrega un elemento en la posicion especificada
#remove(valor) elimina un elemento de la lista
#pop() o pop(posicion) elimina el ultimo elemento // elimina el elemento de la posicion especificada

#lista.sort(reverse=True) => Ordenar a lista de forma decrescente
#lista.sort() => Ordenarlista de forma crescente
#lista.sort(key=len) = ordena lista con palabras por longitud de menor a mayor
#lista.reverse() => Ordenar lista en reversa

lista = [1, 50, 25, 100, 75]
print("inicial: ", lista)

lista.append(150)
print("append: ", lista)

lista2=[99, 500]
lista.extend(lista2)
print("extend: ", lista)

lista2=[99, 500]
lista.insert(2, 999)
print("insert: ", lista)

list2 = [99, 500]
lista.remove(99)
print("remove: ", lista)

lista2 = [99, 500]
lista.pop(4)
print("pop: ", lista)

Programación de Algoritmos Duoc/Primer semestre/Clase 6/Listas.py


from typing import List, Tuple

from django.db.models import QuerySet
from thefuzz import fuzz
from trama.models import Obra

class Scorer:
    def score(self, query_result: QuerySet, text: str) ->\
            List[Tuple[Obra, float]]:
        scoring_fun = fuzz.token_set_ratio
        obras: List[Obra] = query_result.all()

        scored_obras = {}
        for obra in obras:
            trabajos = [
                x.nombre_trabajo for x in
                obra.trabajo_representado.all()]
            score = max(
                scoring_fun(obra.nombre_obra, text),
                scoring_fun(obra.descripcion, text),
                scoring_fun(obra.estilo.nombre_estilo, text),
            )

            score_trabajos = max([scoring_fun(x, text)
                                  for x in trabajos])

            scored_obras[obra] = max(score, score_trabajos)
        return [(x, y) for (x, y) in
                sorted(scored_obras.items(), key=lambda x: x[1],
                       reverse=True)]


import re
import textblob
from textblob import TextBlob
import csv

def get_tweet_sentiment(tweet):
    analysis = TextBlob(tweet)
    if analysis.sentiment.polarity > 0:
        return 'P'
    elif analysis.sentiment.polarity == 0:
        return 'N'
    else:
        return 'Z'

def get_tweets():
    tweets = []
    fetched_tweets = []
    file = open('MY_results_full_data','w+')
    with open('population_preprocessed_FULL.csv', encoding = 'utf8') as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        line_count = 0
        for row in csv_reader:
            if line_count != 0:
                fetched_tweets.append(row[0])
            line_count += 1
        for tweet in fetched_tweets:
            sentiment = get_tweet_sentiment(tweet)
            file.write(sentiment)
    file.close()

get_tweets()


import argparse
import logging
import sys

from lib.event_manager import Atman
from lib.globals import LOGGER_TAG

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Alien')
    parser.add_argument("--verbose", "-v", action="store_true")
    parser.add_argument("--show_logs", "-s", action="store_false")
    parser.add_argument("--log_file", "-lf", default=None, help="Set path to save log output")
    args = parser.parse_args()

    logger = logging.getLogger(LOGGER_TAG)

    if args.log_file:
        log_file_handler = logging.FileHandler(args.log_file)
        formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] [%(threadName)s] %(message)s')
        log_file_handler.setFormatter(formatter)
        logger.addHandler(log_file_handler)

    if args.show_logs:
        stdout_handler = logging.StreamHandler(sys.stdout)
        formatter = logging.Formatter('[%(levelname)s] [%(threadName)s] %(message)s')
        stdout_handler.setFormatter(formatter)
        logger.addHandler(stdout_handler)

    if args.verbose:
        logger.setLevel(level=logging.DEBUG)
    else:
        logger.setLevel(level=logging.INFO)

    trigger_events = Atman()
    trigger_events.start()
    trigger_events.join()


# coding:utf-8
from PyQt6.QtCore import Qt, pyqtSignal, QUrl, QEvent
from PyQt6.QtGui import QDesktopServices
from PyQt6.QtWidgets import QWidget, QLabel, QVBoxLayout, QHBoxLayout, QFrame

from qfluentwidgets import (ScrollArea, PushButton, ToolButton, FluentIcon,
                            isDarkTheme, IconWidget, Theme, ToolTipFilter)
from ..common.icon import Icon
from ..common.config import cfg, FEEDBACK_URL, HELP_URL, EXAMPLE_URL

class ToolBar(QWidget):
    """ Tool bar """

    def __init__(self, title, subtitle, parent=None):
        super().__init__(parent=parent)
        self.titleLabel = QLabel(title, self)
        self.subtitleLabel = QLabel(subtitle, self)

        self.documentButton = PushButton(
            self.tr('Documentation'), self, Icon.DOCUMENT)
        self.sourceButton = PushButton(self.tr('Source'), self, FluentIcon.GITHUB)
        self.themeButton = ToolButton(Icon.CONSTRACT, self)
        self.feedbackButton = ToolButton(FluentIcon.FEEDBACK, self)

        self.vBoxLayout = QVBoxLayout(self)
        self.buttonLayout = QHBoxLayout()

        self.__initWidget()

    def __initWidget(self):
        self.setFixedHeight(138)
        self.vBoxLayout.setSpacing(0)
        self.vBoxLayout.setContentsMargins(36, 22, 36, 12)
        self.vBoxLayout.addWidget(self.titleLabel)
        self.vBoxLayout.addSpacing(4)
        self.vBoxLayout.addWidget(self.subtitleLabel)
        self.vBoxLayout.addSpacing(4)
        self.vBoxLayout.addLayout(self.buttonLayout, 1)
        self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.buttonLayout.setSpacing(4)
        self.buttonLayout.setContentsMargins(0, 0, 0, 0)
        self.buttonLayout.addWidget(self.documentButton, 0, Qt.AlignmentFlag.AlignLeft)
        self.buttonLayout.addWidget(self.sourceButton, 0, Qt.AlignmentFlag.AlignLeft)
        self.buttonLayout.addStretch(1)
        self.buttonLayout.addWidget(self.themeButton, 0, Qt.AlignmentFlag.AlignRight)
        self.buttonLayout.addWidget(self.feedbackButton, 0, Qt.AlignmentFlag.AlignRight)
        self.buttonLayout.setAlignment(Qt.AlignmentFlag.AlignVCenter | Qt.AlignmentFlag.AlignLeft)

        self.themeButton.installEventFilter(ToolTipFilter(self.themeButton))
        self.feedbackButton.installEventFilter(
            ToolTipFilter(self.feedbackButton))
        self.themeButton.setToolTip(self.tr('Toggle theme'))
        self.feedbackButton.setToolTip(self.tr('Send feedback'))

        self.titleLabel.setObjectName('titleLabel')
        self.subtitleLabel.setObjectName('subtitleLabel')

        self.themeButton.clicked.connect(self.toggleTheme)
        self.documentButton.clicked.connect(
            lambda: QDesktopServices.openUrl(QUrl(HELP_URL)))
        self.sourceButton.clicked.connect(
            lambda: QDesktopServices.openUrl(QUrl(EXAMPLE_URL)))
        self.feedbackButton.clicked.connect(
            lambda: QDesktopServices.openUrl(QUrl(FEEDBACK_URL)))

    def toggleTheme(self):
        theme = Theme.LIGHT if isDarkTheme() else Theme.DARK
        cfg.set(cfg.themeMode, theme)

class ExampleCard(QWidget):
    """ Example card """

    def __init__(self, title, widget: QWidget, sourcePath, stretch=0, parent=None):
        super().__init__(parent=parent)
        self.widget = widget
        self.stretch = stretch

        self.titleLabel = QLabel(title, self)
        self.card = QFrame(self)

        self.sourceWidget = QFrame(self.card)
        self.sourcePath = sourcePath
        self.sourcePathLabel = QLabel(
            self.tr('Source code'), self.sourceWidget)
        self.linkIcon = IconWidget(FluentIcon.LINK, self.sourceWidget)

        self.vBoxLayout = QVBoxLayout(self)
        self.cardLayout = QVBoxLayout(self.card)
        self.topLayout = QHBoxLayout()
        self.bottomLayout = QHBoxLayout(self.sourceWidget)

        self.__initWidget()

    def __initWidget(self):
        self.linkIcon.setFixedSize(16, 16)
        self.__initLayout()

        self.sourceWidget.setCursor(Qt.CursorShape.PointingHandCursor)
        self.sourceWidget.installEventFilter(self)

        self.titleLabel.setObjectName('titleLabel')
        self.card.setObjectName('card')
        self.sourcePathLabel.setObjectName('sourcePathLabel')
        self.sourceWidget.setObjectName('sourceWidget')

    def __initLayout(self):
        self.vBoxLayout.setSizeConstraint(QVBoxLayout.SizeConstraint.SetMinimumSize)
        self.cardLayout.setSizeConstraint(QVBoxLayout.SizeConstraint.SetMinimumSize)
        self.topLayout.setSizeConstraint(QHBoxLayout.SizeConstraint.SetMinimumSize)

        self.vBoxLayout.setSpacing(12)
        self.vBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.topLayout.setContentsMargins(12, 12, 12, 12)
        self.bottomLayout.setContentsMargins(18, 18, 18, 18)
        self.cardLayout.setContentsMargins(0, 0, 0, 0)

        self.vBoxLayout.addWidget(self.titleLabel, 0, Qt.AlignmentFlag.AlignTop)
        self.vBoxLayout.addWidget(self.card, 0, Qt.AlignmentFlag.AlignTop)
        self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignTop)

        self.cardLayout.setSpacing(0)
        self.cardLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.cardLayout.addLayout(self.topLayout, 0)
        self.cardLayout.addWidget(self.sourceWidget, 0, Qt.AlignmentFlag.AlignBottom)

        self.widget.setParent(self.card)
        self.topLayout.addWidget(self.widget)
        if self.stretch == 0:
            self.topLayout.addStretch(1)

        self.widget.show()

        self.bottomLayout.addWidget(self.sourcePathLabel, 0, Qt.AlignmentFlag.AlignLeft)
        self.bottomLayout.addStretch(1)
        self.bottomLayout.addWidget(self.linkIcon, 0, Qt.AlignmentFlag.AlignRight)
        self.bottomLayout.setAlignment(Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter)

    def eventFilter(self, obj, e):
        if obj is self.sourceWidget:
            if e.type() == QEvent.Type.MouseButtonRelease:
                QDesktopServices.openUrl(QUrl(self.sourcePath))

        return super().eventFilter(obj, e)

class GalleryInterface(ScrollArea):
    """ Gallery interface """

    def __init__(self, title: str, subtitle: str, parent=None):
        """
        Parameters
        ----------
        title: str
            The title of gallery

        subtitle: str
            The subtitle of gallery

        parent: QWidget
            parent widget
        """
        super().__init__(parent=parent)
        self.view = QWidget(self)
        self.toolBar = ToolBar(title, subtitle, self)
        self.vBoxLayout = QVBoxLayout(self.view)

        self.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
        self.setViewportMargins(0, self.toolBar.height(), 0, 0)
        self.setWidget(self.view)
        self.setWidgetResizable(True)

        self.vBoxLayout.setSpacing(30)
        self.vBoxLayout.setAlignment(Qt.AlignmentFlag.AlignTop)
        self.vBoxLayout.setContentsMargins(36, 20, 36, 36)

        self.__setQss()
        cfg.themeChanged.connect(self.__setQss)

    def addExampleCard(self, title, widget, sourcePath: str, stretch=0):
        card = ExampleCard(title, widget, sourcePath, stretch, self.view)
        self.vBoxLayout.addWidget(card, 0, Qt.AlignmentFlag.AlignTop)
        return card

    def scrollToCard(self, index: int):
        """ scroll to example card """
        w = self.vBoxLayout.itemAt(index).widget()
        self.verticalScrollBar().setValue(w.y())

    def resizeEvent(self, e):
        super().resizeEvent(e)
        self.toolBar.resize(self.width(), self.toolBar.height())

    def __setQss(self):
        self.view.setObjectName('view')
        theme = 'dark' if isDarkTheme() else 'light'
        with open(f'app/resource/qss/{theme}/gallery_interface.qss', encoding='utf-8') as f:
            self.setStyleSheet(f.read())


#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
main.py
@author Luc Kusters
@date 10-11-2023
"""

import os.path
import typing

import collections

Task = collections.namedtuple("Task", ("low", "high"))
TaskPair = collections.namedtuple("TaskPair", ("t1", "t2"))

def load_data(path: os.PathLike) -> list[str]:
    with open(path, "r") as fhandle:
        lines: list[str] = fhandle.readlines()
    return lines

def parse_data(lines: list[str]) -> list[TaskPair]:
    parsed_data = []
    for line in lines:
        task1, task2 = line.split(",")
        t1 = Task(*list(int(lim) for lim in task1.split("-")))
        t2 = Task(*list(int(lim) for lim in task2.split("-")))
        parsed_data.append(TaskPair(t1, t2))
    return parsed_data

def fully_contained(task_pair: TaskPair) -> bool:
    t1, t2 = task_pair
    t1_contains_t2 = (t1.low >= t2.low) and (t1.high <= t2.high)
    t2_contains_t1 = (t1.low <= t2.low) and (t1.high >= t2.high)
    if t1_contains_t2 or t2_contains_t1:
        return True
    return False

def argmax(iter_: typing.Iterable):
    return max(zip(iter_, range(len(iter_))))[1]

def overlap(task_pair: TaskPair) -> bool:
    """
    t1 = 6-8
    t2 = 3-4

    t_high = argmax(t1.high, t2.high)
    """
    # sort tasks by max high range value
    idx_high = argmax(tuple(t.high for t in task_pair))
    idx_low = not idx_high
    t_low = task_pair[idx_low]
    t_high = task_pair[idx_high]
    print(t_low, t_high, t_low.high >= t_high.low)
    return t_low.high >= t_high.low

def part_1(parsed_data: list[TaskPair]) -> int:
    num_fully_contained = sum(fully_contained(task_pair)
                              for task_pair in parsed_data
                              )
    return num_fully_contained

def part_2(parsed_data: list[TaskPair]):
    return sum(overlap(task) for task in parsed_data)

def main():
    data = load_data("data.txt")
    parsed_data = parse_data(data)
    print("part 1:", part_1(parsed_data))
    print("part_2:", part_2(parsed_data))

if __name__ == "__main__":
    main()


from c7n.utils import type_schema
from c7n_gcp.actions import MethodAction, SetIamPolicy
from c7n_gcp.provider import resources
from c7n_gcp.query import QueryResourceManager, TypeInfo, ChildTypeInfo, ChildResourceManager

@resources.register('spanner-instance')
class SpannerInstance(QueryResourceManager):
    """
    https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instances
    """
    class resource_type(TypeInfo):
        service = 'spanner'
        version = 'v1'
        component = 'projects.instances'
        enum_spec = ('list', 'instances[]', None)
        scope_key = 'parent'
        scope_template = 'projects/{}'
        name = id = 'name'
        default_report_fields = [
            "name", "displayName", "nodeCount", "state", "config"]
        labels = True
        labels_op = 'patch'
        asset_type = "spanner.googleapis.com/Instance"

        @staticmethod
        def get(client, resource_info):
            return client.execute_command(
                'get', {'name': resource_info['resourceName']}
            )

        @staticmethod
        def get_label_params(resource, all_labels):
            return {'name': resource['name'],
                    'body': {
                        'instance': {
                            'labels': all_labels
                        },
                        'field_mask': ', '.join(['labels'])}}

@SpannerInstance.action_registry.register('delete')
class SpannerInstanceDelete(MethodAction):
    """The action is used for spanner instances delete.

    GCP action is https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instances/delete

    :Example:

    .. code-block:: yaml

        policies:
          - name: gcp-spanner-instances-delete
            resource: gcp.spanner-instance
            filters:
              - type: value
                key: nodeCount
                op: gte
                value: 2
            actions:
              - type: delete
    """
    schema = type_schema('delete')
    method_spec = {'op': 'delete'}

    def get_resource_params(self, model, resource):
        return {'name': resource['name']}

@SpannerInstance.action_registry.register('set')
class SpannerInstancePatch(MethodAction):
    """The action is used for spanner instances nodeCount patch.

    GCP action is https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instances/patch

    :Example:

    .. code-block:: yaml

        policies:
          - name: gcp-spanner-instances-change-node-count
            resource: gcp.spanner-instance
            filters:
              - type: value
                key: nodeCount
                op: gte
                value: 2
            actions:
              - type: set
                nodeCount: 1
    """
    schema = type_schema('set', required=['nodeCount'],
                         **{'nodeCount': {'type': 'number'}})
    method_spec = {'op': 'patch'}
    method_perm = 'update'

    def get_resource_params(self, model, resource):
        result = {'name': resource['name'],
                  'body': {
                      'instance': {
                          'nodeCount': self.data['nodeCount']
                      },
                      'field_mask': ', '.join(['nodeCount'])}
                  }
        return result

SpannerInstance.action_registry.register('set-iam-policy', SetIamPolicy)

@resources.register('spanner-database-instance')
class SpannerDatabaseInstance(ChildResourceManager):
    """GCP resource:
    https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instances.databases
    """
    def _get_parent_resource_info(self, child_instance):
        resource_name = None
        if child_instance['name'] is not None:
            resource_names = child_instance['name'].split('/databases')
            if len(resource_names) > 0:
                resource_name = resource_names[0]
        return {
            'resourceName': resource_name
        }

    class resource_type(ChildTypeInfo):
        service = 'spanner'
        version = 'v1'
        component = 'projects.instances.databases'
        enum_spec = ('list', 'databases[]', None)
        name = id = 'name'
        scope = None
        parent_spec = {
            'resource': 'spanner-instance',
            'child_enum_params': [
                ('name', 'parent')
            ]
        }
        default_report_fields = ["name", "state", "createTime"]
        asset_type = "spanner.googleapis.com/Database"

        @staticmethod
        def get(client, resource_info):
            return client.execute_command(
                'get', {
                    'name': resource_info['resourceName']}
            )

SpannerDatabaseInstance.action_registry.register('set-iam-policy', SetIamPolicy)

@SpannerDatabaseInstance.action_registry.register('delete')
class SpannerDatabaseInstanceDropDatabase(MethodAction):
    """The action is used for databases deleting.

    GCP action is https://cloud.google.com/spanner/docs
        /reference/rest/v1/projects.instances.databases/dropDatabase.

    :Example:

    .. code-block:: yaml

        policies:
          - name: gcp-spanner-instance-databases-delete
            resource: gcp.spanner-database-instance
            filters:
              - type: value
                key: name
                op: contains
                value: dev
            actions:
              - type: delete
    """
    schema = type_schema('dropDatabase', **{'type': {'enum': ['delete']}})
    method_spec = {'op': 'dropDatabase'}
    method_perm = 'drop'

    def get_resource_params(self, model, resource):
        return {'database': resource['name']}


from __future__ import annotations

import asyncio
import os
import tempfile
from collections.abc import AsyncIterator, Iterator
from pathlib import Path
from typing import Any

import aiohttp
import aiohttp.web
import pytest
from yarl import URL

from platform_container_runtime.config import KubeClientAuthType, KubeConfig
from platform_container_runtime.kube_client import KubeClient

from .conftest import create_local_app_server

class TestKubeClientTokenUpdater:
    @pytest.fixture
    async def kube_app(self) -> aiohttp.web.Application:
        async def _get_nodes(request: aiohttp.web.Request) -> aiohttp.web.Response:
            auth = request.headers["Authorization"]
            token = auth.split()[-1]
            app["token"]["value"] = token
            return aiohttp.web.json_response({"kind": "NodeList", "items": []})

        app = aiohttp.web.Application()
        app["token"] = {"value": ""}
        app.router.add_routes([aiohttp.web.get("/api/v1/nodes", _get_nodes)])
        return app

    @pytest.fixture
    async def kube_server(
        self, kube_app: aiohttp.web.Application, unused_tcp_port_factory: Any
    ) -> AsyncIterator[str]:
        async with create_local_app_server(
            kube_app, port=unused_tcp_port_factory()
        ) as address:
            yield f"http://{address.host}:{address.port}"

    @pytest.fixture
    def kube_token_path(self) -> Iterator[str]:
        _, path = tempfile.mkstemp()
        Path(path).write_text("token-1")
        yield path
        os.remove(path)

    @pytest.fixture
    async def kube_client(
        self, kube_server: str, kube_token_path: str
    ) -> AsyncIterator[KubeClient]:
        async with KubeClient(
            config=KubeConfig(
                url=URL(kube_server),
                auth_type=KubeClientAuthType.TOKEN,
                token_path=kube_token_path,
                token_update_interval_s=1,
            )
        ) as client:
            yield client

    async def test_token_periodically_updated(
        self,
        kube_app: aiohttp.web.Application,
        kube_client: KubeClient,
        kube_token_path: str,
    ) -> None:
        await kube_client.get_nodes()
        assert kube_app["token"]["value"] == "token-1"

        Path(kube_token_path).write_text("token-2")
        await asyncio.sleep(2)

        await kube_client.get_nodes()
        assert kube_app["token"]["value"] == "token-2"

class TestKubeClient:
    async def test_get_node(self, kube_client: KubeClient) -> None:
        nodes = await kube_client.get_nodes()

        assert nodes

        node = await kube_client.get_node(nodes[0].metadata.name)

        assert node.metadata.labels
        assert node.container_runtime_version
        assert node.os
        assert node.architecture


import argparse
import logging
import socket

from dns.resolver import Resolver

from certipy.target import Target

class DnsResolver:
    def __init__(self, options: argparse.Namespace, target: Target):
        self.resolver = Resolver()

        # We can't put all possible nameservers in the list of nameservers, since
        # the resolver will fail if one of them fails
        nameserver = options.nameserver
        if nameserver is None:
            nameserver = target.dc_ip
        if nameserver is None:
            nameserver = target.target_ip

        self.resolver.nameservers = [nameserver]
        self.use_tcp = options.dns_tcp

    def resolve(self, hostname: str) -> str:
        # Try to resolve the hostname with DNS first, then try a local resolve
        try:
            # Check if hostname is an IP
            socket.inet_aton(hostname)
            return hostname
        except Exception:
            pass

        ip_addr = None
        logging.debug(
            "Trying to resolve %s at %s"
            % (repr(hostname), repr(self.resolver.nameservers[0]))
        )
        try:
            answers = self.resolver.resolve(hostname, tcp=self.use_tcp)
            if len(answers) == 0:
                raise Exception()

            ip_addr = answers[0].to_text()
        except Exception:
            pass

        if ip_addr is None:
            try:
                ip_addr = socket.gethostbyname(hostname)
            except Exception:
                ip_addr = None

        if ip_addr is None:
            logging.warning("Failed to resolve: %s" % hostname)
            return hostname

        return ip_addr


from datetime import timedelta
from logging import Logger
import json
from typing import Dict, Tuple
import pandas as pd
from pydantic import validate_arguments

from algo_trading.logger.controllers import LogConfig
from algo_trading.utils.utils import dt_to_str, str_to_dt
from algo_trading.strategies.sma_cross_strat import SMACross, SMACrossUtils
from algo_trading.repositories.db_repository import AbstractDBRepository, DBRepository
from algo_trading.repositories.key_val_repository import KeyValueRepository
from algo_trading.config.controllers import (
    ColumnController,
    DBHandlerController,
    KeyValueController,
    StockStatusController,
    StrategyInfo,
)
from algo_trading.utils.calculations import Calculator
from algo_trading.exceptions.data_exceptions import DateNotFoundException

from .controllers import BackTestPayload, BackTestResult

# TODO: PERSIST LOGS TO MINIO BUCKET

class SMACrossBackTester:
    @validate_arguments(config=dict(arbitrary_types_allowed=True))
    def __init__(
        self,
        payload: BackTestPayload,
        db_info: Dict,
        db_handler: DBHandlerController,
        log: Logger,
        log_info: LogConfig,
    ) -> None:
        """
        SMACross Backtesting class. Entrypoint is the test() method.

        Args:
            payload (BackTestPayload): Pydantic paylod model.
            db_info (Dict[str, str], optional): DB to get price data. Defaults to DB_INFO.
            db_handler (DBHandlerController, optional): Defaults to DB_HANDLER.
            log (Logger, optional): Defaults to LOG.
            log_info (LogConfig, optional): Defaults to LOG_INFO.
        """
        self.ticker = payload.ticker
        self.start_date = payload.start_date
        self.end_date = payload.end_date
        self.starting_capital = payload.starting_capital

        self.db_info = db_info
        self.db_handler = db_handler
        self.log = log
        self.log_info = log_info

        self.fake_kv_repo = None

    @property
    def db_repo(self) -> AbstractDBRepository:
        """
        Live prices DB to pull data from to test.

        Returns:
            AbstractDBRepository: DB Repo handler object.
        """
        try:
            return self._db_repo
        except AttributeError:
            self._db_repo = DBRepository(
                self.db_info,
                self.db_handler,
                self.log_info,
            ).handler
            return self._db_repo

    @property
    def price_data(self) -> pd.DataFrame:
        """
        Pulling data from the real DB. This is why we needed db_info.
        Caches this data for testing so we don't have to clog the
        live DB.

        Returns:
            pd.DataFrame: Price DF to use for testing.
        """
        try:
            return self._price_data
        except AttributeError:
            if self.start_date == "max":
                self._price_data = self.db_repo.get_until_date(
                    self.ticker, self.end_date
                )
                self._price_data = Calculator.calculate_sma(
                    self._price_data, ColumnController.close.value
                )
            else:
                # Getting 199 days back in order to calculate SMA values
                # for the given start date

                row_nums = self.db_repo.get_row_num(self.ticker)
                try:
                    start_date_idx = row_nums.index[
                        row_nums[ColumnController.date.value]
                        == str_to_dt(self.start_date)
                    ].tolist()[0]
                except IndexError:
                    self.log.error(
                        f"Failed to backtest {self.ticker} with start date {self.start_date}"
                    )
                    raise DateNotFoundException(self.start_date, self.ticker)

                pull_date_idx = max(0, int(start_date_idx) - 199)
                pull_date = row_nums.iloc[pull_date_idx].to_dict()[
                    ColumnController.date.value
                ]
                self._price_data = self.db_repo.get_dates_between(
                    self.ticker, dt_to_str(pull_date), self.end_date
                )
                self._price_data = Calculator.calculate_sma(
                    self._price_data, ColumnController.close.value
                )
                self._price_data = self._price_data.iloc[
                    (start_date_idx - pull_date_idx) :
                ].reset_index(drop=True)
            return self._price_data

    def _init_fake_key_value(self) -> Tuple[StockStatusController, Dict[str, str]]:
        """
        Initializes the fake key,value store depending on the first day
        of the test data.

        Returns:
            Tuple[StockStatusController, Dict[str, str]]: Initialized status as a dict.
        """
        first_day = self.price_data.iloc[0].to_dict()
        if (
            first_day[ColumnController.ma_7.value]
            > first_day[ColumnController.ma_21.value]
        ):
            last_cross_up = dt_to_str(
                first_day[ColumnController.date.value] - timedelta(days=1)
            )
            last_cross_down = dt_to_str(
                first_day[ColumnController.date.value] - timedelta(days=2)
            )
            last_status = StockStatusController.buy
        else:
            last_cross_up = dt_to_str(
                first_day[ColumnController.date.value] - timedelta(days=2)
            )
            last_cross_down = dt_to_str(
                first_day[ColumnController.date.value] - timedelta(days=1)
            )
            last_status = StockStatusController.sell

        cross_info = StrategyInfo(
            sma_last_cross_up=last_cross_up,
            sma_last_cross_down=last_cross_down,
            sma_last_status=last_status,
        )

        return last_status, {self.ticker: json.dumps(cross_info.dict())}

    def _get_num_shares(self, cash: float, share_price: float) -> float:
        """
        Simple calculation of num shares to buy.

        Args:
            cash (float): Current cash
            share_price (float): Share price

        Returns:
            float: Num shares to purchase
        """
        return cash / share_price

    def _get_new_capital(self, num_shares: float, share_price: float) -> float:
        """
        Simple calculation of capitcal after selling.

        Args:
            num_shares (float): Num shares to sell
            share_price (float): Share price

        Returns:
            float: Liquid capital
        """
        return num_shares * share_price

    def _get_percent_change(
        self, start_cap: float, end_cap: float, precision: int = 2
    ) -> float:
        """
        Generate percent change from starting and ending capital.

        Args:
            start_cap (float): Starting capital
            end_cap (float): Ending capital
            precision (int, optional): Decimal places. Defaults to 2.

        Returns:
            float: Percent change
        """
        return round(((end_cap - start_cap) / start_cap) * 100, precision)

    def test(self) -> Tuple[BackTestResult, Dict[str, str]]:
        """
        Runs the SMA strategy over the cached price data.
        Instantiates a fake DBRepository and a fake KeyValueRepository
        to 'query' from.

        Returns:
            BackTestResult: Results of the back test.
            Dict[str, StockStatusController]: Trade book used for testing.
        """

        trade_book = {}

        init_status, init_kv = self._init_fake_key_value()
        fake_kv_repo = KeyValueRepository(
            kv_info=init_kv,
            kv_handler=KeyValueController.fake,
            log_info=self.log_info,
        ).handler

        starting_cap = self.starting_capital
        num_trades = 0
        if init_status == StockStatusController.buy:
            num_shares = self._get_num_shares(
                self.starting_capital,
                self.price_data[ColumnController.close.value].iloc[0],
            )
            init_message = f"{num_shares} shares"
        else:
            num_shares = 0
            init_message = f"${self.starting_capital}"

        self.log.info(
            f"Beginning SMA Cross strategy with {init_message} for "
            + f"{self.ticker.upper()} at price "
            + f"{self.price_data[ColumnController.close.value].iloc[0]} on "
            + f"{self.price_data[ColumnController.date.value].iloc[0]}"
        )

        for idx, row in self.price_data.iterrows():
            if idx == 0:
                # Skip the first day.
                continue
            else:

                # Current key/val store for self.ticker
                cross_info = StrategyInfo(**json.loads(fake_kv_repo.get(self.ticker)))

                cross_info = SMACrossUtils.check_cross_up(
                    self.price_data[: (idx + 1)],
                    idx,
                    cross_info,
                )

                cross_info = SMACrossUtils.check_cross_down(
                    self.price_data[: (idx + 1)],
                    idx,
                    cross_info,
                )

                fake_kv_repo.set(self.ticker, cross_info.dict())
                date = self.price_data.iloc[idx][ColumnController.date.value]
                sma = SMACross(self.ticker, fake_kv_repo, date)
                result = sma.run()
                if result.signal == StockStatusController.buy:
                    num_shares = self._get_num_shares(
                        self.starting_capital, row[ColumnController.close.value]
                    )
                    num_trades += 1
                    self.log.debug(
                        f"Bought {num_shares} shares at price {row[ColumnController.close.value]} "
                        + f"on {row[ColumnController.date.value]}."
                    )
                    trade_book[
                        dt_to_str(row[ColumnController.date.value])
                    ] = StockStatusController.buy.value
                elif result.signal == StockStatusController.sell:
                    self.starting_capital = self._get_new_capital(
                        num_shares, row[ColumnController.close.value]
                    )
                    num_trades += 1
                    self.log.debug(
                        f"Sold {num_shares} shares at price "
                        + f"{row[ColumnController.close.value]} on "
                        + f"{row[ColumnController.date.value]} for a new capital of {self.starting_capital}."
                    )
                    trade_book[
                        dt_to_str(row[ColumnController.date.value])
                    ] = StockStatusController.sell.value
                    num_shares = 0

        if num_shares != 0:
            self.starting_capital = self._get_new_capital(
                num_shares, self.price_data[ColumnController.close.value].iloc[-1]
            )
            self.log.debug(
                f"Finished with {num_shares} shares at price "
                + f"{self.price_data[ColumnController.close.value].iloc[-1]} "
                + f"on {self.price_data[ColumnController.date.value].iloc[-1]}."
            )
            self.log.debug(f"Selling all for a new capital of {self.starting_capital}.")
        percent_change = self._get_percent_change(starting_cap, self.starting_capital)

        res = BackTestResult(
            ticker=self.ticker,
            start_date=dt_to_str(self.price_data[ColumnController.date.value].iloc[0]),
            end_date=dt_to_str(self.price_data[ColumnController.date.value].iloc[-1]),
            init_cap=starting_cap,
            final_cap=self.starting_capital,
            cap_gains=percent_change,
            num_trades=num_trades,
        )

        self.log.info(
            f"Successfully backtested SMA Cross for {self.ticker}:\n {json.dumps(res.dict(), indent=2)}\n"
        )

        return res, trade_book


from acsploit.options import Options

options = Options()
options.add_option('n_inputs', 10, 'Number of elements to sort')

DESCRIPTION = ('Produces a worst-case input set for bucketsort (aka radixsort)'
               '\n\n  Generates a list with a large range and many values clustered together '
               'so that many values fall in the same bucket')

def run(generator, output):
    # bucketsort worst case is values clustered and a large range so the clustered values fall in same bucket
    out = [generator.get_min_value(), generator.get_max_value()]  # force max range
    for value in generator.get_list_of_values(options['n_inputs'] - 2):  # generate a big cluster
        out.append(value)
    output.output(out)


def palindrome():
    word = input("Check if palindrome: ")
    reverse = ""
    for i in range(len(word)-1, -1, -1):
        reverse += word[i]
    if reverse == word:
        print("palindrome")
    else:
        print("not palindrome")

palindrome()


def main():
    with open("input.txt") as file:
        input = file.read()
    nums = [int(val) for val in input.split()]
    head = build_tree(nums)
    print(head)
    print('metadata = {}'.format(head.get_metadata_count()))

def build_tree(nums):
    num_children = nums.pop(0)
    num_metadata  = nums.pop(0)
    children = []
    metadata = []
    for _ in range(num_children):
        children.append(build_tree(nums))
    for _ in range(num_metadata):
        metadata.append(nums.pop(0))
    return Node(children, metadata)

class Node:
    def __init__(self, children, metadata):
        self.children = children
        self.metadata = metadata
        self.metadata_count = None

    def get_metadata_count(self):
        count = 0
        if self.metadata_count:
            count = self.metadata_count
        elif not self.children:
            count = sum(self.metadata)
        else:
            count = self.sum_child_metadata()
        self.metadata_count = count
        return count

    def sum_child_metadata(self):
        count = 0
        for i in self.metadata:
            if i <= len(self.children):
                count += self.children[i - 1].get_metadata_count()
        return count

    def __repr__(self):
        return('( children = {} metadata = {} )'.format(self.children, self.metadata))

if __name__ == '__main__':
    main()


from turtle import Screen
import time
from snake import Snake
from food import Food
from scoreboard import Scoreboard

screen = Screen()
screen.setup(width=600, height=600)
screen.bgcolor('black')
screen.title('Python')
screen.tracer(0)

DELAY = 0.7
snake = Snake()
food = Food()
scoreboard = Scoreboard()

screen.listen()
screen.onkey(snake.up, "Up")
screen.onkey(snake.down, "Down")
screen.onkey(snake.left, "Left")
screen.onkey(snake.right,"Right")

game_started = True

while game_started:
    screen.update()
    time.sleep(DELAY)
    snake.move()

   # Detect collision with food
    if snake.head.distance(food) < 15:
       food.refresh()
       snake.grow()
       scoreboard.add_point()
       if DELAY > 0.3:
           DELAY -= 0.1
       elif DELAY < 0.3 and DELAY > 0.05:
            DELAY -= 0.01

       print(DELAY)
    # Detect collision with wall
    if snake.head.xcor() > 295 or snake.head.xcor() < -295 or snake.head.ycor() > 295 or snake.head.ycor() < -295:
        game_started = False
        scoreboard.game_over()

    # Detect collision with self
    for segment in snake.snake[1:]:
        if snake.head.distance(segment) < 10:
            game_started = False
            scoreboard.game_over()

screen.exitonclick()


dictionary = dict()
n = int(input())
for i in range(n):
    k,v = input().strip().split(' ')
    dictionary[k] = v

arr = []
j = 0
for j in range(n):
	name = input()
	if name in dictionary:
		number = dictionary[name]
		print(name + '='+str(number))
	else:
		print("Not found")


import numpy as np
import re
import sys
import time

from multiprocessing import Process, Queue

from plotter.utils.gcode import *
from plotter.utils.calibration import *

def processPlotterQueue(plotter):
    """Callback for plotter process."""
    plotter.processQueueAsync()

class BasePlotter:
    """Base class of all plotter implementations. Always call '__init__' in the derived class after
    setting up all (custom) member variables. Otherwise the (custom) config and calibration is
    not available in the worker process."""

    def __init__(self, config, initial_lengh, PhysicsEngineClass):
        """Sets up the worker process and initializes the system."""
        base = config["base_width"]
        self.calib = Calibration(base,
                                 PhysicsEngineClass.calcOrigin(
                                     initial_lengh, base),
                                 stepsPerMM=config["steps_per_mm"],
                                 resolution=config["movement_resolution"])

        self.config = config
        self.physicsEngine = PhysicsEngineClass(self.config, self.calib)
        self.currPos = np.zeros((2,))
        self.currCordLength = self.physicsEngine.point2CordLength(self.currPos)
        self.speed = 10000
        self.penIsDown = False

        self.workerProcess = Process(target=processPlotterQueue, args=(self,))
        self.workerQueue = Queue(1000)
        self.workerProcess.start()

    def shutdown(self):
        """Stops the worker queue and the worker process."""
        print("Shutting down..")
        self.workerQueue.put(None)
        self.workerQueue.close()
        self.workerQueue.join_thread()
        self.workerProcess.join()

    def executeGCodeFile(self, file_name):
        """Opens the specified gcode file and pushes each command into the worker queue.
        This will block if the queue is full."""
        with open(file_name, 'r') as f:
            lines = f.readlines()

        for c in lines:
            self.workerQueue.put(c.strip())

    def processQueueAsync(self):
        """Plotter worker function which runs in the worker process.
        Processes new commands by reading from the worker queue."""
        print("Plotter process started")

        item = self.workerQueue.get()
        while(item is not None):

            self.executeCmd(item)

            item = self.workerQueue.get()

        print("Plotter process stopped")
        exit(0)

    def executeCmd(self, cmd):
        """Executes a command. Should only be called from the worker process."""

        if cmd.startswith("G0"):
            d = decodeGCode(cmd)
            if not d:
                return

            if "S" in d:
                self.setSpeed(d["S"])

            self.moveToPos([d.get("X", self.currPos[0]),
                            d.get("Y", self.currPos[1])])

        elif cmd.startswith("G28"):
            self.moveToPos([0, 0])

        elif cmd.startswith("G2"):
            d = decodeGCode(cmd)
            if not d:
                return

            if "S" in d:
                self.setSpeed(d["S"])

            if "R" not in d and "X" not in d and "Y" not in d:
                print(d)
                print("Unexpected cmd type. Failed to process command.")
                return

            self.moveArc([d["X"], d["Y"]], d["R"],
                         d.get("A", 0), d.get("B", 360))

        elif cmd.startswith("M3"):
            self.penDown()
        elif cmd.startswith("M4"):
            self.penUp()
        else:
            print("Unexpected cmd type. Failed to process command.")

    def moveToPos(self, targetPos):
        """Move to specified position.
        Raises an error if not implemented by derived class."""
        raise NotImplementedError("Function moveToPos not implemented")

    def moveArc(self, center, radius, startAngle, endAngle):
        """Move on an arc.
        Raises an error if not implemented by derived class."""
        raise NotImplementedError("Function moveArc not implemented")

    def penUp(self):
        """Lift the pen.
        Raises an error if not implemented by derived class."""
        raise NotImplementedError("Function penUp not implemented")

    def penDown(self):
        """Lower the pen.
        Raises an error if not implemented by derived class."""
        raise NotImplementedError("Function penDown not implemented")

    def setSpeed(self, s):
        """Sets the current speed. (used by subsequent commands)."""
        self.speed = s

    def __str__(self):
        return """
{}

------------ State ------------
Current Position: {}
Current Length:   {}
PenState:         {}
Current Speed:    {}
Queue Size:       {}
-------------------------------""".format(self.calib, self.currPos, self.currCordLength, "DOWN" if self.penIsDown else "UP", self.speed, self.workerQueue.qsize())


__author__ = "Martin Lacayo-Emery <popanalyst@gmail.com>"

import sys
import os
import arcgisscripting
import lib.pop.separate

if __name__=="__main__":
    #create geoprocessor object
    gp = arcgisscripting.create()

    #store parameters
    inFolder=sys.argv[1]
    fieldName=sys.argv[3]
    outFolder=sys.argv[4]
    if sys.argv[5]=="true":
        stemname=True
    else:
        stemname=False
    namingSchemeValues=["Value","Order"]
    namingScheme=namingSchemeValues.index(sys.argv[6])

    for name in os.listdir(inFolder):
        inName=inFolder+"\\"+name
        gp.AddMessage("Spliting "+inName)
        if stemname:
            stem=name.replace(".","_")+".dbf"
        else:
            stem=""
        lib.pop.separate.separateFile(inName,fieldName,outFolder,stem,namingScheme)


"""Sets up, parses and groups command line arguments using argparse.

Typical usage example:
    parser = set_up_arg_parser()
    args = parse_args(parser)
    arg_groups = create_arg_groups(parser, args)
    arg_group_dict = arg_group_to_dict(arg_groups, "Group Name")
"""

import logging
from argparse import ArgumentParser, Namespace
from typing import Any, TypeAlias, Union

from .choices import COMMAND_CHOICES

ArgGroups: TypeAlias = dict[str, Namespace]
logger = logging.getLogger(__name__)

def set_up_arg_parser() -> ArgumentParser:
    """Sets up argument parser with grouped command line arguments.

    Commands are used in PSI API request query params and response processing.

    Returns:
        An argparse.ArgumentParser instance with 2 argument groups.
    """
    logger.info("Setting up CLI arguments.")
    parser = ArgumentParser(prog="pyspeedinsights")

    # Add argument options for default API call query params.
    api_group = parser.add_argument_group("API Group")
    api_group.add_argument(
        "url", help="The URL or sitemap URL of the site being analyzed."
    )
    api_group.add_argument(
        "-c",
        "--category",
        metavar="\b",
        dest="category",
        choices=COMMAND_CHOICES["category"],
        help=(
            "The Lighthouse category to run: "
            "`accessibility`, `best-practices`, "
            "`performance` (default), `pwa` or `seo`."
        ),
    )
    api_group.add_argument(
        "-l",
        "--locale",
        metavar="\b",
        dest="locale",
        choices=COMMAND_CHOICES["locale"],
        help="The locale used to localize formatted results. Defaults to English (US).",
    )
    api_group.add_argument(
        "-s",
        "--strategy",
        metavar="\b",
        dest="strategy",
        choices=COMMAND_CHOICES["strategy"],
        help="The analysis strategy to use: `desktop` (default) or `mobile`.",
    )
    api_group.add_argument(
        "-uc",
        "--campaign",
        metavar="\b",
        dest="utm_campaign",
        help="The UTM campaign name for analytics.",
    )
    api_group.add_argument(
        "-us",
        "--source",
        metavar="\b",
        dest="utm_source",
        help="The UTM campaign source for analytics.",
    )
    api_group.add_argument(
        "-t",
        "--token",
        metavar="\b",
        dest="captcha_token",
        help="The captcha token passed when filling out a captcha.",
    )

    # Add other argument options for how to process the API response.
    proc_group = parser.add_argument_group("Processing Group")
    proc_group.add_argument(
        "-f",
        "--format",
        metavar="\b",
        dest="format",
        choices=COMMAND_CHOICES["format"],
        help=(
            "The format of the results: `json` (default), `excel` or `sitemap`. "
            "`json` outputs all response data to a json file (1 URL only). "
            "`excel` writes Lighthouse audits and PageSpeed Insights metrics "
            "to an Excel file (1 URL only). "
            "`sitemap` parses the sitemap URL you provide and writes Lighthouse audits "
            "and PageSpeed Insights metrics for all the pages in your sitemap to Excel."
        ),
    )
    return parser

def create_arg_groups(parser: ArgumentParser, args: Namespace) -> ArgGroups:
    """Creates separate namespaces for each arg group.

    Allows for separately passing each arg group as kwargs to a func or cls.

    Returns:
        A dict with group names as keys and argparse.Namespace instances as values.
    """
    logger.info("Creating CLI argument groups.")
    arg_groups = {}
    for group in parser._action_groups:
        group_dict = {a.dest: getattr(args, a.dest, None) for a in group._group_actions}
        title = group.title
        if title:
            arg_groups[title] = Namespace(**group_dict)
    return arg_groups

def arg_group_to_dict(
    arg_groups: ArgGroups, arg_group_name: str
) -> dict[str, Union[Any, None]]:
    """Converts an arg group Namespace to a dict.

    Returns:
        A dict with str-based API or reponse processing param names as keys
        and str or NoneType as values.
    """
    return vars(arg_groups[arg_group_name])