from tkinter import *
from tkinter.ttk import *
import random

class VARIABLES_AND_CONSTS:
    global WIDTH_CANVAS, HEIGHT_CANVAS
    global BALL_SIZE
    global REFRESH_TIME
    global STEP_SIZE
    global STEP_SIZE
    global LEFT_TURN
    global RIGHT_TURN

    global BALL_START_X1
    global BALL_START_Y1
    global BALL_START_X2
    global BALL_START_Y2

    global ACTUAL_START_X1
    global ACTUAL_START_Y1
    global ACTUAL_START_X2
    global ACTUAL_START_Y2

    global BALL_POS_X
    global BALL_POS_Y

    global NUM_BOXES

    global NUM_NAILS_FLOORS

    global NAIL_DIAMETER
    global NAIL_X
    global NAIL_Y
    global NAIL_CENTER

    global DIRECTION

    global NUM_BALLS

    NUM_BOXES = 13
    NUM_NAILS_FLOORS = 13

    WIDTH_CANVAS = 500; HEIGHT_CANVAS = 500
    BALL_SIZE = 10
    REFRESH_TIME =  15

    # STARTING BALL COORDS
    BALL_START_X1 = (WIDTH_CANVAS/2) - (BALL_SIZE/2)
    BALL_START_Y1 = 0
    BALL_START_X2 = (WIDTH_CANVAS/2) + (BALL_SIZE/2)
    BALL_START_Y2 = BALL_SIZE

    NAIL_DIAMETER = 5
    NAIL_X = WIDTH_CANVAS/(NUM_BOXES + 2)
    NAIL_Y = ((HEIGHT_CANVAS/4) * 3) / NUM_NAILS_FLOORS
    NAIL_CENTER = NAIL_DIAMETER / 2

    # STEP_SIZE_X = NAIL_Y/(NAIL_X*2)
    # STEP_SIZE_X = ((HEIGHT_CANVAS*(3/4))/NUM_NAILS_FLOORS) / ((WIDTH_CANVAS/NUM_BOXES)/2)

    SLOPE_Y = ((HEIGHT_CANVAS/25) * 24) - ((HEIGHT_CANVAS/4) * 3)
    SLOPE_X = (WIDTH_CANVAS/(NUM_BOXES + 2)) * (NUM_BOXES + 1)-(WIDTH_CANVAS/(NUM_BOXES + 2))

    STEP_SIZE = 1

    global  SLOPE
    SLOPE = SLOPE_Y / SLOPE_X

    LEFT_TURN = -SLOPE
    RIGHT_TURN = SLOPE

    NUM_BALLS = 50

class MAIN:

    def __init__ (self, master = None):
        self.master = master

        self.x = 0
        self.y = STEP_SIZE

        # CREATE WINDOW
        self.canvas = Canvas(width=WIDTH_CANVAS, height=HEIGHT_CANVAS)
        self.canvas['bg'] = 'black'

        self.drawBall()
        self.drawBox()
        self.drawNail()
        self.canvas.pack()
        self.moveBall()
        print(SLOPE)

    def drawBall(self):
        self.ball = self.canvas.create_oval(BALL_START_X1,
                                            BALL_START_Y1,
                                            BALL_START_X2,
                                            BALL_START_Y2,
                                            fill = 'green')

    def getCoords(self):
        # GET START AND FINAL X POSITION
        ACTUAL_BALL_X1 = self.canvas.coords(self.ball)[0]
        ACTUAL_BALL_X2 = self.canvas.coords(self.ball)[2]
        # GET START AND FINAL Y POSITION
        ACTUAL_BALL_Y1 = self.canvas.coords(self.ball)[1]
        ACTUAL_BALL_Y2 = self.canvas.coords(self.ball)[3]

        # REST FINAL POSITION MINUS HALF THE DIFERENCE WITH START TO FIND THE MID PART
        BALL_CENTER_X = ACTUAL_BALL_X2 - ((ACTUAL_BALL_X2 - ACTUAL_BALL_X1) / 2)
        BALL_CENTER_Y = ACTUAL_BALL_Y2 - ((ACTUAL_BALL_Y2 - ACTUAL_BALL_Y1) / 2)

        BALL_POS = [BALL_CENTER_X,BALL_CENTER_Y]

        return BALL_POS

    def moveBall(self):
        self.canvas.move(self.ball,self.x,self.y)
        self.canvas.after(REFRESH_TIME,self.moveBall)

        BORDER_RIGHT = (WIDTH_CANVAS/(NUM_BOXES + 2)) * (NUM_BOXES + 1)
        BORDER_LEFT = WIDTH_CANVAS/(NUM_BOXES + 2)

        for x in range(1, NUM_NAILS_FLOORS, 1):
            if round(self.getCoords()[1]) == round(NAIL_Y * x):
                self.y = STEP_SIZE

                DIRECTION = random.randint(0,1)
                # 1 FOR RIGHT
                # 0 FOR LEFT
                if DIRECTION == 1:
                    # IF TOUCHING THE RIGHT BORDER, BOUNCE TO LEFT
                    if self.getCoords()[0] < BORDER_RIGHT:
                        self.x = RIGHT_TURN
                    else:
                        self.x = LEFT_TURN
                else:
                    # IF TOUCHING THE LEFT BORDER, BOUNCE TO RIGHT
                    if self.getCoords()[0] > BORDER_LEFT:
                        self.x = LEFT_TURN
                    else:
                        self.x = RIGHT_TURN

            if self.getCoords()[1] >= (HEIGHT_CANVAS/4) * 3:
                self.x = 0
            if  round(self.getCoords()[1]) == (HEIGHT_CANVAS/25) * 24:
                self.y = 0

    def drawBox(self):

        # NUM_BOXES += 2 TO ELIMINATE LEFT AND RIGHT BORDER
        # REST 1 TO NUM_BOXES TO STOP BEFORE RIGHT BORDER
        CONT_X1 = WIDTH_CANVAS/(NUM_BOXES + 2)
        CONT_X2 = (WIDTH_CANVAS/(NUM_BOXES + 2)) * (NUM_BOXES + 1)
        CONT_Y1 = (HEIGHT_CANVAS/4) * 3
        CONT_Y2 = (HEIGHT_CANVAS/25) * 24
        self.container = self.canvas.create_rectangle(CONT_X1,
                                                      CONT_Y1,
                                                      CONT_X2,
                                                      CONT_Y2,
                                                      outline='white')

        SEPARATOR_Y2 = CONT_Y2
        SEPARATOR_Y1 = CONT_Y1
        for i in range(2, NUM_BOXES+1, 1):
            SEPARATOR_X = (WIDTH_CANVAS/(NUM_BOXES + 2)) * i
            self.separation = self.canvas.create_line(SEPARATOR_X,
                                                      SEPARATOR_Y1,
                                                      SEPARATOR_X,
                                                      SEPARATOR_Y2,
                                                      fill='white')

        self.border_left = self.canvas.create_line(CONT_X1,
                                                   0,
                                                   CONT_X1,
                                                   CONT_Y2,
                                                   fill='red')

        self.border_right = self.canvas.create_line(CONT_X2,
                                                    0,
                                                    CONT_X2,
                                                    CONT_Y2,
                                                    fill='red')

    def drawNail(self):
        # THIS IS WHEN THE NAILS ARE IN THE MIDDLE OF THE BOXES
        for i in range(1, NUM_NAILS_FLOORS, 2):
            for x in range(3,(NUM_BOXES*2) + 2, 2):
                self.nail = self.canvas.create_oval(((NAIL_X * x) / 2) - NAIL_CENTER,
                                                    (NAIL_Y * i) - NAIL_CENTER,
                                                    ((NAIL_X * x) / 2) + NAIL_CENTER,
                                                    (NAIL_Y * i) + NAIL_CENTER,
                                                    fill='white')

        # THIS IS WHEN THE NAILS ARE IN THE BOXES' COORDS DIRECTION
        for i in range(2, NUM_NAILS_FLOORS, 2):
            for x in range(2,NUM_BOXES+1, 1):
                self.nail = self.canvas.create_oval((NAIL_X * x) - NAIL_CENTER,
                                                    (NAIL_Y * i) - NAIL_CENTER,
                                                    (NAIL_X * x) + NAIL_CENTER,
                                                    (NAIL_Y * i) + NAIL_CENTER,
                                                    fill='white')

master = Tk()
main = MAIN(master)
mainloop()


#solution 1
#O(m*n)

def zero_matrix(a):
    m = len(a)
    n = len(a[0])
    f1 = False
    f2 = False
    for row in a:
        if sum(row) == 0:
            f1 = True
            break
    for i in range(n):
        col = 0
        for j in range(m):
            col += a[j][i]
        if col == 0:
            f2 = True
            break
    return f1 and f2

if __name__ == '__main__':
    print(zero_matrix([[0,0],[0,0]]))
    print(zero_matrix([[1,0],[0,1]]))


from django.contrib import admin

from .models import Team

class CompetitionInline(admin.StackedInline):
    model = Team.competition.through

class TeamAdmin(admin.ModelAdmin):
    fieldsets = [
        (None, {
            'fields': [
                'id',
                'name',
                'code',
                'short_name',
                'squad_market_value',
                'crest_url',
            ]
        }),
    ]
    inlines = [CompetitionInline]
    list_display = (
        'id',
        'name',
        'code',
        'short_name',
        'squad_market_value',
        'crest_url',
    )
    readonly_fields = (
        'id',
        'crest_url',
    )
    search_fields = [
        'name',
        'short_name',
    ]

admin.site.register(Team, TeamAdmin)


#!/usr/bin/env python

# Faster script + multiprocessing
# Script that calculates cfd score for targets with bulge 'X', and save the accumulated cfd score for the input guide
# Also calculates the Doench score if the targets has bulge 'X' and 0 mms (doench = 0 if no such target exists)

# argv 1 = target file
# argv 2 is genome_directory (eg ../../Genomes/hg19/)
# argv 3 is pam file -> to check if len is 23 and pam is NGG
# argv 4 is guide file

# Block scikit warnings
import multiprocessing
import itertools
import string
import azimuth.model_comparison
import subprocess
import numpy as np
from os.path import isfile, join
from os import listdir
import os
import sys
import re
import pickle
import time
import warnings
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings('ignore', category=UserWarning)

SIZE_DOENCH = 10000
N_THR = 3
# doench_string.append(seq)
# doench_score =  azimuth.model_comparison.predict(np.asarray(doench_string), None, None, model= model, pam_audit=False)
# doench_score = np.around(doench_score * 100)

def doenchParallel(targets, model, result):
    start_time = time.time()
    doench_score = azimuth.model_comparison.predict(
        targets, None, None, model=model, pam_audit=False)
    doench_score = [np.around(i * 100) for i in doench_score]
    max_doench = int(max(doench_score))
    result.append(max_doench)

def doenchForIupac(sequence_doench, guide_seq):
    pos_iupac = []
    var = []
    for pos, c in enumerate(sequence_doench):
        if c in iupac_code:
            pos_iupac.append(pos)
            var.append(iupac_code[c])

    if var:
        for i in itertools.product(*var):
            t = list(sequence_doench)
            for p, el in enumerate(pos_iupac):
                t[el] = i[p]
            targets_for_doench[guide_seq].append(''.join(t))
    else:
        targets_for_doench[guide_seq].append(sequence_doench)

def get_mm_pam_scores():
    try:
        mm_scores = pickle.load(open(os.path.dirname(
            os.path.realpath(__file__)) + '/mismatch_score.pkl', 'rb'))
        pam_scores = pickle.load(open(os.path.dirname(
            os.path.realpath(__file__)) + '/PAM_scores.pkl', 'rb'))
        return (mm_scores, pam_scores)
    except:
        raise Exception(
            "Could not find file with mismatch scores or PAM scores")

def revcom(s):
    basecomp = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'U': 'A', '-': '-'}
    letters = list(s[::-1])
    try:
        letters = [basecomp[base] for base in letters]
    except:
        return None
    return ''.join(letters)

# Calculates CFD score
def calc_cfd(guide_seq, sg, pam, mm_scores, pam_scores):

    score = 1
    sg = sg.replace('T', 'U')
    guide_seq = guide_seq.replace('T', 'U')
    s_list = list(sg)
    guide_seq_list = list(guide_seq)

    for i, sl in enumerate(s_list):
        if guide_seq_list[i] == sl:
            score *= 1

        else:
            try:  # Catch exception if IUPAC character
                key = 'r' + guide_seq_list[i] + \
                    ':d' + revcom(sl) + ',' + str(i + 1)
            except Exception as e:
                score = 0
                break
            try:
                score *= mm_scores[key]
            except Exception as e:  # If '-' is in first position, i do not have the score for that position
                pass

    score *= pam_scores[pam]
    return score

tab = str.maketrans("ACTGRYSWMKHDBVactgryswmkhdbv",
                    "TGACYRSWKMDHVBtgacyrswkmdhvb")

def reverse_complement_table(seq):
    return seq.translate(tab)[::-1]
# if __name__ == '__main__':

mm_scores, pam_scores = get_mm_pam_scores()
guides_dict = dict()
guides_dict_doench = dict()
targets_for_doench = dict()

score_filename = sys.argv[1].strip().split('.targets.txt')[0] + '.scores.txt'
targets_score_file = sys.argv[1].strip().split('.targets.txt')[
    0] + '.targets.CFD.txt'
bedfile_tmp_name = sys.argv[1].strip().split('.targets.txt')[
    0] + '.bedfile_tmp.bed'
remove_bedfile_tmp = False
with open(sys.argv[3]) as pamfile:
    line = pamfile.readline().strip().split(' ')
    if len(line[0]) != 23:
        with open(score_filename, 'w+') as result:
            result.write('NO SCORES')
            exit()
    if 'NGG' not in line[0]:
        print('WARNING: The model used for the CFD and Doench scores are based on the NGG PAM, the scores may not be valid for other PAMs')

N_THR = multiprocessing.cpu_count() // 2

iupac_code = {
    "R": ("A", "G"),
    "Y": ("C", "T"),
    "S": ("G", "C"),
    "W": ("A", "T"),
    "K": ("G", "T"),
    "M": ("A", "C"),
    "B": ("C", "G", "T"),
    "D": ("A", "G", "T"),
    "H": ("A", "C", "T"),
    "V": ("A", "C", "G"),
    "r": ("A", "G"),
    "y": ("C", "T"),
    "s": ("G", "C"),
    "w": ("A", "T"),
    "k": ("G", "T"),
    "m": ("A", "C"),
    "b": ("C", "G", "T"),
    "d": ("A", "G", "T"),
    "h": ("A", "C", "T"),
    "v": ("A", "C", "G"),
}

start = time.time()

# Get list of chromosomes file to set enr_str
chromosome_files = [f for f in listdir(
    sys.argv[2]) if isfile(join(sys.argv[2], f))]
# enr = sys.argv[2].split('/')
enr_str = ''
chr_ext = '.fa'
if '.enriched.' in chromosome_files[0]:
    enr_str = '.enriched'
elif '.indels.' in chromosome_files[0]:
    enr_str = '.indels'
if '.fasta' in chromosome_files[0]:
    chr_ext = '.fasta'
# if enr[-1]:
#   if'+' in enr[-1]:
#     enr_str = '.enriched'
# else:
#   if'+' in enr[-2]:
#     enr_str = '.enriched'

with open(os.path.dirname(os.path.realpath(__file__)) + "/azimuth/saved_models/V3_model_nopos.pickle", 'rb') as f:
    model = pickle.load(f)
max_doench = 0
sum_cfd = 0

# NOTE uncomment for progress bas
# process = subprocess.Popen(['wc', '-l', sys.argv[1]], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# out, err = process.communicate()
# total_line = int(out.decode('UTF-8').split(' ')[0])
# if total_line < 2:
#     print('WARNING! Input file has no targets')
#     sys.exit()
# if total_line < 10:
#     mod_tot_line = 1
# else:
#     mod_tot_line = int(total_line/90)
# lines_processed = 0

bulge_pos = 8
all_word = []
with open(sys.argv[1]) as result, open(targets_score_file, 'w+') as save_targ_scor:
    save_targ_scor.write(next(result).strip() + '\tCFD\n')  # Add header
    # Calc CDF score
    for target in result:
        target = target.strip().split('\t')
        # print(target)

        guide_seq = target[1]
        off = target[2].upper()
        m_guide_seq = re.search('[^ATCGN-]', guide_seq)
        m_off = re.search('[^ATCG-]', off)
        iup_off = []
        first = True
        start_iup_off = 1

        if (m_guide_seq is None) and (m_off is None):

            # Calc CFD

            pam = off[-2:]
            sg = off[:-3]
            #print("off. ", off)
            #print ("sg: ", sg)
            #print ("guide_seq: ", guide_seq)
            if target[0] == 'DNA':
                # print('tests', guide_seq[int(target[bulge_pos]):], off[int(
                # target[bulge_pos]):-3])
                cfd_score = calc_cfd(guide_seq[int(target[bulge_pos]):], off[int(
                    target[bulge_pos]):-3], pam, mm_scores, pam_scores)
            else:
                cfd_score = calc_cfd(guide_seq, sg, pam, mm_scores, pam_scores)
            if (target[bulge_pos + 1] == '0'):
                # estraggo sequenza
                with open(bedfile_tmp_name, 'w+') as bedfile:
                    remove_bedfile_tmp = True
                    if target[6] == '+':
                        bedfile.write(
                            target[3] + '\t' + str(int(target[4]) - 4) + '\t' + str(int(target[4]) + 23 + 3))
                    else:
                        bedfile.write(
                            target[3] + '\t' + str(int(target[4]) - 3) + '\t' + str(int(target[4]) + 23 + 4))

                extr = subprocess.Popen(['bedtools getfasta -fi ' + sys.argv[2] + '/' + target[3] +
                                         enr_str + chr_ext + ' -bed ' + bedfile_tmp_name], shell=True, stdout=subprocess.PIPE)
                extr.wait()
                out, err = extr.communicate()
                out = out.decode('UTF-8')
                if target[6] == '+':
                    sequence_doench = out.strip().split('\n')[-1].upper()
                else:
                    sequence_doench = reverse_complement_table(
                        out.strip().split('\n')[-1].upper())

                if target[1] not in targets_for_doench:
                    targets_for_doench[target[1]] = []
                # Get all possible targets with iupac itertools for doench
                doenchForIupac(sequence_doench, target[1])

            save_targ_scor.write('\t'.join(target) +
                                 '\t' + str(cfd_score) + '\n')
            sum_cfd = sum_cfd + cfd_score
            try:
                guides_dict[target[1]] = guides_dict[target[1]] + cfd_score
            except:
                guides_dict[target[1]] = cfd_score

        else:
            if "N" in off:
                continue
            if (target[bulge_pos + 1] == '0'):
                with open(bedfile_tmp_name, 'w+') as bedfile:
                    remove_bedfile_tmp = True
                    if target[6] == '+':
                        bedfile.write(
                            target[3] + '\t' + str(int(target[4]) - 4) + '\t' + str(int(target[4]) + 23 + 3))
                    else:
                        bedfile.write(
                            target[3] + '\t' + str(int(target[4]) - 3) + '\t' + str(int(target[4]) + 23 + 4))

                extr = subprocess.Popen(['bedtools getfasta -fi ' + sys.argv[2] + '/' + target[3] +
                                         enr_str + chr_ext + ' -bed ' + bedfile_tmp_name], shell=True, stdout=subprocess.PIPE)
                extr.wait()
                out, err = extr.communicate()
                out = out.decode('UTF-8')
                if target[6] == '+':
                    sequence_doench = out.strip().split('\n')[-1].upper()
                else:
                    sequence_doench = reverse_complement_table(
                        out.strip().split('\n')[-1].upper())

                if target[1] not in targets_for_doench:
                    targets_for_doench[target[1]] = []
                # Get all possible targets with iupac itertools for doench
                doenchForIupac(sequence_doench, target[1])

            i = 0
            for char in off:
                if char in iupac_code:
                    n = len(iup_off)
                    for list_char in iupac_code[char]:
                        if not first:
                            for test in range(n - start_iup_off, n):
                                iup_off.append(
                                    iup_off[test][:i] + list_char + iup_off[test][i+1:])

                        else:
                            iup_off.append(off[:i] + list_char + off[i+1:])
                    first = False
                    start_iup_off = start_iup_off * len(iupac_code[char])

                i += 1
            dna_gap_removal = True
            for no_iup_str in range(len(iup_off) - start_iup_off, len(iup_off)):

                # se non ci sono gap passo la stringa non modificata al calc_cfd
                no_iup_gap_srt = iup_off[no_iup_str]

                # Calc CFD

                pam = no_iup_gap_srt[-2:]
                sg = no_iup_gap_srt[:-3]
                if target[0] == 'DNA':
                    cfd_score = calc_cfd(guide_seq[int(target[bulge_pos]):], sg[int(
                        target[bulge_pos]):], pam, mm_scores, pam_scores)
                else:
                    cfd_score = calc_cfd(
                        guide_seq, sg, pam, mm_scores, pam_scores)
                sum_cfd = sum_cfd + cfd_score
                try:
                    guides_dict[target[1]] = guides_dict[target[1]] + cfd_score
                except:
                    guides_dict[target[1]] = cfd_score

                # Recalculate mismatch value, only for pam at end with length 3 (eg NGG)
                mm_new_t = 0
                guide_no_pam = guide_seq[:-3]
                list_t = list(no_iup_gap_srt)
                for position_t, char_t in enumerate(no_iup_gap_srt[:-3]):
                    if char_t.upper() != guide_no_pam[position_t]:
                        mm_new_t += 1
                        if guide_no_pam[position_t] != '-':
                            list_t[position_t] = char_t.lower()

                target[2] = ''.join(list_t)
                target[bulge_pos - 1] = str(mm_new_t - int(target[bulge_pos]))
                # total differences between targets and guide (mismatches + bulges)
                target[bulge_pos + 1] = str(mm_new_t)
                save_targ_scor.write('\t'.join(target) +
                                     '\t' + str(cfd_score) + '\n')
        # NOTE decomment for progress bar
        # lines_processed +=1
        # if lines_processed % (mod_tot_line) == 0:
        #     print('Scoring: Total progress ' + str(round(lines_processed /total_line *100, 2)) + '%')

job_id = sys.argv[1].split('/')[-1].split('.')[0]

all_scores = []
with open(score_filename, 'w+') as res, open(sys.argv[4], 'r') as guides:
    man = multiprocessing.Manager()
    shared_doench = man.list()  # list containing max doech for each thread
    guides = guides.read().strip().split('\n')
    for g in guides:
        guides_dict_doench[g] = 0
        if g not in guides_dict:
            guides_dict[g] = 0
    # for k in guides_dict.keys():
        if g not in targets_for_doench:
            guides_dict_doench[g] = 0
        else:
            if len(targets_for_doench[g]) > SIZE_DOENCH:
                jobs = []
                remaining_splits = (
                    len(targets_for_doench[g])//SIZE_DOENCH) + 1
                for i in range((len(targets_for_doench[g])//SIZE_DOENCH) + 1):
                    for thr in range(min(N_THR, remaining_splits)):
                        p = multiprocessing.Process(target=doenchParallel, args=(np.asarray(targets_for_doench[g][i*N_THR*SIZE_DOENCH + thr*SIZE_DOENCH: min(
                            i*N_THR*SIZE_DOENCH + (thr+1)*SIZE_DOENCH, len(targets_for_doench[g]))]), model, shared_doench,))
                        remaining_splits -= 1
                        p.start()
                        jobs.append(p)
                    for i in jobs:
                        i.join()

                guides_dict_doench[g] = max(shared_doench)
                shared_doench = man.list()
            else:
                start_time = time.time()
                doench_score = azimuth.model_comparison.predict(np.asarray(
                    targets_for_doench[g]), None, None, model=model, pam_audit=False)
                doench_score = [np.around(i * 100) for i in doench_score]
                guides_dict_doench[g] = int(max(doench_score))
        if guides_dict[g] == 0:  # NO CFD WAS CALCULATED
            all_scores.append([g, 0, str(guides_dict_doench[g])])
        else:
            all_scores.append(
                [g, int(round((100/(100 + guides_dict[g]))*100)), str(guides_dict_doench[g])])
    all_scores.sort(key=lambda x: x[1], reverse=True)
    res.write('#crRNA\tCFD\tDoench 2016\n')
    for guide_scored in all_scores:
        res.write('\t'.join([str(el) for el in guide_scored]) + '\n')

if remove_bedfile_tmp:
    os.remove(bedfile_tmp_name)
end = time.time()


from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.db.models import Max
from django.template import loader
from .models import Members
from .forms import Trsc,Usearch,AddR,AddST,AddT,AddRT
import json

from home.models import RouteStation,Station,Route,Trains,Reservation,Add_Train
def getTrains(request):
    if request.method=='POST':
        form=Usearch(request.POST)
        if form.is_valid():

            data=form.cleaned_data
            src=data['src']
            des=data['des']
            a=RouteStation.objects.filter(sid=des)
            x=[]
            o=0
            for i in a:
                tno=i.tno
                b=RouteStation.objects.filter(tno=tno,sid=src)
                for j in b:
                    if j.order<i.order:
                        x.append(j)
                        o=i.order-j.order

        else:
            return HttpResponse('
invalid Data
')
        return render(request,'features/trains.html',{'data':x,'o':o,'src':src,'des':des})
    return HttpResponse('
Wrong REq
')

def schedule(request):
    a=Trains.objects.all()
    return render(request,'features/schedule.html',{'a':a})

def getTinfo(request):
    form=Trsc(request.GET)
    if form.is_valid():
        data=form.cleaned_data
        tno=data['tnum']
        a=RouteStation.objects.filter(tno=tno).order_by('order')

        return render(request,'features/trinfo.html',{'data':a})

    return HttpResponse('
DAta invalid
')

def search(request):
    a=Station.objects.all()
    return render(request,'features/seat.html',{'a':a})

def pnr(request):
    if request.method=='POST':
        pnr=request.POST['pnr']
        a=Reservation.objects.filter(pnr=pnr)

        return render(request,'features/pnr.html',{'r':a})

    return render(request,'features/pnr.html')


from typing import List

class Solution:
    def heightChecker(self, heights: List[int]) -> int:

        expected = sorted(heights)
        idx = 0
        count = 0
        while idx < len(heights):
            if heights[idx] != expected[idx]:
                count += 1
            idx += 1
        return count


from __future__ import print_function
import sys
import os
if sys.version_info[0] == 2:
	import unicodecsv as csv
elif sys.version_info[0] == 3:
	import csv
import logging

"""
MIT License
Copyright (c) 2018 Chapin Bryce, Preston Miller
Please share comments and questions at:
  https://github.com/PythonForensics/Learning-Python-for-Forensics
  or email pyforcookbook@gmail.com

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""

def csv_writer(output_data, headers, output_dir, output_name):
	"""
	The csv_writer function uses the csv DictWriter module to
	write the list of dictionaries. The	DictWriter can take
	a fieldnames argument, as a list, which represents the
	desired order of columns.
	:param output_data: The list of dictionaries containing
	embedded metadata.
	:param headers: A list of keys in the dictionary that
	represent the desired order of columns in the output.
	:param output_dir: The folder to write the output CSV to.
	:param output_name: The name of the output CSV.
	:return:
	"""
	msg = 'Writing ' + output_name + ' CSV output.'
	print('[+]', msg)
	logging.info(msg)

	out_file = os.path.join(output_dir, output_name)

	if sys.version_info[0] == 2:
		csvfile = open(out_file, "wb")
	elif sys.version_info[0] == 3:
		csvfile = open(out_file, "w", newline='',
		encoding='utf-8')

	with csvfile:
		# We use DictWriter instead of Writer to write
		# dictionaries to CSV.
		writer = csv.DictWriter(csvfile, fieldnames=headers)

		# Writerheader writes the header based on the supplied
		# headers object
		writer.writeheader()
		for dictionary in output_data:
			if dictionary:
				writer.writerow(dictionary)


# ==============================================
#	GENERAL MESSAGES
# ==============================================
begin_msg = "Starting SQLHunt..."
continue_msg = "The attack seems to have a specific attack option"
payload_verification_msg = "Testing if the payload works..."
not_implemented_attack_msg = "This attack has not been implemented yet."

# ==============================================
#	WARNING MESSAGES
# ==============================================
warning_url_with_payload_without_params = "The URL seems to have an injection statement but no option has been precised"

# ==============================================
#	EROOR MESSAGES
# ==============================================
invalid_url = "Invalid URL"
invalid_specified_attack = "The option is invalid or not available yet"
error_urllib_exception = "The page doesn't respond or the network is unreachable"


import libtcodpy as libtcod
from render_functions import RenderOrder
from random import randint

from components.ai import BasicMonster
from components.fighter import Fighter
from components.item import Item

from entity import Entity
from game_messages import Message

from item_functions import cast_confuse, cast_fireball, cast_lightning, heal
from map_objects.rectangle import Rect
from map_objects.tile import Tile

class GameMap:

    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.tiles = self.initialize_tiles()

    def initialize_tiles(self):
        tiles = [[Tile(True) for y in range(self.height)] for x in range(self.width)]
        return tiles

    def make_map(self, max_rooms, room_min_size, room_max_size, map_width, map_height, player, entities,
                 max_monsters_per_room, max_items_per_room):

        rooms = []
        num_rooms = 0

        for r in range(max_rooms):
            # random width and height
            w = randint(room_min_size, room_max_size)
            h = randint(room_min_size, room_max_size)
            # random position without going out of the boundaries of the map
            x = randint(0, map_width - w - 1)
            y = randint(0, map_height - h - 1)

             # "Rect" class makes rectangles easier to work with
            new_room = Rect(x, y, w, h)

            # run through the other rooms and see if they intersect with this one
            for other_room in rooms:
                if new_room.intersect(other_room):
                    break
            else:
                # this means there are no intersections, so this room is valid

                # "paint" it to the map's tiles
                self.create_room(new_room)

                # center coordinates of new room, will be useful later
                (new_x, new_y) = new_room.center()

                if num_rooms == 0:
                    # this is the first room, where the player starts at
                    player.x = new_x
                    player.y = new_y
                else:
                    # all rooms after the first:
                    # connect it to the previous room with a tunnel

                    # center coordinates of previous room
                    (prev_x, prev_y) = rooms[num_rooms - 1].center()

                    # flip a coin (random number that is either 0 or 1)
                    if randint(0, 1) == 1:
                        # first move horizontally, then vertically
                        self.create_h_tunnel(prev_x, new_x, prev_y)
                        self.create_v_tunnel(prev_y, new_y, new_x)
                    else:
                        # first move vertically, then horizontally
                        self.create_v_tunnel(prev_y, new_y, prev_x)
                        self.create_h_tunnel(prev_x, new_x, new_y)
                self.place_entities(new_room, entities, max_monsters_per_room, max_items_per_room)
                # finally, append the new room to the list
                rooms.append(new_room)
                num_rooms += 1

    def create_room(self, room):
        # go through the tiles in the rectangle and make them passable
        for x in range(room.x1 + 1, room.x2):
            for y in range(room.y1 + 1, room.y2):
                self.tiles[x][y].blocked = False
                self.tiles[x][y].block_sight = False

    def create_h_tunnel(self, x1, x2, y):
        for x in range(min(x1, x2), max(x1, x2) + 1):
            self.tiles[x][y].blocked = False
            self.tiles[x][y].block_sight = False

    def create_v_tunnel(self, y1, y2, x):
        for y in range(min(y1, y2), max(y1, y2) + 1):
            self.tiles[x][y].blocked = False
            self.tiles[x][y].block_sight = False

    def place_entities(self, room, entities, max_monsters_per_room, max_items_per_room):
        # Get a random number of monsters
        number_of_monsters = randint(0, max_monsters_per_room)
        number_of_items = randint(0, max_items_per_room)
        for i in range(number_of_monsters):
            # Choose a random location in the room
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)

            if not any([entity for entity in entities if entity.x == x and entity.y == y]):
                if randint(0, 100) < 80:
                    fighter_component = Fighter(hp=10, defense=0, power=3)
                    ai_component = BasicMonster()
                    monster = Entity(x, y, 'o', libtcod.desaturated_green, 'Orc', blocks=True,
                                     render_order=RenderOrder.ACTOR, fighter=fighter_component, ai=ai_component)
                else:
                    fighter_component = Fighter(hp=16, defense=1, power=4)
                    ai_component = BasicMonster()

                    monster = Entity(x, y, 'T', libtcod.darker_green, 'Troll', blocks=True, fighter=fighter_component,
                                     render_order=RenderOrder.ACTOR, ai=ai_component)

                entities.append(monster)
        for i in range(number_of_items):
            x = randint(room.x1 + 1, room.x2 - 1)
            y = randint(room.y1 + 1, room.y2 - 1)
            if not any([entity for entity in entities if entity.x == x and entity.y == y]):
                item_chance = randint(0, 100)

                if item_chance < 70:
                    item_component = Item(use_function=heal, amount=4)
                    item = Entity(x, y, '!', libtcod.violet, 'Healing Potion', render_order=RenderOrder.ITEM,
                                    item=item_component)
                elif item_chance < 80:
                    item_component = Item(use_function=cast_fireball, targeting=True, targeting_message=Message(
                        'Left-click a target tile for the fireball, or right-click to cancel.', libtcod.light_cyan),
                                          damage=12, radius=3)
                    item = Entity(x, y, '#', libtcod.red, 'Fireball Scroll', render_order=RenderOrder.ITEM,
                                  item=item_component)
                elif item_chance < 90:
                    item_component = Item(use_function=cast_confuse, targeting=True, targeting_message=Message(
                        'Left-click an enemy to confuse it, or right-click to cancel.', libtcod.light_cyan))
                    item = Entity(x, y, '#', libtcod.light_pink, 'Confusion Scroll', render_order=RenderOrder.ITEM,
                                  item=item_component)
                else:
                    item_component = Item(use_function=cast_lightning, damage=20, maximum_range=5)
                    item = Entity(x, y, '#', libtcod.yellow, 'Lightning Scroll', render_order=RenderOrder.ITEM,
                                  item=item_component)
                entities.append(item)

    def is_blocked(self, x, y):
        if self.tiles[x][y].blocked:
            return True
        return False


import discord, pytz, config
from datetime import datetime, timezone, timedelta
from varname import varname, nameof

client = discord.Client()

@client.event
async def on_ready():
	print('We have logged in as {0.user}'.format(client))
	return

async def invalid(message):
	return

async def print_help(message):
	await message.channel.send('`Basic commands:\n\nprefix: .\nhelp : Help\ntimefrance : Local time in Paris, France\ntimecanada: Local time in Toronto, Canada\ntime : Local time\nschedule: Schedule`')

async def print_schedule(message):
	await message.channel.send(file=discord.File('schedule_zaidane.png'))

async def print_time(message):
	if message.author.id == 211840395141840897:
		tz = pytz.timezone('America/Toronto')
		time = datetime.now(tz).strftime('%A %d/%m/%Y\n%H:%M %p Toronto Time')
	else:
		tz = pytz.timezone('Europe/Paris')
		time = datetime.now(tz).strftime('%A %d/%m/%Y\n%H:%M %p Paris Time')
	await message.channel.send(time)

async def print_timeParis(message):
	tz = pytz.timezone('Europe/Paris')
	time = datetime.now(tz).strftime('%A %d/%m/%Y\n%H:%M %p Paris Time')
	await message.channel.send(time)

async def print_timeToronto(message):
	tz = pytz.timezone('America/Toronto')
	time = datetime.now(tz, ).strftime('%A %d/%m/%Y\n%H:%M %p Toronto Time')
	await message.channel.send(time)

def getCurrentTime():
	"""
	docstring
	"""
	return datetime.now()

def addThirtyMinutes(t):
	thirtyMinutes = timedelta(minutes = 30)
	t += thirtyMinutes
	return t

GNG = ((1,2,3),(),(13,15,16,17,18),(4,5,6),(),(),())
CSI = ((),(4,5,6,10,11,12),(),(7,8,9),(),(),())
CEG = ((13,14,15,16,17,18),(),(),(),(),(),())
JPN = ((),(21,22,23),(),(20,21,22,23,24,25,26,27),(),(),())

schedule = [[None]*31,[None]*31,[None]*31,[None]*31,[None]*31,[None]*31,[None]*31]

courses = [GNG, CSI, CEG, JPN]

for course in courses:
	for day in range(7):
		for period in range(len(course[day])):
			schedule[day][course[day][period]] = course

async def currentClass(message):
	currentDay = datetime.now().weekday()
	currentTime = getCurrentTime()
	t = currentTime.replace(hour=7, minute=30)
	blocks = [None]*31
	block = 0
	saved = 0
	nextClass = None
	for i in range(31):
		blocks[i] = addThirtyMinutes(t)
		t = addThirtyMinutes(t)

	for i in range(31):
		if blocks[i] <= currentTime < blocks[i+1]:
			block = i
			saved = i
			break

	while schedule[currentDay][saved] == None:
		saved += 1
	nextClass = blocks[saved]

	currentPeriod = schedule[currentDay][block]

	switcher = {
		GNG: 'GNG',
		CSI: 'CSI',
		CEG: 'CEG',
		JPN: 'JPN',
		None: 'no class',
	}
	currentClass = switcher.get(currentPeriod, 'Error')

	if schedule[currentDay][block] == None:
		await message.channel.send(config.bot['user'] + ' has ' + currentClass + ' right now. Their next class is at ' + nextClass.strftime('%A %d/%m/%Y %H:%M %p Toronto Time (%H:%M %p Paris Time)'))
	else:
		await message.channel.send(config.bot['user'] + ' has ' + currentClass + ' right now.')

#	currentDay = datetime.weekday()
#	time, t1, t2 = getCurrentTime()
#	m = 30
#	turn = 0
#	for i in range(8, 23):
#		if turn == 0:
#			t1 = getTodayTimeAt(t1, i, m)
#			t2 = getTodayTimeAt(t2, )
#			schedule.update(dict.fromkeys([]))
#			turn = 1
#		else:
#			t1 = getTodayTimeAt(t1, i)
#			turn = 0
#

@client.event
async def on_message(message):
	if message.author == client.user:
		return

	switcher = {
		'.invalid' : invalid
	}

	switcher.update(dict.fromkeys(['.help', '.h'], print_help))
	switcher.update(dict.fromkeys(['.time france', '.time f', '.timef', '.tf'], print_timeParis))
	switcher.update(dict.fromkeys(['.time canada', '.time c', '.timec', '.tt'], print_timeToronto))
	switcher.update(dict.fromkeys(['.time', '.t'], print_time))
	switcher.update(dict.fromkeys(['.schedule', '.s'], print_schedule))
	switcher.update(dict.fromkeys(['.current'], currentClass))

	if message.content in switcher:
		msg = message.content
	else:
		msg = '.invalid'

	func = switcher.get(msg, ".invalid")
	await func(message)

client.run(config.bot['token'])


from cloudcafe.common.tools.datagen import rand_name
from cloudroast.compute.fixtures import ComputeFixture
import unittest

class CreateServerTest(ComputeFixture):

    @classmethod
    def setUpClass(cls):
        super(CreateServerTest, cls).setUpClass()

        cls.boot_method = 'image'
        cls.volume_size = 80
        cls.nova_driver = 'xenserver'

        cls.name = rand_name("server")
        cls.metadata = {'meta_key_1': 'meta_value_1',
                        'meta_key_2': 'meta_value_2'}
        cls.image = cls.images_client.get_image(cls.image_ref).entity
        cls.flavor = cls.flavors_client.get_flavor_details(
            cls.flavor_ref).entity
        cls.create_resp = cls.server_behaviors.create_active_server(
            cls.name, cls.image.id, cls.flavor.id, metadata=cls.metadata)
        cls.server = cls.create_resp.entity
        cls.resources.add(cls.server.id, cls.servers_client.delete_server)

        # Expected parameters
        cls.expected_vcpus = cls.flavor.vcpus
        cls.expected_ram = cls.flavor.ram
        cls.expected_name = cls.name
        cls.expected_number_of_disks = 1 + int(
            cls.flavor.extra_specs.get('number_of_data_disks', 0))
        cls.expected_primary_disk = cls.determine_primary_disk_size(
            boot_method=cls.boot_method,
            flavor=cls.flavor,
            volume_size=80)
        cls.expected_image_id = cls.determine_image_id(
            boot_method=cls.boot_method,
            image=cls.image)
        cls.expected_xenstore_disk_config_enabled = cls.determine_xenstore_disk_config_enabled(cls.server)
        cls.expected_networks = cls.determine_expected_networks(cls.flavor)
        cls.expected_accessIPv4_address = ""
        cls.expected_accessIPv6_address = ""

    @classmethod
    def determine_disk_config(cls, disk_config, image):
        return disk_config if disk_config else image.disk_config

    @classmethod
    def determine_access_ip_address(cls, access_ip_address, ip_address):
        return access_ip_address if access_ip_address else ip_address

    @classmethod
    def determine_expected_networks(cls, flavor):
        expected_networks = []
        ip_v6_networking = True if flavor.extra_specs.get('class') != 'onmetal' else False
        expected_networks.append({"name": "public", "has_ip_v4": True, "has_ip_v6": ip_v6_networking})
        expected_networks.append({"name": "private", "has_ip_v6": True, "has_ip_v6": ip_v6_networking})
        return expected_networks

    @classmethod
    def determine_primary_disk_size(cls, boot_method, flavor, volume_size=0):
        if flavor.extra_specs.get('class') == 'onmetal':
            return 28
        elif boot_method == 'volume':
            return volume_size
        else:
            return flavor.disk

    @classmethod
    def determine_image_id(cls, boot_method, image):
        if boot_method == 'volume':
            return None
        return image.id

    @classmethod
    def determine_xenstore_disk_config_enabled(cls, server):
        actual_disk_config = server.disk_config
        return actual_disk_config.lower() == 'auto'

    def test_server_addresses(self):
        pass

    def test_created_server_image_field(self):
        actual_image_id = self.server.image.id if self.server.image is not None else None
        self.assertEqual(self.expected_image_id, actual_image_id)

    def test_can_log_into_server_after_creation(self):
        remote_client = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        self.assertTrue(remote_client.can_authenticate())

    def test_created_server_vcpus(self):
        remote_client = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        server_actual_vcpus = remote_client.get_number_of_cpus()
        self.assertEqual(server_actual_vcpus, self.expected_vcpus)

    def test_created_server_ram(self):
        remote_instance = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        lower_limit = int(self.expected_ram) - (int(self.expected_ram) * .1)
        server_ram_size = int(remote_instance.get_allocated_ram())
        self.assertTrue((int(self.expected_ram) == server_ram_size or lower_limit <= server_ram_size))

    def test_created_server_hostname(self):
        remote_client = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        hostname = remote_client.get_hostname()
        self.assertEqual(hostname, self.expected_name)

    def test_created_server_primary_disk(self):
        remote_client = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        disk_size = remote_client.get_disk_size(
            self.servers_config.instance_disk_path)
        self.assertEqual(disk_size, self.expected_primary_disk)

    def test_number_of_disks(self):
        remote_client = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        disks = remote_client.get_all_disks()
        self.assertEqual(self.expected_number_of_disks, len(disks))

    def test_created_server_xenstore_metadata(self):
        remote_client = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        xen_meta = remote_client.get_xen_user_metadata()
        for key, value in self.metadata.iteritems():
            self.assertIn(key, xen_meta)
            self.assertEqual(xen_meta[key], value)

    def test_xenstore_disk_config(self):
        remote_client = self.server_behaviors.get_remote_instance_client(
            self.server, self.servers_config)
        auto_config_enabled = remote_client.get_xenstore_disk_config_value()
        self.assertEqual(auto_config_enabled, self.expected_xenstore_disk_config_enabled)


# -*- coding:utf-8 -*-

import struct

from enumerate import *
from log import Log
from osdobject import OSDObject, OSDObjectType
from imageutil import ImageUtil

logger = Log.get_logger("engine")

class Palette(OSDObject):
    def __init__(self, scene, id, colors):
        self._id = id
        self._scene = scene
        self._lut = []
        if isinstance(colors, str):
            if colors == 'RGB24':
                self._pixel_format = PixelFormat.RGB
            else:
                raise Exception('Unknown colors %s' % colors)
        else:
            self._pixel_format = PixelFormat.LUT
            self._lut = colors

    def type(self):
        return OSDObjectType.PALETTE

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

    def color(self, index, based_color=None):
        if self._pixel_format == PixelFormat.RGB:
            return index
        else:
            assert index < len(self._lut), "{} should < {}".format(index, len(self._lut))
            return self._lut[index]

    @property
    def entry_bits(self):
        lut_len = len(self._lut)
        b = 1
        while (1 << b) < lut_len:
            b += 1
        return b

    def __str__(self):
        return "%s(id: %s, %s, size:%d)" % \
               (type(self), self._id, self._pixel_format, len(self._lut))

    def to_binary(self):
        """
        struct rgb {
            u8 r, g, b;
        }
        struct data {
            u8 pixel_format;
            u8 entry_bits;
            u16 lut_entry_count;
            rgb lut[lut_entry_count]
        };
        :return: binary
        """
        bins = struct.pack('<BBH', self._pixel_format.value,
                           self.entry_bits, len(self._lut))
        for i in range(len(self._lut)):
            r, g, b = ImageUtil.rgb(self._lut[i])
            bins += struct.pack('<BBB', r, g, b)
        while len(bins) % 4 != 0:
            bins += b'\x00'
        return bins


import pygame
import random
import numpy as np

buffer = 5
screen_width, screen_height = 1000, 600

config = {

    "large": {
        "number": 5,
        "location": int(.25*screen_height),
        "scale": int(.15*screen_width),
        "points": 10
        },
    "medium": {
        "number": 5,
        "location": int(.35*screen_height),
        "scale": int(.07*screen_width),
        "points": 25
        },
    "small": {
        "number": 5,
        "location": int(.45*screen_height),
        "scale": int(.05*screen_width),
        "points": 30
        }

}

class Target(pygame.sprite.Sprite):
    def __init__(self, image, x, y, points):
        super().__init__()
        self.image = image
        self.points = points
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y

    def get_score(self):
        return self.points

def generate_targets(screen, group):
    xs, ys = get_offsets(screen, group, buffer)
    return pygame.sprite.Group(
        [Target(load_image('target.png', group['scale']), xs[i], ys[i], group['points']) for i in range(group['number'])]
    )

def ranks(sample):
    indices = sorted(range(len(sample)), key=lambda i: sample[i])
    return sorted(indices, key=lambda i: indices[i])

def sample(n=40, k=4, d=10):
    sample = random.sample(range(n-(k-1)*(d-1)), k)
    return np.array([s + (d-1)*r for s, r in zip(sample, ranks(sample))])

def get_offsets(screen, group, buffer=10):
    return (sample(screen.get_width() - group['scale'] - buffer, group['number'], group['scale']) + buffer,
            np.full(group['number'], screen.get_height() - group['location'] - buffer))

def load_image(path, scale):
    return pygame.transform.scale(pygame.image.load(path).convert_alpha(), (scale, scale))

def generate_groups(screen, config):
    return [generate_targets(screen, params) for group, params in config.items()]

def check_hit(target_group, position, score):
    for target in target_group:
        if target.rect.collidepoint(position[0], position[1]):
            score += target.get_score()
            target_group.remove(target)
    return score

def get_count(targets):
    count = 0
    for group in targets:
        count += len(group.sprites())
    return count

# Initialize Pygame
pygame.init()
clock = pygame.time.Clock()
screen = pygame.display.set_mode((screen_width, screen_height))

background_image = pygame.transform.scale(pygame.image.load("background.jpg").convert(), (screen_width, screen_height))

crosshair_image = pygame.transform.scale(pygame.image.load('crosshair.png'), (int(.3*screen_width), int(.3*screen_width)))
crosshair_rect = crosshair_image.get_rect()

pygame.mouse.set_visible(False)

score = 0
targets = generate_groups(screen, config)

running = True
while running:
    # check for user events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                for group in targets:
                    score = check_hit(group, event.pos, score)

    screen.blit(background_image, (0, 0))
    for group in targets:
        group.draw(screen)

    crosshair_rect.center = pygame.mouse.get_pos()
    screen.blit(crosshair_image, crosshair_rect)
    screen.blit(pygame.font.Font(None, 36).render("Score: " + str(score), True, (255, 255, 255)), (10, 10))

    if get_count(targets) == 0:
        screen.blit(pygame.font.Font(None, 36).render("YOU WIN!", True, (255, 255, 255)), (.4*screen_height, 0.4*screen_width))

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

# Quit Pygame
pygame.quit()


import os
import argparse

def childs_function(file_directory):
	with open(file_directory, "r") as file1:
		total_lines = sum(1 for line in file1)
	fileObject = open(file_directory, "r")
	lines = fileObject.readlines()

	r,w = os.pipe()
	r_child,w_child = os.pipe()

	for n in range(total_lines):
		pid = os.fork()
		if pid == 0:
			os.close(w)
			os.close(r_child)
			r = os.fdopen(r, 'r')
			lineR = r.read()
			w_child = os.fdopen(w_child,'w')
			lineReverted = lineR[::-1]
			w_child.write(f"{lineReverted}")
			w_child.flush()
			w_child.close()
			os._exit(0)

	os.close(r)
	os.close(w_child)
	w = os.fdopen(w, 'w')

	for l in lines:
		w.write(l)

	w.close()

	r_child = os.fdopen(r_child)
	while True:
		line = r_child.read()
		if len(line) == 0:
			break
		print(line)

def main(args):
    variables = vars(args)

    childs_function(variables['f'])

if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	parser.add_argument("-f", help='archivo a leer')
	args = parser.parse_args()
	main(args)


import sys

import jpype
import jpype.imports
from jpype import JImplements, JOverride, JImplementationFor

import matplotlib.pyplot as plt

# ../dist/FinkBrowser.exe.jar
jpype.startJVM(jpype.getDefaultJVMPath(), "-ea", "-Djava.class.path=" + sys.argv[1], convertStrings=True)

from com.astrolabsoftware.FinkBrowser.HBaser import FinkHBaseClient
from com.astrolabsoftware.FinkBrowser.Utils  import Init

Init.init()

true  = jpype.java.lang.Boolean(True)
false = jpype.java.lang.Boolean(False)

#client = FinkHBaseClient("localhost", 2181)
client = FinkHBaseClient("134.158.74.54", 2181);
client.connect("ztf_season1", "schema_0.7.0_0.3.8")
#client.setLimit(10)

a17_x = [];
a17_y = [];
a19_x = [];
a19_y = [];
for r in client.scan("", "key:key:ZTF17", "i:ra,i:dec", 0, false, false).values():
  a17_x += [float(r['i:ra'])]
  a17_y += [float(r['i:dec'])]
for r in client.scan("", "key:key:ZTF19", "i:ra,i:dec", 0, false, false).values():
  a19_x += [float(r['i:ra'])]
  a19_y += [float(r['i:dec'])]

plt.plot(a17_x, a17_y, 'r.')
plt.plot(a19_x, a19_y, 'b.')
plt.title('ZTF17(red) + ZTF19(blue)')
plt.xlabel('ra')
plt.ylabel('dec')
plt.show()

client.close()

jpype.shutdownJVM()


import logging

from zelos.handles import SocketHandle
from zelos.manager import IManager

from .base_socket import BaseSelect, BaseSocket

class Network(IManager):
    def __init__(self, helpers, file_manager, tracer):
        super().__init__(helpers)
        self.file_manager = file_manager
        self.trace = tracer
        self.logger = logging.getLogger(__name__)
        self.attempted_connections = set()
        self.num_sockets = 0

        self.ignore_whitelist = False
        self.whitelist = {
            "127.0.0.53": [53]
            # '8.8.8.8': [53]
        }

        # Entries in the DNS whitelist will always result in a
        # successful DNS response. If real networking is used, and the
        # domain is non-existant, the response will be replaced with a
        # default IP. This is useful for ensuring network checks for
        # common domains succeed.
        self.dns_whitelist = {"google.com", "pastebin.com", "virustotal.com"}
        # Entries in the DNS blacklist will always result in an NXDOMAIN
        # result, whether using real networking or Base sockets. This
        # is useful making it appear as if hardcoded C2 hosts are
        # unavailable, which often invokes DGA functionality.
        self.dns_blacklist = {}

        # When returning a fake DNS response, use this IP address in the
        # answer. This could be pointed to a network simulator.
        self.dns_default_ip = "45.45.45.45"

        # By default, return non-existant (NX) responses for all
        # domains, except those listed in the whitelist.
        self.dns_default_to_nx = True

        self.socket_class = BaseSocket
        self.select = BaseSelect(self)

    @property
    def sockets(self):
        return self.handles.get_by_type(SocketHandle)

    def set_socket_class(self, socket_class):
        """
        Allows network activity to be handled by a different socket
        class.
        """
        self.socket_class = socket_class

    def set_select_class(self, select_class):
        """
        Allows select/poll to be handled by a different class.
        """
        self.select = select_class(self)

    def add_attempted_connection(self, string, method):
        self.attempted_connections.add(string)
        self.triggers.tr_contacts_domain(string, method)

        if len(self.attempted_connections) > 10:
            self.triggers.tr_contacts_many_domains(self.attempted_connections)

    def create_socket_handle(self, domain, type, protocol=0):
        sock = self.create_socket(domain, type, protocol)
        socket_handle_num = self.handles.new_socket(
            f"sock#{self.num_sockets:03d}", sock
        )
        self.num_sockets += 1
        return socket_handle_num

    def create_socket(self, domain, type, protocol=0):
        return self.socket_class(self, domain, type, protocol)

    def enable_whitelist(self):
        self.ignore_whitelist = False

    def disable_whitelist(self):
        self.ignore_whitelist = True

    def is_whitelisted(self, host, port):
        """
        Returns if the host and port to connect is whitelisted
        """
        if host in self.whitelist:
            if self.whitelist[host] == -1:
                return True
            if port in self.whitelist[host]:
                return True
        return self.ignore_whitelist


# Add the root path of the dmrgpy library
import os ; import sys ; sys.path.append(os.getcwd()+'/../../src')

import numpy as np
from dmrgpy import bosonchain
ns = 2 # 6 sites in total, 2 spins
nb = 4 # and 4 bosons
sites = ["S=1/2" for i in range(ns)] # add spins
sites = sites + ["B" for i in range(nb)] # add bosons
bc = bosonchain.SpinBoson_Chain(sites) # create the bosonic chain
h = 0
t = 1.0 # hopping
U = 1.0 # Hubbard
mu = 0.0 # chemical potential
# add the bosonic part
for i in range(ns,ns+nb-1):# loop over bosons (hopping)
    h = h +t*bc.Adag[i]*bc.A[i+1] # hopping
for i in range(ns,ns+nb):# loop over bosons (interaction and chemical potential)
    h = h + U*(bc.N[i]-1.0)*(bc.N[i]-1.0) # onsite interaction
    h = h + mu*bc.N[i] # chemical potential
# add the spin spin part
h = h + bc.Sx[0]*bc.Sx[1]
h = h + bc.Sy[0]*bc.Sy[1]
h = h + bc.Sz[0]*bc.Sz[1]
# and add the spin-boson interaction
h = h + (bc.Sx[0] + bc.Sx[1])*(bc.A[2] + bc.Adag[2])

h = h + h.get_dagger()
bc.set_hamiltonian(h)
e = bc.gs_energy() # compute the ground state energy
print("Energy",e)
for i in range(ns,ns+nb):
    print()
    print("Site #",i)
    print("Average occupation",np.round(bc.vev(bc.N[i]).real,2))
    print("No occupation",np.round(bc.vev(bc.D0[i]).real,2))
    print("Single occupation",np.round(bc.vev(bc.D1[i]).real,2))
    print("Double occupation",np.round(bc.vev(bc.D2[i]).real,2))
    print("Triple occupation",np.round(bc.vev(bc.D3[i]).real,2))


import torch
import torch.nn as nn
import torch.nn.functional as F

""" From: https://github.com/kevinzakka/one-shot-siamese/blob/master/model.py """

class SiameseNetwork(nn.Module):
    def __init__(self):

        super(SiameseNetwork, self).__init__()

        # Koch et al.
        # Conv2d(input_channels, output_channels, kernel_size)
        #Input should be 105x105x1
        self.conv1 = nn.Conv2d(1, 64, 10)
        self.conv2 = nn.Conv2d(64, 128, 7)
        self.conv3 = nn.Conv2d(128, 128, 4)
        self.conv4 = nn.Conv2d(128, 256, 4)
        self.fc1 = nn.Linear(9216, 4096)
        # self.fc2 = nn.Linear(4096, 1)
        self.extraL = nn.Linear(4096, 1)

        # 3 channels 150x150
        #self.conv1 = nn.Conv2d(3, 64, 10)
        #self.conv2 = nn.Conv2d(64, 128, 7)
        #self.conv3 = nn.Conv2d(128, 128, 4)
        #self.conv4 = nn.Conv2d(128, 256, 4)
        #self.fc1 = nn.Linear(30976, 4096)
        #self.fc2 = nn.Linear(4096, 1)

        # 1 channel 200x200
        # self.conv1 = nn.Conv2d(1, 64, 10)
        # self.conv2 = nn.Conv2d(64, 128, 7)
        # self.conv3 = nn.Conv2d(128, 128, 4)
        # self.conv4 = nn.Conv2d(128, 256, 4)
        # self.fc1 = nn.Linear(30976, 4096)

        # using kaiming intialization
        # random source- https://adityassrana.github.io/blog/theory/2020/08/26/Weight-Init.html
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_in')

        # distanceLayer = True
        # defines if the last layer uses a distance metric or a neuron output

    def forward_once(self, x):

        out = F.relu(F.max_pool2d(self.conv1(x), 2))
        out = F.relu(F.max_pool2d(self.conv2(out), 2))
        out = F.relu(F.max_pool2d(self.conv3(out), 2))
        out = F.relu(self.conv4(out))

        out = out.view(out.shape[0], -1)
        out = self.fc1(out)
        out = self.extraL(out)
        # out = torch.sigmoid(self.fc1(out)) # #sigmoid as we use BCELoss
        return out

    def forward(self, input1, input2):
        output1 = self.forward_once(input1)
        output2 = self.forward_once(input2)

        # if self.lastLayer:
        #     # compute l1 distance
        #     diff = torch.abs(output1 - output2)
        #     # score the similarity between the 2 encodings
        #     scores = self.extraL(diff)
        #     return scores
        # else:
        return output1, output2

########### +++++++++++++++ ###########

#create the Siamese Neural Network
# class SiameseNetwork(nn.Module):

#     def __init__(self):
#         super(SiameseNetwork, self).__init__()

#         # Setting up the Sequential of CNN Layers
#         self.cnn1 = nn.Sequential(
#             nn.Conv2d(3, 96, kernel_size=11,stride=4),
#             nn.ReLU(inplace=True),
#             nn.MaxPool2d(3, stride=2),

#             nn.Conv2d(96, 256, kernel_size=5, stride=1),
#             nn.ReLU(inplace=True),
#             nn.MaxPool2d(2, stride=2),

#             nn.Conv2d(256, 384, kernel_size=3,stride=1),
#             nn.ReLU(inplace=True)
#         )

#         # Setting up the Fully Connected Layers
#         self.fc1 = nn.Sequential(
#             nn.Linear(384, 1024),
#             nn.ReLU(inplace=True),

#             nn.Linear(1024, 256),
#             nn.ReLU(inplace=True),

#             nn.Linear(256,2)
#         )

#     def forward_once(self, x):
#         # This function will be called for both images
#         # Its output is used to determine the similiarity
#         output = self.cnn1(x)
#         output = output.view(output.size()[0], -1)
#         output = self.fc1(output)
#         return output

#     def forward(self, input1, input2):
#         # In this function we pass in both images and obtain both vectors
#         # which are returned
#         output1 = self.forward_once(input1)
#         output2 = self.forward_once(input2)

#         return output1, output2


# -*- coding: utf-8 -*-
"""
Created on Sun Apr 26 19:10:13 2020

@author: Dell_1
"""

import nltk
import string

from os import listdir
from os.path import isfile, join

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity

# All text entries to compare
BASE_INPUT_DIR = "C:\\Users\\arjav\\Desktop\\Text_Mining\\Project\\testfiles1"

#returns File list
def returnFilePathsList(folderPath):
    fileInfo = []
    FileNamesList = [fileName for fileName in listdir(folderPath) if isfile(join(folderPath, fileName))]
    FilePathsList = [join(folderPath, fileName) for fileName in listdir(folderPath) if isfile(join(folderPath, fileName))]
    fileInfo.append(FileNamesList)
    fileInfo.append(FilePathsList)
    return fileInfo

fileNames, filePaths = returnFilePathsList(BASE_INPUT_DIR)
#print(fileNames, "\n", filePaths)

# Get document contents
def create_docContentDict(filePaths):
    rawContentDict = {}
    for filePath in filePaths:
        with open(filePath, "r") as f:
            fileContent = f.read()
        rawContentDict[filePath] = fileContent
    return rawContentDict
rawContentDict = create_docContentDict(filePaths)
#print(rawContentDict)

def tokenizeContent(contentsRaw):
    tokenized = nltk.tokenize.word_tokenize(contentsRaw)
    return tokenized

def removeStopWordsFromTokenized(contentsTokenized):
    stop_word_set = set(nltk.corpus.stopwords.words("english"))
    filteredContents = [word for word in contentsTokenized if word not in stop_word_set]
    return filteredContents

def performPorterStemmingOnContents(contentsTokenized):
    porterStemmer = nltk.stem.PorterStemmer()
    filteredContents = [porterStemmer.stem(word) for word in contentsTokenized]
    return filteredContents

def stemming(contentsTokenized):
    stemmer= nltk.LancasterStemmer()
    filteredContents = [stemmer.stem(word) for word in contentsTokenized]
    return filteredContents

def removePunctuationFromTokenized(contentsTokenized):
    excludePuncuation = set(string.punctuation)
    filteredContents = [word for word in contentsTokenized if word not in excludePuncuation]
    return filteredContents

def convertItemsToLower(contentsRaw):
    filteredContents = [term.lower() for term in contentsRaw]
    return filteredContents

# process data using PorterStemmer
def processData(raw_data):
    cleaned = tokenizeContent(raw_data)
    cleaned = removeStopWordsFromTokenized(cleaned)
    cleaned = performPorterStemmingOnContents(cleaned)
    cleaned = removePunctuationFromTokenized(cleaned)
    cleaned = convertItemsToLower(cleaned)
    return cleaned

# process data using LancasterStemmer
def processData2(raw_data):
    cleaned = tokenizeContent(raw_data)
    cleaned = removeStopWordsFromTokenized(cleaned)
    cleaned = stemming(cleaned)
    cleaned = removePunctuationFromTokenized(cleaned)
    cleaned = convertItemsToLower(cleaned)
    return cleaned

# print TFIDF values
def print_TFIDF_values(term, values, fileNames):
    values = values.transpose()
    numValues = len(values[0])
    print('                ', end="")   #bank space for formatting output
    for n in range(len(fileNames)):
        print('{0:18}'.format(fileNames[n]), end="")
    print()
    for i in range(len(term)):
        print('{0:8}'.format(term[i]), end='\t|  ')
        for j in range(numValues):
            print('{0:.12f}'.format(values[i][j]), end='   ')
        print()

def print_Jaccard_Similarity(query, document):
    intersection = set(query).intersection(set(document))
    union = set(query).union(set(document))
    print("\n===============Jaccard Similarity=============\n", len(intersection)/len(union))
    print('===============================================\n')

def print_CosineSimilarity(tfs, fileNames):
    #print(cosine_similarity(tfs[0], tfs[1]))
    print("\n\n\n========COSINE SIMILARITY=====================\n")
    numFiles = len(fileNames)
    names = []
    print('                   ', end="")    #formatting
    for i in range(numFiles):
        if i == 0:
            for k in range(numFiles):
                print(fileNames[k], end='   ')
            print()

        print(fileNames[i], end='   ')
        for n in range(numFiles):
            matrixValue = cosine_similarity(tfs[i], tfs[n])
            numValue = matrixValue[0][0]
            names.append(fileNames[n])
            print(" {0:.8f}".format(numValue), end='         ')
            #(cosine_similarity(tfs[i], tfs[n]))[0][0]
        print()
    print("\n\n=====================================\n")

def main():
    baseFolderPath = "C:\\Users\\arjav\\Desktop\\Text_Mining\\Project\\testfiles1"

    fileNames, filePathList = returnFilePathsList(baseFolderPath)

    rawContentDict = create_docContentDict(filePathList)

    query_doc1 = ([key for key in rawContentDict.values()][0])
    compare_doc1 = ([key for key in rawContentDict.values()][1])

    query_doc = processData2(query_doc1)
    compare_doc = processData2(compare_doc1)

    #Jaccard Similarity
    print_Jaccard_Similarity(query_doc,compare_doc)

    # calculate tfidf
    tfidf = TfidfVectorizer(tokenizer=processData)
    tfs = tfidf.fit_transform(rawContentDict.values())
    tfs_Values = tfs.toarray()
    tfs_Term = tfidf.get_feature_names()
    # print results
    print_TFIDF_values(tfs_Term, tfs_Values, fileNames)
    print_CosineSimilarity(tfs, fileNames)

main()


def Unmanned(length: int, n: int, track: list[list[int]]) -> int:
    awaited = 0  # time spend on red

    # process all traffic lights in list
    for traffic_light in track:

        # if the light is further than length, should not process it
        if traffic_light[0] >= length:
            continue

        des_time = traffic_light[0] + awaited
        red_time = traffic_light[1]
        green_time = traffic_light[2]

        # calculate full light cycle and add to awaited
        tl_cycle = red_time + green_time
        residual = des_time % tl_cycle
        if residual < red_time:
            awaited += red_time - residual

    total_time = length + awaited

    return total_time


with open('inputs/input_09.txt','r') as f:
    x = f.read().splitlines()

def sign(x):
    if x < 0:
        return -1
    elif x == 0:
        return 0
    return 1

def updateHead(head, direction):
    if direction == "U":
        return (head[0], head[1] + 1)
    elif direction == "D":
        return (head[0], head[1] - 1)
    elif direction == "R":
        return (head[0] + 1, head[1])
    elif direction == "L":
        return (head[0] - 1, head[1])

def updateTail(tail, head):
    diff = (head[0] - tail[0], head[1] - tail[1])
    if abs(diff[0]) > 1 or abs(diff[1]) > 1:
        return (tail[0] + sign(diff[0]), tail[1] + sign(diff[1]))
    return tail

def updateTails(tails, head):
    new_tails = []
    for t in tails:
        new_loc = updateTail(t, head)
        head = new_loc
        new_tails.append(new_loc)
    return new_tails

points = set()
points.add((0,0))
head = (0,0)
tail = (0,0)
for line in x:
    direction = line[0]
    distance = int(line[1:])
    for i in range(distance):
        head = updateHead(head, direction)
        tail = updateTail(tail, head)
        points.add(tail)
print("Answer 1 = ", len(list(points)))

points2 = set()
points2.add((0,0))
head2 = (0,0)
tails = [(0,0) for _ in range(9)]
for line in x:
    direction = line[0]
    distance = int(line[1:])
    for i in range(distance):
        head2 = updateHead(head2, direction)
        tails = updateTails(tails, head2)
        points2.add(tails[-1])

print("Answer 2 = ", len(list(points2)))


from django.urls import path
from .views import (cargar_inicio,politicas,LoginView, LogoutView)

urlpatterns = [
    path('', cargar_inicio, name = 'inicio'),
    path('politicas/',politicas,name ='politicas'),

    path('login/', LoginView.as_view(template_name='accounts/login.html'),name='login'),
    path('logoutsesion', LogoutView.as_view(template_name='accounts/logout.html'),name='logout'),

]


#for number in range(1, 11):
#  print("Number {}".format(number))

#temp_f = 40
#while temp_f > 32:
#    print("The water is {} degrees.".format(temp_f))
#    temp_f -= 1

#temp_f = 40
#while temp_f > 32:
#    print("The water is {} degrees.".format(temp_f))
#    temp_f -= 1
#    if temp_f == 33:
#        break

#for number in range(1,11):
#    if number == 7:
#        print("We're skipping number 7.")
#        continue
#    print("This is the number {}.".format(number))

#for number in range(1,11):
#    if number == 3:
#        pass
#    else:
#        print("The number is {}.".format(number))

on = True
def add():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a + b)

def subtraction():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a - b)

def multiply():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a * b)

def divide():
    a = float(input("Enter a number. "))
    b = float(input("Enter another number. "))
    print(a / b)

# enclose selection into while loop

while on:
    operation = input("Please type +, -, *, /, or q: ")
    if operation == '+':
        add()

    elif operation == '-':
        subtraction()

    elif operation == '*':
        multiply()

    elif operation == '/':
        divide()

    elif operation == 'q':
        calc_on = False

    else:
        print("That operation is not available.  ")


import os
import csv
import json
import glob
import appdirs
from jupyter_core.paths import jupyter_runtime_dir
from jupyter_client import BlockingKernelClient
from permon.backend import Stat
from permon import exceptions

class JupyterRAMUsage(Stat):
    """
    tag: ``jupyter.ram_usage``

    settings:

    .. code-block:: javascript

        {
            "connection info": "",
            "query interval [s]": 1
        }

    Tracks the RAM usage of all variables in
    a user-specified jupyter notebook. If no connection info is given in the
    settings, take the kernel with the latest start date.

    ``connection info`` must be a string containing the info displayed when
    running ``%connect_info`` in a jupyter notebook
    (you can directly copy-paste it).

    ``query interval [s]`` specifies how often the thread running in the
    jupyter notebook should read the variables. The lower this is, the higher
    the resolution of the stat but it might start affecting the speed of
    your notebook when too low.

    Note that RAM tracked in this way is not equal to the actual RAM
    the OS needs because some further optimization is done by e. g. numpy
    to reduce the OS memory usage.
    """
    name = 'RAM Usage of objects in a Python Jupyter Notebook [MB]'
    base_tag = 'ram_usage'
    default_settings = {
        'connection info': '',
        # how often the memory usage is read in the jupyter notebook
        'query interval [s]': 1.
    }

    @classmethod
    def _read_latest_connection_file(cls):
        """
        Reads the latest jupyter kernel connection file.
        https://jupyter.readthedocs.io/en/latest/projects/jupyter-directories.html.
        """
        runtime_dir = jupyter_runtime_dir()
        files = glob.glob(os.path.join(runtime_dir, 'kernel-*.json'))
        if len(files) == 0:
            return None

        # use the latest connection file
        connection_file = max(files, key=os.path.getctime)
        with open(connection_file, 'r') as f:
            return json.load(f)

    @classmethod
    def get_connection_info(cls):
        """
        Get the target kernel connection info.
        Returns a dictionary of the connection info supplied
        in the settings, or the latest started kernel if none is given.
        Retuns `None` if no kernel has been found.
        """
        if len(cls.settings['connection info']) == 0:
            return cls._read_latest_connection_file()
        return json.loads(cls.settings['connection info'])

    @classmethod
    def check_availability(cls):
        # the stat is not available if no suitable connection info
        # can be found
        if cls.get_connection_info() is None:
            raise exceptions.StatNotAvailableError(
                'Could not find any running kernel.')

    def __init__(self, fps):
        self.config = self.get_connection_info()
        data_dir = appdirs.user_data_dir('permon', 'bminixhofer')
        os.makedirs(data_dir, exist_ok=True)

        self.usage_file = os.path.join(data_dir, 'jupyter_ram_usage.csv')
        open(self.usage_file, 'w').close()

        # self.setup_code is the code that is run in the notebook when the
        # stat is instantiated. It starts a thread which reads the memory
        # usage of all public variables in a set interval and saves it to a
        # csv file in the user data directory
        self.setup_code = f"""
if '_permon_running' not in globals() or not _permon_running:
    import threading
    import csv
    import sys
    import time
    from pympler import asizeof
    from types import ModuleType

    def _permon_get_ram_usage_per_object():
        while _permon_running:
            ram_usage = []
            global_vars = [key for key in globals() if not key.startswith('_')]
            for name in global_vars:
                value = globals()[name] if name in globals() else None
                if isinstance(value, ModuleType):
                    continue

                try:
                    ram_usage.append((name, asizeof.asizeof(value)))
                except TypeError:
                    continue

            with open('{self.usage_file}', 'w') as f:
                writer = csv.writer(f, delimiter=',')
                for name, ram in ram_usage:
                    writer.writerow([name, ram])
            time.sleep({self.settings['query interval [s]']})

    _permon_thread = threading.Thread(target=_permon_get_ram_usage_per_object)
    _permon_running = True
    _permon_thread.start()
"""
        self.teardown_code = """
_permon_running = False
"""
        self.client = BlockingKernelClient()
        self.client.load_connection_info(self.config)
        self.client.start_channels()
        self.client.execute(self.setup_code)
        super(JupyterRAMUsage, self).__init__(fps=fps)

    def __del__(self):
        # stop the thread running in the jupyter notebook
        # and stop the connection to the kernel upon deletion
        self.client.execute(self.teardown_code)
        self.client.stop_channels()

    def get_stat(self):
        # reads the csv file the setup code has written to
        ram_usage = []
        with open(self.usage_file, 'r') as f:
            reader = csv.reader(f)
            for row in reader:
                ram_usage.append(
                    (row[0], float(row[1]) / 1000**2)
                )
        # sort the ram_usage list so that the largest variables come first
        ram_usage = sorted(ram_usage, key=lambda x: x[1], reverse=True)

        # return the sum of RAM usage and the variables taking up the most RAM
        return sum(x[1] for x in ram_usage), ram_usage[:5]

    @property
    def minimum(self):
        return 0

    @property
    def maximum(self):
        return None


from skbuild import setup
import torch
from torch.utils import cpp_extension
import re
from os import path as osp
import sys

def _s(s):
    match = re.fullmatch(r"([^:]*\:)(.+)", s)
    if " " in s and match is not None:
        return match[1] + '"' + match[2] + '"'
    else:
        return s

if torch.__version__.startswith("1.0"):
    pytorch_base_include_path_suffix = osp.sep + osp.join("lib", "include")
elif torch.__version__.startswith("1.1"):
    pytorch_base_include_path_suffix = osp.sep + osp.join("include")
elif torch.__version__.startswith("1.2"):
    pytorch_base_include_path_suffix = osp.sep + osp.join("include")
else:
    raise ValueError("unsupported PyTorch version {}".format(torch.__version__))

pytorch_install_prefix = None
for current_include_path in cpp_extension.include_paths(False):
    if ("torch" + pytorch_base_include_path_suffix) in current_include_path:
        offset_of_search_string = current_include_path.rfind("torch" + pytorch_base_include_path_suffix)
        current_include_path = current_include_path[:offset_of_search_string + len("torch")]
        if osp.isdir(osp.join(current_include_path, "share")):
            pytorch_install_prefix = current_include_path
            break

if pytorch_install_prefix is None:
    raise ValueError("could not determine pytorch install prefix")

cmake_args = [
        "-DPYTORCH_INCLUDES:PATH=" + osp.pathsep.join(cpp_extension.include_paths(False)),
        "-DPYTORCH_LDFLAGS:STRING=" + " ".join(map(_s, cpp_extension._prepare_ldflags([], False, False))),
        "-DTORCH_INSTALL_PREFIX:PATH=" + pytorch_install_prefix
    ]
try:
    cmake_args.extend([
        "-DPYTORCH_CUDA_INCLUDES:PATH=" + osp.pathsep.join(cpp_extension.include_paths(True)),
         "-DPYTORCH_CUDA_LDFLAGS:STRING=" + " ".join(map(_s, cpp_extension._prepare_ldflags([], True, False)))
    ])
except OSError:
    pass

setup(
    name="pytorch_register_op_minimal",
    version="0.0.0",
    author="Leopold Walkling",
    author_email="leopold_walkling@web.de",
    cmake_args=cmake_args,
    packages=["pytorch_register_op_minimal"],
    package_dir={"pytorch_register_op_minimal": "pytorch_register_op_minimal"}
)


from pet import Pet
import random

class Shop:
    def __init__(self, pet_data):
        self.gold = 10
        self.pet_data = pet_data
        self.available_pets = []
        self.items = ["Apple", "Honey"]
        self.initialize_shop()

    def initialize_shop(self):
        pet_ids = list(self.pet_data.keys())
        selected_pet_ids = random.sample(pet_ids, 5)
        for pet_id in selected_pet_ids:
            pet_info = self.pet_data[pet_id]
            pet = Pet(name=pet_info["Name"], attack=pet_info["Attack"], health=pet_info["Health"], tier=pet_info["Tier"], trigger=pet_info["Trigger"])
            self.available_pets.append(pet)

    def get_state(self):
        state = {
            "gold": self.gold,
            "available_pets": [(pet.name, pet.get_attack(), pet.get_health(), pet.tier, pet.get_trigger()) for pet in self.available_pets],
            "available_items": self.items.copy()
        }
        return state

    def buy_pet(self, pet_index, team):
        if self.gold >= 3:
            pet = self.available_pets.pop(pet_index)
            team.add_pet(pet)
            self.gold -= 3

    def buy_item(self, item_index, pet):
        if self.gold >= 3:
            item = self.items.pop(item_index)
            pet.set_item(item)
            self.gold -= 3

    def roll(self):
        if self.gold >= 1:
            self.available_pets = []
            self.items = ["Apple", "Honey"]
            self.initialize_shop()
            self.gold -= 1

    def display(self):
        """Display the available pets and items in the shop."""
        print("\nAvailable Pets:")
        for i, pet in enumerate(self.available_pets):
            print(f"{i}. {pet.name} (Cost: {3}g)")
        print("\nAvailable Items:")
        for i, item in enumerate(self.items):
            print(f"{i}. {item} (Cost: {3}g)")
        print(f"\nGold: {self.gold}g")


inf = 1 << 60

def main():
    N = int(input())
    S = [list(input()) for _ in range(N)]
    ans = inf
    for s in range(10):
        s = str(s)
        t = 0
        times = [0] * 10
        for i in range(N):
            j = S[i].index(s)
            times[j] += 1
        mt = max(times)
        w = 9
        for i in range(9, -1, -1):
            if mt == times[i]:
                w = i
                break
        ans = min(ans, 10 * (mt - 1) + w)
    print(ans)

if __name__ == '__main__':
    main()


import glob
import xml.etree.ElementTree as ET
from PIL import Image

#adding images in a folder to list
li=[]
for j in glob.glob("E:/gokul/PascalVOC-to-Images/data/*.jpg"): #path to data folder(should contain image and xml in same folder)
    li.append(j)

#for cropping images from a list by using bounding box in pascal voc(xml)
count=0
for i in glob.glob("E:/gokul/PascalVOC-to-Images/data/*.xml"): #path to data folder(should contain image and xml in same folder)
    # print('name',j)
    tree = ET.parse(i)
    # print('tree',tree)

    root = tree.getroot()
    # print('root',root)

    objects = root.findall('object')
    # print('objects',objects)
    temp=0
    for o in objects:
        bndbox = o.find('bndbox') # reading bound box
        xmin = int(bndbox.find('xmin').text)
        ymin = int(bndbox.find('ymin').text)
        xmax = int(bndbox.find('xmax').text)
        ymax = int(bndbox.find('ymax').text)
        print(xmin,ymin,xmax,ymax)
        bbox=(xmin,ymin,xmax,ymax)
        # print('fin',bbox)
        image=li[count]
        im=Image.open(image)
        im=im.crop(bbox)
        im.show()
        im.save(f"E:/gokul/PascalVOC-to-Images/output/cropped_image{count}_{temp}.jpg") #set save directory(E:/gokul/PascalVOC-to-Images/output/)
        temp=temp+1
    count=count+1