# -*- coding: utf-8 -*-
import scrapy
import datetime, re
from hrfoecast.items import HrfoecastItem

class GazpromSpider(scrapy.Spider):
    """
    scraped data from gazpromvacancy.ru
    """
    name = 'gazprom'
    allowed_domains = ['gazpromvacancy.ru']
    start_urls = ['https://www.gazpromvacancy.ru/jobs/']

    def response_is_ban(self, request, response):
        # scrapy-proxy-pool function
        return b'banned' in response.body

    def exception_is_ban(self, request, exception):
        # scrapy-proxy-pool function
        return None

    def vacancy_data(self, response):

        main_selector = '//*[@class="job-container"]'
        raw_data = response.xpath(main_selector)

        scraped_info = HrfoecastItem()

        # data for job_url info
        scraped_info['job_url'] = response.url
        # data for job_title info
        scraped_info['job_title'] = raw_data.xpath(
            '//*[@id="content-normal"]/article/h1/text()').extract()[0]

        # data for company_name info
        scraped_info['company_name'] = response.xpath(
            '//*[@id="content-normal"]/article/dl/dd[1]/a/text()').extract()[0]

        # data for crawled_date
        scraped_info['crawled_date'] = str(datetime.date.today())

        # data for posted_date
        raw_data = response.xpath(
            '//*[@id="content-normal"]/article/dl/dd[5]/time/text()').extract()[
            0].replace('\n', '').split()

        month = {'января': '01', 'февраля': '02', 'марта': '03', 'апреля': '04',
                 'мая': '05', 'июня': '06', 'июля': '07', 'августа': '08',
                 'сентября': '09', 'октября': '10', 'ноября': '11',
                 'декабря': '12'}

        scraped_info['posted_date'] = "{2}-{1}-{0}".format(raw_data[0],
                                                           month[raw_data[1]],
                                                           raw_data[2])

        # data for location
        scraped_info['location'] = response.xpath(
            '//*[@id="content-normal"]/article/dl/dd[2]/text()').get()

        # data for  job_description
        temporaly_data = ''
        for item in response.xpath('//*[@id="content-normal"]/article/div[1]'):
            temporaly_data += item.xpath('h2/text()').get() + '\n'
            if item.xpath('ul/li/span|ul/li/div|ul/li|p') != None:
                for data in item.xpath('ul/li/span|ul/li/div/text()|ul/li/text()|p').getall():
                    temporaly_data += data + '\n'

        for item in response.xpath('//*[@id="content-normal"]/article/div[2]'):
            temporaly_data += item.xpath('h2/text()').get() + '\n'
            if item.xpath('ul/li/span|ul/li/div|ul/li|p') != None:
                for data in item.xpath('ul/li/span|ul/li/div/text()|ul/li/text()|p').getall():
                    temporaly_data += data + '\n'

        temporaly_data = re.sub('', '', temporaly_data)
        temporaly_data = re.sub('', '', temporaly_data)
        temporaly_data = re.sub('
', '', temporaly_data)
        temporaly_data = re.sub('
', '', temporaly_data)
        temporaly_data = re.sub('
', '', temporaly_data)

        scraped_info['job_description'] = temporaly_data

        yield scraped_info

    def parse(self, response):

        vacancy_selector = '//*[@class="job-list-item"]/h3/a/@href'

        for link in response.xpath(vacancy_selector):
            vacancy_url = 'https://www.gazpromvacancy.ru/' + link.get()
            yield scrapy.Request(url=vacancy_url, callback=self.vacancy_data)

        page_link = response.xpath(
            '//li[@class="current"]/following::li[1]/a/@href')

        if page_link:
            print('next page = ', page_link.get())
            yield scrapy.Request(
                url='https://www.gazpromvacancy.ru/' + page_link.get(),
                callback=self.parse)


from PySide6 import QtWidgets
from data.data_manager import DataManager
from data.chess_structs import ChessGame, ChessPlayer
from gui.edit.wid_edit_player import PlayerEditDialog
from helpers.gui import ShowModalException, SpawnModal

class PlayersWidget(QtWidgets.QWidget):
    ''' Widgets that shows players '''

    def __init__(self, db_manager: DataManager, parent: QtWidgets.QWidget):
        super().__init__(parent)
        self.db_manager = db_manager

        self.main_layout = QtWidgets.QHBoxLayout(self)
        self.setLayout(self.main_layout)

        # Datasheet
        self.table_widget = QtWidgets.QTableWidget(self)
        self.table_widget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
        # self.table_widget.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
        self.table_widget.setSelectionBehavior(QtWidgets.QAbstractItemView.SelectionBehavior.SelectRows)
        self.table_widget.setSelectionMode(QtWidgets.QAbstractItemView.SelectionMode.SingleSelection)
        self.table_widget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)

        headers = list(ChessPlayer.getHeaders())
        self.table_widget.setColumnCount(len(headers))
        self.table_widget.setHorizontalHeaderLabels(headers)

        self.__RefreshTableData()
        self.main_layout.addWidget(self.table_widget)

        # Buttons
        self.buttons_widget = self.__CreateButtonsWidget()
        self.main_layout.addWidget(self.buttons_widget)

    def __CreateButtonsWidget(self):
        buttons_widget = QtWidgets.QWidget(self)
        buttons_layout = QtWidgets.QVBoxLayout(buttons_widget)
        buttons_widget.setLayout(buttons_layout)

        # Top
        new_btn = QtWidgets.QPushButton("New (N)", buttons_widget)
        delete_btn = QtWidgets.QPushButton("Delete (D)", buttons_widget)
        edit_btn = QtWidgets.QPushButton("Edit (E)", buttons_widget)

        new_btn.clicked.connect(self.__OnNewPlayer)
        delete_btn.clicked.connect(self.__OnDeletePlayer)
        edit_btn.clicked.connect(self.__OnEditPlayer)

        # Bottom
        showgames_btn = QtWidgets.QPushButton("Show games (S)", buttons_widget)

        showgames_btn.clicked.connect(self.__OnShowPlayerGame)

        # Add all to widget
        buttons_layout.addWidget(new_btn)
        buttons_layout.addWidget(delete_btn)
        buttons_layout.addWidget(edit_btn)
        buttons_layout.addStretch()
        buttons_layout.addWidget(showgames_btn)

        return buttons_widget

    def __GetSelectedPlayerID(self):
        rows = self.table_widget.selectionModel().selectedRows()
        if len(rows):
            return int(rows[0].data())
        else:
            return None

    def __GetSelectedPlayerData(self):
        id = self.__GetSelectedPlayerID()
        if id:
            return next((p for p in self.player_data if p.id == id), None)

    def __OnNewPlayer(self):
        dialog = PlayerEditDialog(self.db_manager, self)
        if dialog.exec_():
            self.__RefreshTableData()

    def __OnDeletePlayer(self):
        id = self.__GetSelectedPlayerID()
        try:
            result = SpawnModal(
                "I have for you imporant question",
                "Are you sure?",
                QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.Cancel
            )
            if result == QtWidgets.QMessageBox.Yes:
                self.db_manager.GetDatabaseAPI().DeletePlayer(id)
                self.__RefreshTableData()
        except Exception as e:
            ShowModalException()

    def __OnEditPlayer(self):
        player = self.__GetSelectedPlayerData()
        if not player:
            SpawnModal('Error', 'Cannot find currently selected player.', QtWidgets.QMessageBox.Ok)
            return

        dialog = PlayerEditDialog(self.db_manager, self, player)
        if dialog.exec_():
            self.__RefreshTableData()

    def __OnShowPlayerGame(self):
        print("!!!")

    def RefreshData(self):
        self.__RefreshTableData()

    def __RefreshTableData(self):
        self.player_data = list(self.db_manager.GetDatabaseAPI().GetPlayers())
        self.table_widget.setRowCount(len(self.player_data))
        for i, player in enumerate(self.player_data):
            for j, data in enumerate(player.getData()):
                new_item = QtWidgets.QTableWidgetItem(str(data))
                self.table_widget.setItem(i, j, new_item)

        # self.table_widget.setSizeAdjustPolicy(QtWidgets.QAbstractScrollArea.AdjustToContents)
        # self.table_widget.resizeColumnsToContents()
        # self.table_widget.horizontalHeader().setStretchLastSection(True)


import time

def is_bouncy(number):
	digits = [int(digit) for digit in str(number)]
	increasing = decreasing = True
	for index in xrange(0, len(digits) - 1):
		if digits[index] > digits[index + 1]:
			increasing = False
		if digits[index] < digits[index + 1]:
			decreasing = False

		if increasing is False and decreasing is False:
			return True

	return False

def main():
	result = 0
	num, proportion, bouncy_numbers = 100, 0, 0
	while True:
		bouncy_numbers += 1 if is_bouncy(num) else 0
		proportion = bouncy_numbers * 100 / num

		if proportion == 99 and bouncy_numbers * 100 % num == 0:
			result = num
			break

		num += 1

	print("The result is %d." % result)

if __name__ == '__main__':
	start = time.time()
	main()
	done = time.time()
	print("The solution took %.4f seconds to compute." % (done - start))


import sys
import automato_pilha

def read_file():
    config = {}
    transition = {}

    aux = 0
    file_name = str(sys.argv[1])
    file = open(file_name, 'r')

    for i in range(1, 8):
        conteudo = file.readline().strip('\n').split(' ')
        config[i] = conteudo

    for i in file:
        aux = aux + 1
        transition[aux] = i.strip('\n').split(' ')
    return config, transition

def read_word():
    word = sys.argv[2]
    return word

def main():
    read_file()
    read_word()

    config = {}
    transitions = {}

    config, transitions = read_file()
    word = read_word()

    automato_pilha.machine(config, word, transitions)

main()


# Python
import cv2
print(cv2.__version__)
flip=2  # change camera play direction
dispW = 640
dispH = 480

camSet='nvarguscamerasrc !  video/x-raw(memory:NVMM), width=3264, height=2464, format=NV12, framerate=21/1 ! nvvidconv flip-method='+str(flip)+' ! video/x-raw, width='+str(dispW)+', height='+str(dispH)+', format=BGRx ! videoconvert ! video/x-raw, format=BGR ! appsink'
cam= cv2.VideoCapture(camSet)
dispW = int(cam.get(cv2.CAP_PROP_FRAME_WIDTH)) # screen width
dispH = int(cam.get(cv2.CAP_PROP_FRAME_HEIGHT)) # screen height
print(f'window size = {dispW}Width x {dispH}Height')

BW = int(.18 * dispW) # rectangle width
BH = int(.14 * dispH) # rectangle height
posX = 10 # rectangle X-position start point
posY = 270 # rectangle Y-position start point
dx = 2 # each x move step
dy = 2 # each y move step

while True:
    ret, frame = cam.read()

    # step1: copy the initial color pixel points in ROI area
    # remind: in coordination, row=y, column=x
    roi_init = frame[posY:posY+BH, posX:posX+BW].copy()
    print('roi_init= ',roi_init)

    # step2: change the screen copy to gray
    roi_gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
    roi_gray = cv2.cvtColor(roi_gray,cv2.COLOR_GRAY2BGR) # from gray picture to set the ROI in original frame
    frame = cv2.rectangle(roi_gray, (posX, posY),(posX+BW, posY+BH),(0,255,0),4)

    # step3: ROI area replace with the initial colored pixel points
    frame[posY:posY+BH, posX:posX+BW] = roi_init

    cv2.imshow('nanoCam', frame)
    cv2.moveWindow('nanoCam',0,0)
    posX += dx
    posY += dy
    if posX <= 0: # left boundary
        dx = dx*(-1) # change direction
    if posX + BW >= dispW: # right boundary
        dx = dx*(-1)
    if posY <= 0:  # upper boundary
        dy = dy*(-1)
    if posY + BH >= dispH: # bottom boundary
        dy = dy*(-1)

    if cv2.waitKey(5)==ord('q'):
        break

cam.release()
cv2.destroyAllWindows()


import numpy

def makeTable( \
    column_titles, \
    cut_flow_fileNames, \
    cut_flow_str_fileName, \
    crossSection_fileNames) :

    cut_flow_data = [[numpy.loadtxt(f, usecols = [1], delimiter = "@@@") for f in s] for s in cut_flow_fileNames]
    #print cut_flow_data

    cut_flow_str = numpy.loadtxt(cut_flow_str_fileName, delimiter = "@@@", dtype = str)
    # print cut_flow_str

    crossSection_data = [numpy.loadtxt(f, ndmin = 1) for f in crossSection_fileNames]
    #print crossSection_data

    table = []

    # Add column titles
    table.append(column_titles)

    # Add row titles
    for iCut in range(0, cut_flow_str.shape[0]) :

        table.append([cut_flow_str[iCut]])

    # Add table entries
    for iCut in range(0, cut_flow_str.shape[0]) :

        row = []

        #print "Cut", iCut, ":"

        for iSet in range(0, len(cut_flow_fileNames)) :

            val = [crossSection_data[iSet][iFile] * cut_flow_data[iSet][iFile][iCut] / cut_flow_data[iSet][iFile][0] \
                for iFile in range(0, len(cut_flow_fileNames[iSet]))]

            val = sum(val)
            #print val
            row.append(str("%0.4f" % val))

        table[iCut+1].extend(row)

    #print table

    return table


#
# HEADER ???
#

# Notes
# MN: DO NOT USE GLOBALS!!!!
#

import sys
import time
import subprocess

# define class
class Participants():

    # name of the participant
    name = "Notfound"
    # accumulator for total distance
    distance = 0.0
    #accumulator for total number of runs
    runs = 0

#method
    def __init__(self, Name, distance=0.0,run=0):
        #initialize the method
        self.name = Name
        if distance > 0:

           self.distance = distance
           self.runs = 1

    #get the name of the participants
    def getName(self):
        return self.name

    #get the current value of distance
    def getDistance(self):
        return self.distance

    #add single distnace to the distance accumulator
    def addDistance(self,distance):
        if distance > 0:
             self.distance += distance
             self.runs += 1

    #add an array of distance to distance accumulator
    def addDistances(self,distances):
        for distance in distances:
            if distance in distances:
              self.distance += distance
              self.runs += 1
        return

    #stringify method
    def _str_(self):
        name_format = "{:>20s}".format(self.name)
        distance_format = "{:>9.4f}".format(self.distance)
        runs_format = "{:<4d}".format(self.runs)
        return "Name : "+name_format+". Distance run : "+distance_format+". Runs : "+runs_format

# create the empty list
Max_run = None
Min_run = None
file_name_list = []
participant_Arr = []

# initialize the variables
total_line = 0
total_distance = 0.0
total_file_read = 0
Total_Multiple_record = 0

# create the function to do the main processing
def processFile(fh):

    global total_line
    global total_distance

    # use for loop to calculate the total number of line and total distance
    for line in file_object:
        if (line.split(",")[0] != "name"):
            file_line = line.split(",")
            file_line[1] = file_line[1].rstrip('\n')
            total_line += 1
            total_distance += float(file_line[1])

            Max_Min(List(file_line))
    return

def List(file_line):
    global Total_Multiple_record

    if len(participant_Arr) >= 1:
        for item in participant_Arr:
            # check if the name of participants is in the line
            if file_line[0] == item.getName():

                if item.runs == 1:
                    Total_Multiple_record += 1

                item.addDistance(float(file_line[1]))
                return item
    File = Participants(file_line[0], float(file_line[1]), 1)
    participant_Arr.append(File)
    return File

# define the new function called Max_Min
def Max_Min(participant):

    global Max_run
    global Min_run

    if Max_run is not None and Min_run is not None:
        if participant.getDistance() > Max_run.getDistance():
            Max_run = participant
        elif participant.getDistance() < Min_run.getDistance():
            Min_run = participant
        return

    Max_run = participant
    Min_run = participant
    return

# Define printKV function
def printKV(key, value, klen=0):
    # Initialize the variable of formatting values
    Value_format = 0
    # define the way of formatting key words in printKV function
    key_format = "{:<30}".format(key)
    # Since there are three types of values, I use if-elif to separate these three cases
    # and use isinistance function to write conditions
    if isinstance(value, str):
        Value_format = "{:<40}".format(value)
    elif isinstance(value, int):
        Value_format = "{:<40}".format(value)
    elif isinstance(value, float):
        Value_format = "{:<40.5f}".format(value)
    # I use print function to print these two format variables in one line
    print(key_format + ':' + Value_format)
    return

# start the main process
# first open the file name list to read

masterFile = input("Please provide master file : ")
in_file = open(masterFile, 'r')
for line in in_file:
    file_name_list.append(line.rstrip("\n"))
in_file.close()

while (len(file_name_list) > 0):
    total_file_read += 1
    file_name = file_name_list.pop()
    # read the last name in the list each time and remove the name from the list after finishing reading
    file_object = open(file_name, 'r')
    processFile(file_name)
    file_object.close()

# create an output file reporting name of the participantn how many their name appears in the input files
# and total distance run
f = open("f2016_cs8_wed25_fp.data.output.csv", 'w')
for item in participant_Arr:
    # MN: object methods needs to be called like functions
    #f.write(str(item.getName()) + ',' + str(item.runs) + ',' + str(item.getDistance) + '\n')
    f.write(str(item.getName()) + ',' + str(item.runs) + ',' + str(item.getDistance()) + '\n')

f.close()

printKV("Number of input files read", total_file_read, 30)
printKV("Total number of Lines read", total_line, 30)
printKV("Total distance run", total_distance, 30)
printKV("Max distance run", Max_run.getDistance(), 30)
printKV("    by participant", Max_run.getName(), 30)
printKV("Min distance run", Min_run.getDistance(), 30)
printKV("    by participant", Min_run.getName(), 30)
printKV("Total number of participants", len(participant_Arr), 30)
print("Number of participants")
printKV("with multiple record", Total_Multiple_record, 30)


def translateChar (inputChar):
  if str.isdigit(inputChar):
    return int(inputChar)
  elif (inputChar == "a" or inputChar == "A"):
    return 10
  elif inputChar == "b" or inputChar == "B":
    return 11
  elif inputChar == "c" or inputChar == "C":
    return 12
  elif inputChar == "d" or inputChar == "D":
    return 13
  elif inputChar == "e" or inputChar == "E":
    return 14
  elif inputChar == "f" or inputChar == "F":
    return 15
  return 0

def convertHexStringToDecimal (hexString):
  result = 0

  strLen = len(hexString)
# print ("strLen: {0}".format (strLen))
  range3 = range(strLen, 0, -1)
# print ("range3: {0}".format (range3))
  reversedStr = hexString[::-1]

  for currIndex in range3:
    adjustedIndex = currIndex -1
    print ("adjustedIndex: {0}".format (adjustedIndex))
    currMultiplier = 16 ** adjustedIndex
    print ("currMultiplier: {0}".format (currMultiplier))
    currDecimal = translateChar (reversedStr[adjustedIndex])
    print ("currDecimal: {0}".format (currDecimal))
    currPositionalResult = currMultiplier * currDecimal
    print ("currPositionalResult: {0}".format (currPositionalResult))
    result += currPositionalResult
    print ("result: {0}".format (result))

  return result

testString = 'cafedecaf'
decimalValue = convertHexStringToDecimal (testString)

print ("final value of testString '{0}': {1}".format (testString, decimalValue))


#!/usr/bin/python3

# Programa Creado Por Andy Zapata - IMIT 2020

import numpy as np
import glob # - Unix style pathname pattern expansion (Edison)
import math as mh

#=================================================================================================#
def filesxyz () :
    """
    Get names of xyz at current directory
    """
    # - Lineas tomadas del script creado por Edison: radial_distribution_analisys.py
    list_xyz = []  # unique files

    for input_xyz in glob.glob('*.xyz'):
        list_xyz = input_xyz[:-4]  # deleting file extention

    return list_xyz
#=================================================================================================#
def LXYZ (NXYZ) :
    """
    Get Number of atoms, labels and coordenates of the atoms in xyz
    """
    natoms = 0

    g = NXYZ + ".xyz"
    f = open(g,"r")
    natoms = int(f.readline())
    print (f"Numero de atomos en",g,":",natoms)

    f.readline()
    MXYZ = np.zeros((natoms,3))
    LA = []
    LA.append(natoms)
    for i in range(natoms):
        line = f.readline()
        for j in range(4):
            if j == 0 :
                LA.append(line.split()[0])  #En vez de guardar el n'umero como str, se podría
            else :                          #poner el número atómico, asi se juntan los arreglos
                MXYZ[i,j-1] = line.split()[j] # Z + coord

    f.close()
    return LA, MXYZ
#=================================================================================================#
def rv (va,rmax,NALA,MXYZ) :
    """
    Return distance of all atoms to vertice and coordinates, which are lesser to rmax
    """
    #Esta hecho solo por ahora, para tener solo un tipo de átomo
    #del vertice
    coordv = np.zeros((3))
    for i in range(NALA[0]):
        if va == NALA[i+1] :
            for j in range(3):
                coordv[j] = MXYZ[i,j]
    distv = np.zeros((NALA[0]-1,4))
    dr = np.zeros((3))
    r = 0.0
    cont = 0
    for i in range(NALA[0]) :
        for j in range(3):
            if va != NALA[i+1] :
                dr[j] = MXYZ[i,j] - coordv[j]
                if j == 2 :
                    r = dr[0]*dr[0] + dr[1]*dr[1] + dr[2]*dr[2]
                    r = mh.sqrt(r)
                    if r <= rmax :
                        for k in range(4) :
                            if k == 3 :
                                distv[cont,k] = r
                                cont += 1
                            else :
                                distv[cont,k] = MXYZ[i,k] - coordv[k]  #Se resta coordv, para cambiar el cero de los vectores

    return cont, distv
#=====================================================================================#
def angle (NAV,VR) :
    """
    Get angles between vectors
    """
    cont = 0 #número de ángulos tetha calculados
    tetha = []
    cont = 0
    print ("NAV ",NAV)
    for i in range(NAV-1) :
        l = i
        while l < NAV-1 :
            l += 1
            APB = 0.0
            for k in range(3) :
                APB += VR[i,k]*VR[l,k]
            C = 0.0
            C = APB/(VR[i,3]*VR[l,3])
            t = 0.0
            t = mh.acos(C)
            t = t*180/mh.pi
            tetha.append(t)
            cont += 1
    return cont, tetha
#=================================================================================================#
def SM (NALA,MXYZ,rmaxo) :
    """
    Search water molecules, which are lesser to rmaxo to Hg
    """
    coordv = np.zeros((3))
    for i in range(NALA[0]):
        if "Hg" == NALA[i+1] :
            for j in range(3):
                coordv[j] = MXYZ[i,j]
    distv = np.zeros((NALA[0]-1,4))
    dr = np.zeros((3))
    r = 0.0
    cont = 0
    for i in range(NALA[0]) :
        for j in range(3):
            if "Hg" != NALA[i+1] :
                dr[j] = MXYZ[i,j] - coordv[j]
                if j == 2 :
                    r = dr[0]*dr[0] + dr[1]*dr[1] + dr[2]*dr[2]
                    r = mh.sqrt(r)
                    if r <= rmaxo :
                        for k in range(4) :
                            if k == 3 :
                                distv[cont,k] = r
                                cont += 1
                                #Busco H más cercanos a O, distancia < 1.5
                                if 'O' in NALA[i+1] :
                                    for ii in range(NALA[0]):
                                        for jj in range(3):
                                            if 'Hg' != NALA[ii+1] and 'O' != NALA[ii+1] :
                                                dr[jj] = MXYZ[ii,jj] - MXYZ[i,jj]
                                                if jj == 2 :
                                                    r = dr[0]*dr[0] + dr[1]*dr[1] + dr[2]*dr[2]
                                                    r = mh.sqrt(r)
                                                    if r <= 1.54 :  #El valor 1.5 es para garantizar los H que se disocian del H2O
                                                        for kk in range(4):
                                                            if kk == 3 :
                                                                distv[cont,kk] = r
                                                                #print (NALA[ii+1]," : ",distv[cont,:])
                                                                cont += 1
                                                            else:
                                                                distv[cont,kk] = MXYZ[ii,kk]
                            else :
                                distv[cont,k] = MXYZ[i,k]
    return cont, distv, coordv
#=================================================================================================#
def dihedral (NAW,VR,RHg) :
    """
    Calculate dihedral between water molecule and Hg with Praxeolitic formule
    https://en.wikipedia.org/wiki/Talk%3ADihedral_angle
    https://www.it-swarm.dev/es/python/angulo-diedrico-torsion-desde-cuatro-puntos-en-coordenadas-cartesianas-en-python/1042912628/
    """
    #        H
    #       /|
    # Hg\  O |<- El ángulo dihedral, describe la torsión del vector señalado
    #    \---H
    #
    NO = 0
    NO = int(NAW/3)
    #print ("# O : ",NO)
    #Vectores O->H, H->H, H->Hg
    voh = np.zeros((NO,3))
    vhh = np.zeros((NO,3))
    vhhg= np.zeros((NO,3))
    cont = 0
    for i in range(NO):
        l = i+i*2
        for k in range(3) :
            voh[cont,k] = -1.0*(VR[l+1,k] - VR[l,k])   #Distancia O->H
            vhh[cont,k] = VR[l+2,k] - VR[l+1,k]        #Distancia H->H
            vhhg[cont,k] = RHg[k] - VR[l+2,k]      #Distancia H-Hg
        cont += 1

    #Normalizo vector H->H
    nhh = 0.0
    for i in range(NO):
        dr = 0.0
        r = 0.0
        for j in range(3):
            dr = vhh[i,j]*vhh[i,j]
            r += dr
        nhh = mh.sqrt(r)
        for j in range(3) :
            vhh[i,j] = vhh[i,j]/nhh
    # vOHvHH Proyección de O->H en H->H y resto componente que alignea a H->H
    # vHHgvHH Proyección de H->Hg en H->H y resto componente que alignea a H->H
    dih = np.zeros((NO))
    cont = 0
    for i in range(NO) :
        droh  = roh = 0.0
        drhhg = rhhg = 0.0
        vOHvHH = np.zeros((3))
        vHHgvHH = np.zeros((3))
        x = 0.0
        y = 0.0
        y1 = np.zeros((3))
        for j in range(3): #Producto punto o proyección
            droh   = voh[i,j]*vhh[i,j]
            roh  += droh
            drhhg  = vhhg[i,j]*vhh[i,j]
            rhhg += drhhg
        for j in range(3): #Resto
            vOHvHH[j] = voh[i,j] - roh*vhh[i,j]
            vHHgvHH[j] = vhhg[i,j] - rhhg*vhh[i,j]
    # El ángulo entre vOHvHH y vHHgvHH en un plano es el ángulo de torsión
            x += vOHvHH[j]*vHHgvHH[j]
        y1 = np.cross(vhh[i,:],vOHvHH)
        for j in range(3):
            y +=  y1[j]*vHHgvHH[j]
        dih[cont] = np.arctan2(y,x)*180/mh.pi
        cont += 1
    return dih


def rotated_array_search(input_list, number):
    """
    Find the index by searching in a rotated sorted array

    Args:
       input_list(array), number(int): Input array to search and the target
    Returns:
       int: Index or -1
    """
    first_idx = 0
    last_idx = len(input_list) - 1
    idx = -1
    while (first_idx <= last_idx) and (idx == -1):
        mid_idx = (first_idx + last_idx) // 2
        if input_list[mid_idx] == number:
            idx = mid_idx
        else:
            if (
                number < input_list[mid_idx] and number >= input_list[first_idx]
            ):  # if value is smaller then mid index
                last_idx = mid_idx - 1
            elif (
                number >= input_list[first_idx]
                and number > input_list[mid_idx]
                and number > input_list[last_idx]
            ):  # means pivot on the left side
                last_idx = mid_idx - 1
            else:
                first_idx = mid_idx + 1

    return idx

def linear_search(input_list, number):
    for index, element in enumerate(input_list):
        if element == number:
            return index
    return -1

def test_function(test_case):
    input_list = test_case[0]
    number = test_case[1]
    if linear_search(input_list, number) == rotated_array_search(input_list, number):
        print("Pass")
    else:
        print("Fail")

# normal cases
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 6])
test_function([[6, 7, 8, 9, 10, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 8])
test_function([[6, 7, 8, 1, 2, 3, 4], 1])
test_function([[6, 7, 8, 1, 2, 3, 4], 10])
# edge cases
test_function([[], None])
test_function([[1], 0])


from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect
import datetime

def list_movies(request):
    # find out city of the client
    if 'city' in request.COOKIES:
        cityname = request.COOKIES['city']
        return render(request, 'list_movies.html', {'city': cityname})
    else:
        return redirect("/demo/selectcity")

def select_city(request):
    if request.method == "GET":
        return render(request,'select_city.html')
    else:
        cityname = request.POST['city']
        response = HttpResponseRedirect("/demo/movies")
        response.set_cookie('city',cityname,
                expires = datetime.datetime.now() + datetime.timedelta(days=7))
        return response


_base_ = './ocrnet_hr18_512x1024_40k_cityscapes.py'
model = dict(
    pretrained='open-mmlab://msra/hrnetv2_w18_small',
    backbone=dict(
        extra=dict(
            stage1=dict(num_blocks=(2, )),
            stage2=dict(num_blocks=(2, 2)),
            stage3=dict(num_modules=3, num_blocks=(2, 2, 2)),
            stage4=dict(num_modules=2, num_blocks=(2, 2, 2, 2)))))

data_root = 'data/morai_cityscapes_mix/'

data = dict(
    samples_per_gpu=2,
    workers_per_gpu=2,
    train=dict(
        data_root=data_root,
        img_dir='leftImg8bit/train',
        ann_dir='gtFine/train'),
    val=dict(
        data_root=data_root,
        img_dir='leftImg8bit/val',
        ann_dir='gtFine/val'),
    test=dict(
        data_root=data_root,
        img_dir='leftImg8bit/val',
        ann_dir='gtFine/val'))


import random

NUMELE, MIN, MAX = 15, 10, 20
vettore = []

for i in range(NUMELE):
	vettore.append(random.randint(MIN, MAX))

def sposta(x: int, destra: bool):
	v = []

	if destra:
		for i in range(NUMELE):
			v.append(vettore[i - x])
	else:
		for i in range(NUMELE - x):
			v.append(vettore[i + x])
		for i in range(x):
			v.append(vettore[i])

	return v

print("vettore prima spostamento:\t", vettore)
print("vettore dopo spostamento:\t", sposta(3, True))


from matplotlib.animation import ImageMagickWriter
import torch
from torch import nn, einsum
import torch.nn.functional as F
import os
import numpy as np
import mresnet as resnet
import mdensenet as densenet
import minception as inception
import math

from einops import rearrange, repeat, reduce
from einops.layers.torch import Rearrange

def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=dilation, groups=groups, bias=False, dilation=dilation)

class Bottle2neck(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None, baseWidth=26, scale = 4, stype='normal'):
        """ Constructor
        Args:
            inplanes: input channel dimensionality
            planes: output channel dimensionality
            stride: conv stride. Replaces pooling layer.
            downsample: None when stride = 1
            baseWidth: basic width of conv3x3
            scale: number of scale.
            type: 'normal': normal set. 'stage': first block of a new stage.
        """
        super(Bottle2neck, self).__init__()

        width = int(math.floor(planes / scale))
        self.conv1 = nn.Conv2d(inplanes, width*scale, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(width*scale)

        if scale == 1:
          self.nums = 1
        else:
          self.nums = scale -1
        if stype == 'stage':
            self.pool = nn.AvgPool2d(kernel_size=3, stride = stride, padding=1)
        convs = []
        bns = []
        for i in range(self.nums):
          convs.append(nn.Conv2d(width, width, kernel_size=3, stride = stride, padding=1, bias=False))
          bns.append(nn.BatchNorm2d(width))
        self.convs = nn.ModuleList(convs)
        self.bns = nn.ModuleList(bns)

        self.conv3 = nn.Conv2d(width*scale, planes * self.expansion, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * self.expansion)

        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stype = stype
        self.scale = scale
        self.width  = width

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        spx = torch.split(out, self.width, 1)
        for i in range(self.nums):
          if i==0 or self.stype=='stage':
            sp = spx[i]
          else:
            sp = sp + spx[i]
          sp = self.convs[i](sp)
          sp = self.relu(self.bns[i](sp))
          if i==0:
            out = sp
          else:
            out = torch.cat((out, sp), 1)
        if self.scale != 1 and self.stype=='normal':
          out = torch.cat((out, spx[self.nums]),1)
        elif self.scale != 1 and self.stype=='stage':
          out = torch.cat((out, self.pool(spx[self.nums])),1)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class PreNorm(nn.Module):
    def __init__(self, dim, fn):
        super().__init__()
        self.norm = nn.LayerNorm(dim) #defalt element-wise affine: true
        self.fn = fn

    def forward(self, x, **kwargs):
        return self.fn(self.norm(x), **kwargs)

class FeedForward(nn.Module):
    def __init__(self, dim, hidden_dim, dropout=0.):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(dim, hidden_dim),
            nn.GELU(),
            nn.Dropout(dropout),
            nn.Linear(hidden_dim, dim),
            nn.Dropout(dropout)
        )

    def forward(self, x):
        return self.net(x)

class Attention(nn.Module):
    def __init__(self, dim, heads, dim_head, attn_dropout=0., dropout=0.):
        super().__init__()
        inner_dim = dim_head * heads
        project_out = not (heads == 1 and dim_head == dim)

        # self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False)
        # self.to_qkv = nn.Conv1d(dim, inner_dim * 3, 1, groups=dim_head)
        self.to_qkv = nn.Conv1d(dim, inner_dim * 3, 1, groups=1)

        self.heads = heads
        self.scale = dim_head ** -0.5

        self.attn_drop = nn.Dropout(attn_dropout)

        self.to_out = nn.Sequential(
            nn.Linear(inner_dim, dim),
            nn.Dropout(dropout)
        ) if project_out else nn.Identity()

    def forward(self, x):
        b, d, n, h = *x.shape, self.heads # b n d
        x = rearrange(x, 'b n d -> b d n')

        qkv = self.to_qkv(x).chunk(3, dim=1)
        q, k, v = map(lambda t: rearrange(t, 'b (d h) n -> b h n d', h=h), qkv)

        dots = einsum('b h i d, b h j d -> b h i j', q, k) * self.scale

        attn = dots.softmax(dim=-1)
        attn = self.attn_drop(attn)

        out = einsum('b h i j, b h j d -> b h i d', attn, v)
        out = rearrange(out, 'b h n d -> b n (h d)')
        return self.to_out(out)

class Transformer(nn.Module):
    def __init__(self, dim, heads, dim_head, mlp_dim, dropout=0.0):
        super().__init__()
        self.att = PreNorm(dim, Attention(dim, heads=heads,
                        dim_head=dim_head, dropout=dropout, attn_dropout=0.5))
        self.ff = PreNorm(dim, FeedForward(dim, mlp_dim, dropout=dropout))

    def forward(self, x):
        _, n, _ = x.size()
        # x = rearrange(x, 'b (h w) d -> b d h w', h=int(n**0.5)) # b n d
        # x = self.conv(x)
        # x = rearrange(x, 'b d h w -> b (h w) d') # b n d
        x = self.att(x) + x
        x = self.ff(x) + x
        return x

class PatchEmbed(nn.Module):
    def __init__(self, input_channel=3, embed_dim=None):
        super().__init__()

        self.conv = nn.Sequential(
            conv3x3(input_channel, 32),
            nn.BatchNorm2d(32),
            nn.ReLU(inplace=True),
            conv3x3(32, 64),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            conv3x3(64, embed_dim),
            nn.BatchNorm2d(embed_dim),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(3, 2, 1),
        )

    def forward(self, x):
        b, p, c, h, w = x.size()
        x = rearrange(x, 'b p c h w -> (b p) c h w')
        x = self.conv(x)
        # x = rearrange(x, '(b p) c h w -> b p c h w', p=p)
        return x

class Pre_model(nn.Module):
    def __init__(self, *, num_patch, dim=512, num_classes, pool='mean'):
        super().__init__()
        embed_dim = 128
        head_num = 8
        self.patch_embed = PatchEmbed(input_channel=3, embed_dim=embed_dim)
        self.proj = nn.Conv2d(embed_dim*num_patch, dim, kernel_size=1, stride=1)
        self.conv = Bottle2neck(dim, dim)
        self.transformer1 = Transformer(
            dim=dim, heads=head_num, dim_head=dim//head_num, mlp_dim=512, dropout=0.5)
        self.transformer2 = Transformer(
            dim=dim, heads=head_num, dim_head=dim//head_num, mlp_dim=512, dropout=0.5)
        self.transformer3 = Transformer(
            dim=dim, heads=head_num, dim_head=dim//head_num, mlp_dim=512, dropout=0.5)
        self.transformer4 = Transformer(
            dim=dim, heads=head_num, dim_head=dim//head_num, mlp_dim=512, dropout=0.5)
        self.pool = pool
        self.mlp_head = nn.Sequential(
            nn.LayerNorm(dim),
            nn.Linear(dim, 64)
        )
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
        self.fc = nn.Sequential(
            nn.LayerNorm(64),
            nn.Linear(64, num_classes)
        )

    def forward(self, x):
        b, p, c, h, w = x.size()
        x = self.patch_embed(x) # (b p) c h w

        x = rearrange(x, '(b p) c h w -> b (p c) h w', b=b)
        x = self.proj(x) # b d h w
        x = self.conv(x)

        x = rearrange(x, 'b d h w -> b (h w) d') # b n d

        x = self.transformer1(x) # b n d
        _, n, _ = x.size()
        x = rearrange(x, 'b (h w) d -> b h w d', h=int(n**0.5))
        x = reduce(x, 'b (h1 h2) (w1 w2) d -> b (h1 w1) d', 'max', h2=2, w2=2)

        x = self.transformer2(x) # b n d

        # _, n, _ = x.size()
        # x = rearrange(x, 'b (h w) d -> b h w d', h=int(n**0.5))
        # x = reduce(x, 'b (h1 h2) (w1 w2) d -> b (h1 w1) d', 'max', h2=2, w2=2)

        x = self.transformer3(x) # b n d
        x = self.transformer4(x) # b n d

        x = x.mean(dim=1) if self.pool == 'mean' else x[:, 0]

        out = self.mlp_head(x)
        out = self.fc(out)
        return out

if __name__ == '__main__':
    os.environ['CUDA_VISIBLE_DEVICES'] = '1'
    num_patch = 512
    image = torch.rand(1, num_patch, 3, 28, 28).cuda(0)
    image2 = torch.rand(1, 3, 512, 512).cuda(0)
    pos0 = (torch.rand(1, num_patch)*8).long().cuda(0)
    pos1 = (torch.rand(1, num_patch)*8).long().cuda(0)
    pos2 = (torch.rand(1, num_patch)*50).long().cuda(0)
    model = Pre_model(num_patch=num_patch, dim=512, \
        num_classes=3, pool='mean')
    model = model.cuda(0)
    out = model(image)
    print(out.size())


student_grades = [9, 8, 7 ] #List Example
mySum = sum(student_grades)
length = len(student_grades)
mean = mySum / length
print("Average=",mean)

max_value = max(student_grades)
print("Max Value=",max_value)

print(student_grades.count(8))

#capitalize letter
text1 = "This Text should be in capital"
print(text1.upper())

#student grades using dictionary
student_grades2 = {"marry":9, "Sim": 8 ,"Gary":7}
mySum2 = sum (student_grades2.values()) #values is a method in dict
length2 = len (student_grades2)
mean2 = mySum2 / length2
print(mean2)
print (student_grades2.keys())

#Creating Tuple #Tuples are immutable, difference to list
#cannot use methods like using in list example list.remove()
#Tuples are faster than list
moday_temperatures = { 2,4,5}
print("monday teperatures are:",moday_temperatures)

#Creating List
#This line is edited Online
#this line is edited from PC github
#this line is from laptop Win


#2 assignment fabinocci series
n=int(input('enter the number of terms:'))
a=0
b=1
if n<=0:
    print('the output of your input is',a)
else:
    print(a,b,end=' ')
    for x in range(2,n):
        c=a+b
        print(c,end=' ')
        a=b
        b=c

 #PALIN DROME ARE NOT

# Converting the input number n to a sequence (string).

n=str(input('enter name:'))
# Checking whether the reversed sequence and the original sequence are equal or not.
if (n == "".join(reversed(n))):
    print("Palindrome")
else:
    print("Not a Palindrome")

# #assignment 1 rotate string
def rotate(L,n):
    if n==0:
        return
    if n>0:
        for i in range(n):
            x=L.pop()
            L.insert(0,x)
    else:
        for i in range(-n):
            x=L.pop(0)
            L.append(x)
L=[1,2,3,4,5,6,7,8,9]
n=int(input('enter the integer'))
rotate(L,n)
print(L)

#calculate the number of digits and letters in an string
string=input("Enter string:")
count1=0
count2=0
for i in string:
      if(i.isdigit()):
            count1=count1+1
      elif(i.isalpha()):
            count2=count2+1
print("The number of digits is:")
print(count1)
print("The number of characters is:")
print(count2)

# assignment 1
# number guessing game
import random
number = random.randint(1, 10)

player_name = input("Hello, What's your name?")
number_of_guesses = 0
print('okay! '+ player_name+ ' I am Guessing a number between 1 and 10:')

while number_of_guesses < 5:
    guess = int(input())
    number_of_guesses += 1
    if guess < number:
        print('Your guess is too low')
    if guess > number:
        print('Your guess is too high')
    if guess == number:
        break
if guess == number:
    print('You guessed the number in ' + str(number_of_guesses) + ' tries!')
else:
    print('You did not guess the number, The number was ' + str(number))


alpha = "abcdefghijklmnopqrstuvwxyz"

def gen_alpha_scores():
    scores = {}
    for idx, letter in enumerate(alpha, start=1):
        scores[letter] = idx
        scores[letter.upper()] = idx + 26
    return scores

def part1(packs, scores):
    score = 0
    for items in packs:
        if len(items) % 2 != 0:
            print(f"ERROR: got non-even number of items {len(items), items}")

        half = int(len(items) / 2)
        unique_left = set(items[:half])
        unique_right = set(items[half:])
        overlap = unique_right.intersection(unique_left)
        if len(overlap) != 1:
            print(f"ERROR: got multiple overlap {overlap} in {(left, right)}")

        score += scores[overlap.pop()]
    print(f"Score 1: {score}")

def part2(packs, scores):
    score = 0
    for idx in range(0, len(packs), 3):
        elf1 = set(packs[idx])
        elf2 = set(packs[idx + 1])
        elf3 = set(packs[idx + 2])
        shared = elf1.intersection(elf2).intersection(elf3)
        if len(shared) != 1:
            print(f"ERROR: didn't get 1 shared between {(elf1, elf2, elf3)}")

        score += scores[shared.pop()]
    print(f"Score 2: {score}")

def main():
    packs = []
    with open("input") as file:
        for line in file:
            packs.append(line.strip())

    scores = gen_alpha_scores()

    part1(packs, scores)
    part2(packs, scores)

if __name__ == '__main__':
    main()


import time
import random
import matplotlib.pyplot as plt
import graphviz

class Node:
    def __init__(self,key=None,next=None):
        self.key = key
        self.next = next

class PriorityQueue:
    def __init__(self):
        self.head = None
        self.tail = None
        self.size = 0

    def searchNode(self,i):
        cur = self.head
        while(i > 0):
            if(cur == None): return None
            cur = cur.next
            i = i - 1
        return cur

    # Get parent
    def get_parent(self,i):
        if i > 0:
            return self.searchNode((i-1)//2)
        else:
            return None

    # Get left child
    def get_left_child(self,i):
        return self.searchNode(2*i + 1)

    # Get right child
    def get_right_child(self,i):
        return self.searchNode(2*i + 2)

    def insert(self, key):
        node = Node(key)
        if self.tail:
            self.tail.next = node
        else:
            self.head = node

        self.tail = node

        index = self.size
        self.size = self.size + 1

        while(index != 0):
            parent = self.get_parent(index)
            if(parent.key <= key):break
            tmp = parent.key
            parent.key = key
            node.key = tmp
            index = (index-1)//2
            node = parent

    def _has_left(self,index):
        # determine if there is a left child
        return index * 2 + 1 < self.size

    def _has_right(self,index):
        # determine if there is a left child
        return index * 2 + 2 < self.size

    def delMin(self):
        if self.head is None:
            return None

        self.head.key = self.tail.key

        cur = self.head
        index = 0

        self.size = self.size - 1
        self.tail = self.searchNode(self.size-1)
        self.tail.next = None

        while(self._has_left(index)):
            left = self.get_left_child(index)
            small_child = left
            small_child_index = index * 2 + 1
            if(self._has_right(index)):
                right = self.get_right_child(index)
                if(left.key > right.key):
                    small_child = right
                    small_child_index = index * 2 + 2
            if(small_child.key >= cur.key):
                return
            else:
                tmp = small_child.key
                small_child.key = cur.key
                cur.key = tmp
            cur = small_child
            index = small_child_index

def Q4():
    data = []
    for i in range(1000):
        data.append(random.randint(0, 100000))

    priority_queue = PriorityQueue()

    start = time.time()
    for i in data:
        priority_queue.insert(i)
    end = time.time()
    insert_time = end - start

    start = time.time()
    for i in range(len(data)):
        priority_queue.delMin()
    end = time.time()
    delMin_time = end - start

    x = ['Insert', 'DelMin']
    y = [insert_time, delMin_time]

    plt.bar(x,y)
    plt.title('Linked List based PriorityQueue Performance')
    plt.xlabel('Operation')
    plt.ylabel('Time (s)')
    plt.show()

def dfs_add_edge(priority_queue,g,cur,index):
    left = priority_queue.get_left_child(index)
    if(left == None): return
    g.edge(str(cur.key), str(left.key))
    right = priority_queue.get_right_child(index)
    if(right == None): return
    g.edge(str(cur.key), str(right.key))

    dfs_add_edge(priority_queue,g,left,index*2+1)
    dfs_add_edge(priority_queue,g,right,index*2+2)

def Q5():

    priority_queue = PriorityQueue()
    for i in range(10):
        priority_queue.insert(9-i)

    # Create graph
    g = graphviz.Digraph('PriorityQueue', filename='PriorityQueue.gv', format='png')

    g.node_attr['shape'] = 'circle'
    g.node_attr['style'] = 'filled'

    cur = priority_queue.head
    while cur:
        g.node(str(cur.key),fillcolor='green')
        cur = cur.next

    cur = priority_queue.head
    index = 0

    dfs_add_edge(priority_queue,g,cur,index)

    g.render()


#key d6b483fbdf547be34855aefc9f404b9e
#f"Clicks {clicks}"
import os
from urllib import response
import requests
import json
import csv
import re
from tkinter import *
from tkinter import ttk

def api_key_check():
    global api_key
    try:
        file = open('api_key.txt')
    except IOError as e:
        with open("api_key.txt","w") as f:
            f.write(api_key_entry.get())
    else:
        with file:
            api_key_entry.insert(0, api_key)
    with open('api_key.txt', 'r') as f:
        api_key = f.read()

def load_to_objects():
    global resp
    dataset_id = dataset_id_entry.get()
    global api_key
    print (f"https://apidata.mos.ru/v1/datasets/{dataset_id}")
    resp = requests.get(f"https://apidata.mos.ru/v1/datasets/{dataset_id}?api_key={api_key}")

    filename = "result.json"
    with open(filename, 'w') as f:
        json.dump(resp.text, f)
    print(resp.text)

    templates = json.loads(resp.text)
    with open('sw_templates.json', 'w') as f:
                f.write("")
    for section, commands in templates.items():
        with open('sw_templates.json', 'a') as f:
            if section == "FullDescription":
                    try:
                        with open("FullDescritpion.html","w") as i:
                            i.write(commands)
                    except TypeError:
                        print("FullDiscription is Null")
            f.write(f"\n")
            f.write(f"{section}: {commands} \n")
        print(f"{section}: {commands}")

def load_to_objects_rows():
    global resp
    global api_key
    global templates
    dataset_id = dataset_id_entry.get()
    print (f"https://apidata.mos.ru/v1/datasets/{dataset_id}/rows")
    resp = requests.get(f"https://apidata.mos.ru/v1/datasets/{dataset_id}/rows?api_key={api_key}")

    filename = "result.json"
    with open(filename, 'w') as f:
        json.dump(resp.text, f)
    print(resp.text)

    templates = json.loads(resp.text)
    with open('sw_templates.json', 'w') as f:
                f.write("")
    for tuple in templates:
        for section, commands in tuple.items():
            with open('sw_templates.json', 'a') as f:
                if section == "FullDescription":
                    with open("FullDescritpion.html","w") as i:
                        try:
                            i.write(commands)
                        except TypeError:
                            print("FullDiscription is Null")
                f.write(f"\n")
                f.write(f"{section}: {commands} \n")
            print(f"{section}: {commands}")

def create_csv_from_rows():
    templates = json.loads(resp.text)
    headers = templates[0].keys()

    with open('file.csv', 'w') as f:
        writer = csv.DictWriter(f, fieldnames=headers)
        writer.writeheader()
        writer.writerows(templates)

#
global dataset_id
global api_key
global resp

root = Tk()
root.title("Some Programm :D")
root.geometry("300x200")

greeting = ttk.Label(text="Enter article ID")
greeting.pack(anchor=N)

dataset_id_entry = ttk.Entry()
dataset_id_entry.pack(anchor=N)

api_key_request = ttk.Label(text="Enter your API key")
api_key_request.pack(anchor=N)

api_key = str("")
api_key_entry = ttk.Entry()
api_key_entry.pack(anchor=N)
try:
    file = open('api_key.txt')
except IOError as e:
    print("")
else:
    with open('api_key.txt', 'r') as f:
        api_key = f.read()
        api_key_entry.insert(0, api_key)

load_button = ttk.Button(text="Load description", command = load_to_objects)
load_button.pack(anchor=N)

load_rows_button = ttk.Button(text="Load rows", command = load_to_objects_rows)
load_rows_button.pack(anchor=N)

create_csv_button = ttk.Button(text="Create CSV from rows", command = create_csv_from_rows)
create_csv_button.pack(anchor=N)

load_key_button = ttk.Button(text="Load API Key", command = api_key_check)
load_key_button.pack(anchor=N)
root.mainloop()


from PIL import Image  # Importation du module
import csv  # Importation du package csv
import numpy as np  # Importation de numpy
import sys

def flatten(liste):
    flat_list = []
    for i in range(len(liste)):
        ligne = []
        for j in range(len(liste[i])):
            ligne.append(liste[i][j][0])
        flat_list.append(ligne)
    return flat_list

def img_to_csv(filename, array):
    list_array = array.tolist()
    list_array = flatten(list_array)
    print(len(list_array))
    print(len(list_array[0]))
    with open(filename, 'w', newline='') as csvfile:
        writer = csv.writer(csvfile, delimiter=',',
                            quotechar='"', quoting=csv.QUOTE_MINIMAL)
        writer.writerow([len(list_array), len(list_array[0])])
        writer.writerows(list_array)

def main(input_filename, output_filename):
    # Ouverture de l'image
    img = Image.open(input_filename).convert('LA')
    img_to_csv(output_filename, np.array(img))

if __name__ == "__main__":
    print(f"Arguments count: {len(sys.argv)}")
    if(len(sys.argv) != 3):
        print("Error: please provide input filename and output filename")
    else:
        main(sys.argv[1], sys.argv[2])


import queue

def isOrderableStreet(trucks):
  s = []
  need = 1; state = True
  for truck in trucks:
    while(len(s) != 0 and s[-1] == need):
      need += 1
      s.pop()
    if truck == need:
      need += 1
    elif(len(s) != 0 and s[-1] < truck):
      state = False
      break
    else:
      s.append(truck)
  if(state): return "yes"
  return "no"

def main():
  while True:
    n = int(input())
    if n == 0: break
    trucks = list(map(int, input().strip().split()))
    print(isOrderableStreet(trucks))

if __name__ == '__main__':
  main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 16 14:19:06 2020

@author: hmenet
"""

import arbre
from rec_classes import Amalgamated_tree

#clades are implemented in a hashable type to be used with a dictionary as tuples of sorted leaves

#idea of the algorithm
#1 : in the gene tree, we do not look at the nodes but at the set of leaves of the node
#2 a clade does not have 2 children, but multiple possible couple of children, possible bipartition
#3 we associate to each clade the frequencies of all bipartitions seen in the sample

def sorted_common_leaves_from_tree(tree):
    l=tree.leaves_unrooted()
    l_leaves=[i.name for i in l]
    l_leaves.sort()
    return l_leaves

def sorted_common_leaves_from_leaves(leaves):
    l_leaves=[i.name for i in leaves]
    l_leaves.sort()
    return l_leaves

#clades are numbered, starting at 0

#try to add a clade, if not present
#tree_clade : a tree, the clade will be its leaves
#a clade is just an index, in clade_elements[clade] : sorted list of leaves corresponding to the clade
#and the leaves are the leaves names
def clade_from_tree(tree_clade, clade_elements, clade_keys):
    n_clade=len(clade_elements)
    leaves_clade=tuple(sorted_common_leaves_from_tree(tree_clade))
    clade=-1
    if leaves_clade in clade_keys:
        clade=clade_keys[leaves_clade]
    else:
        clade=n_clade
        clade_elements[clade]=leaves_clade
        clade_keys[leaves_clade]=clade
    return clade

def clade_from_leaves(leaves_clade, clade_elements, clade_keys):
    n_clade=len(clade_elements)
    leaves_clade=tuple(sorted_common_leaves_from_leaves(leaves_clade))
    clade=-1
    if leaves_clade in clade_keys:
        clade=clade_keys[leaves_clade]
    else:
        clade=n_clade
        clade_elements[clade]=leaves_clade
        clade_keys[leaves_clade]=clade
    return clade

#clade_frequencies[u][(v,w)]=0# bipartition v w knowing bipartition u \bar{u}
#l_tree : list of tree on which we want the clade frequencies
#for each bipartitions, 3 possible roots.

def partition_counter_one_tree(tree, clade_elements, clade_keys, bipartition_number, tripartition_number):
    #if rooted, we unroot
    if tree.right2==None:
        arbre.from_rooted_to_un(tree)
    tree_post_order = tree.post_order_traversal_unrooted()
    all_leaves=tree.leaves_unrooted()
    clade1=clade_from_leaves(all_leaves, clade_elements, clade_keys)#clade 0 is the clade of all leaves
    for e in tree_post_order:
        if not e.isRoot():
            #we cut the edge between e and its parent to create a bipartition
            c1=e.leaves_unrooted()#first half of the bipartition
            c2=[leaf for leaf in all_leaves if not leaf in c1]
            clade1=clade_from_leaves(c1, clade_elements, clade_keys)
            clade2=clade_from_leaves(c2, clade_elements, clade_keys)
            bipartition=(min(clade1, clade2), max(clade1, clade2))
            tmp_compte_a_prendre=1
            if bipartition in bipartition_number:
                bipartition_number[bipartition]+=tmp_compte_a_prendre
            else:
                bipartition_number[bipartition]=tmp_compte_a_prendre

        #now, we count the tripartitions generated by deleting the considered node
        #deleting leaves and root do not create tripartitions
        if not e.isLeaf():
            #we already computed one of the clades, c2
            #we now compute the remaining 2
            if not e.isRoot():
                child_clade1=clade_from_tree(e.left, clade_elements, clade_keys)
                child_clade2=clade_from_tree(e.right, clade_elements, clade_keys)
                child_clade3=clade2
            else:
                #if its the root, no clades have been computed
                child_clade1=clade_from_tree(e.left, clade_elements, clade_keys)
                child_clade2=clade_from_tree(e.right, clade_elements, clade_keys)
                child_clade3=clade_from_tree(e.right2, clade_elements, clade_keys)
            l_tmp=[child_clade1, child_clade2, child_clade3]
            l_tmp.sort()
            c1_tmp, c2_tmp,c3_tmp=l_tmp
            tripartition=c1_tmp, c2_tmp,c3_tmp
            if tripartition in tripartition_number:
                tripartition_number[tripartition]+=1
            else:
                tripartition_number[tripartition]=1

#return the clade corresponding to the union of the two input clades
def union_clade(c1,c2,clade_elements, clade_keys):
    l=list(clade_elements[c1])
    l+=list(clade_elements[c2])
    l.sort()
    c=clade_keys[tuple(l)]
    return c

#trees are unrooted
def compute_clade_frequencies(l_tree):
    bipartition_number=dict()
    tripartition_number=dict()
    clade_elements=dict()
    clade_keys=dict()
    #union_clade=dict()
    kcmpt=0
    for tree in l_tree:
        kcmpt+=1
        partition_counter_one_tree(tree, clade_elements, clade_keys,bipartition_number, tripartition_number)
    clade_frequencies=dict()
    n_clade=len(clade_elements)
    for c in range(n_clade):
        clade_frequencies[c]=dict()
    for c1,c2,c3 in tripartition_number:
        #to be faster we would have to keep in memory the relations between the clades
        n_tripartition=tripartition_number[(c1,c2,c3)]
        #a1 a2 knowing a, and ab represent \bar{a}
        for tmp1,tmp2,tmp3 in [(c2,c3,c1),(c1,c3,c2),(c1,c2,c3)]:
            #a,a1,a2,ab = union_clade[(min(tmp1,tmp2), max(tmp1,tmp2))],tmp1,tmp2,tmp3
            #print("a")

            a,a1,a2,ab = union_clade(tmp1,tmp2,clade_elements, clade_keys),tmp1,tmp2,tmp3
            b_continue=True
            for u in [a,a1,a2]:
                if len(clade_elements[u])==0:
                    b_continue=False
            if b_continue:
                clade_frequencies[a][(min(a1,a2),max(a1,a2))]=n_tripartition/bipartition_number[(min(a,ab),max(a,ab))]
    #for the bipartition frequency of the first clade, there is no knowing, no tripartition
    s=sum([bipartition_number[u] for u in bipartition_number.keys()])
    for c1,c2 in bipartition_number:
        clade_frequencies[0][(min(c1,c2),max(c1,c2))]=bipartition_number[(min(c1,c2),max(c1,c2))]/s

    amalgamated_tree=Amalgamated_tree()
    amalgamated_tree.initialize(clade_elements,clade_frequencies)
    return amalgamated_tree

def compute_clade_frequencies_multiple_families(l_tree_by_family):
    am_tree_list=[]
    for l_tree in l_tree_by_family:
        amalgamated_tree=compute_clade_frequencies(l_tree)
        #tree list are given as "name"+str(id_counter)
        am_tree_list.append(amalgamated_tree)
    return am_tree_list

def from_rooted_tree_to_clades(tree):
    clade_elements=dict()
    clade_keys=dict()
    clade_frequencies=dict()
    tree_to_clade=dict()
    clade_to_tree=dict()
    c=0
    for e in tree.post_order_traversal():
        l_tmp=[u.name for u in e.leaves()]
        l_tmp.sort()
        leaves = tuple(l_tmp)
        clade_elements[c]=leaves
        clade_keys[leaves]=c
        tree_to_clade[e]=c
        clade_to_tree[c]=e
        if not e.isRoot():
            p=e.parent
            pl_tmp=[u.name for u in p.leaves()]
            pl_tmp.sort()
            pleaves=tuple(pl_tmp)
            pc=clade_keys[pleaves]
            cl_tmp=[u.name for u in p.left.leaves()]
            cr_tmp=[u.name for u in p.right.leaves()]
            cl_tmp.sort()
            cr_tmp.sort()
            clleaves=tuple(cl_tmp)
            crleaves=tuple(cr_tmp)
            if clleaves in clade_keys and crleaves in clade_keys:
                cl=clade_keys[clleaves]
                cr=clade_keys[crleaves]
                clade_frequencies[pc]=dict()
                clade_frequencies[pc][(min(cl,cr), max(cl,cr))]=1
        if e.isLeaf():
            clade_frequencies[c]=dict()
        c+=1

    amalgamated_tree=Amalgamated_tree()
    amalgamated_tree.initialize(clade_elements,clade_frequencies,corresponding_clade_to_tree=clade_to_tree)

    return amalgamated_tree

#from rooted tree to clades data list, with no amalgamation or root uncertainty, for the intermediate level of 3 level reconciliation
def compute_clade_frequencies_rooted_tree(l_tree_by_family):
    am_tree_list=[]
    for tree in l_tree_by_family:
        am_tree_list.append(from_rooted_tree_to_clades(tree))
    return am_tree_list


# -*- coding: utf-8 -*-
# © <YEAR(S)> <AUTHOR(S)>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).

from openerp import _, api, fields, models, netsvc
from openerp.addons import decimal_precision as dp
from openerp.exceptions import ValidationError

class AccountInvoiceRefund(models.Model):
    _inherit = 'account.invoice.refund'

    product_id = fields.Many2one(
        'product.product',
        string=_(u'Product'),
        ondelete='set null',
        select=True,
    )

    amount = fields.Float(
        _(u'Amount'),
        digits_compute=dp.get_precision('Account'),
    )

    @api.multi
    def compute_refund(self, mode='refund'):
        ctx = self._context.copy()

        invoice_obj = self.env['account.invoice']
        account_m_line = self.env['account.move.line']
        wf_service = netsvc.LocalService('workflow')

        for ref in self:
            product_id = ref.product_id.id
            amount = ref.amount
            for inv in invoice_obj.browse(self._context.get('active_ids')):
                # journal_id = inv.journal_id.id
                if mode != 'refund':
                    if inv.amount_total != inv.residual:
                        raise ValidationError(_(u"Invalid operation, the bill \
                                              already has payments"))
                if amount > inv.residual:
                    raise ValidationError(_(u"Invalid operation, the balance \
                                          of the invoice is less than the \
                                          amount payable"))

        ctx.update({'product_id': product_id})
        ctx.update({'mode': mode})
        ctx.update({'amount': amount})

        res = super(AccountInvoiceRefund, self.with_context(
                    ctx)).compute_refund(mode)
        refund_id = res['domain'][1][2][0]

        wf_service.trg_validate(self._uid, 'account.invoice', refund_id,
                                'invoice_open', self._cr)

        for form in self:
            for invoice in invoice_obj.browse(self._context.get('active_ids')):
                if mode == 'refund':
                    to_reconcile_ids = {}
                    refund = invoice_obj.browse(refund_id)
                    for tmp_line in refund.move_id.line_ids:
                        if tmp_line.account_id.id == inv.account_id.id:
                            to_reconcile_ids[tmp_line.account_id.id] = [
                                tmp_line.id]
                    for account in to_reconcile_ids:
                        invoice.register_payment(account_m_line.browse(
                            to_reconcile_ids[account]))
        return res


import dash
import dash_bootstrap_components as dbc
from dash import Input, Output, State, dcc, html
from dash.exceptions import PreventUpdate

import scout

from ..util.DashAction import DashAction
from ..components.DashPage import DashPage
from ..components.CID import CID
from ..components.Sidebar import Sidebar
from ..components import components
from ..plots.DE.DEHistogram import DEHistogram

from ..plots import DE

class ApplyDE(DashAction):
    def apply(self, groupby, reference, params):
        scout.tl.rank_marker_genes(self.dataset.adata, groupby=groupby, reference=reference, **params)

        return dict(update=True, groupby=groupby)

    def setup_callbacks(self, app):
        output = Output("de-store", "data")

        inputs = dict(
            submit=Input(f"{self.page_id}-main-sidebar-apply_btn", "n_clicks"),
            groupby=State(f"{self.page_id}-groupby", "value"),
            reference=State(f"{self.page_id}-reference", "value")
        )

        for param in DE.de_tools.de_params.values():
            inputs[param.key] = State(f"de-{param.key}", "value")

        @app.dash_app.callback(output=output, inputs=inputs)
        def _(submit, groupby, reference, **kwargs):
            if submit is None:
                raise PreventUpdate

            return self.apply(groupby, reference, params=kwargs)

        # Update References
        output = Output(f"{self.page_id}-reference", "options")
        inputs = dict(
            groupby=Input(f"{self.page_id}-groupby", "value"),
        )

        @app.dash_app.callback(output=output, inputs=inputs)
        def _(groupby):
            cats = self.dataset.get_categoric()

            if len(cats) == 0:
                ref_options = []
            else:
                ref_options = self.dataset.adata.obs[groupby].cat.categories.to_list()

            return ["rest"] + ref_options

    def get_sidebar_params(self) -> list:
        cats = self.dataset.get_categoric()

        divs = []

        divs.append(
            html.Div(
                children=[
                    html.Label("Group By", className="param-label",),
                    html.Div([
                        dcc.Dropdown(options=cats, value=cats[0], id=f"{self.page_id}-groupby", clearable=False)
                    ], className="param-select"),
                ],
                className="param-row-stacked",
            )
        )

        divs.append(
            html.Div(
                children=[
                    html.Label("Reference", className="param-label"),
                    html.Div([
                        dcc.Dropdown(
                            options=["rest"], value="rest", id=f"{self.page_id}-reference", clearable=False
                        )
                    ], className="param-select"),
                ],
                className="param-row-stacked",
            )
        )

        for key, param in DE.de_tools.de_params.items():
            divs.append(
                html.Div(
                    children=[
                        html.Label(param.name, className="param-label",),
                        html.Div([
                            dcc.Dropdown(
                                id=f"{self.page_id}-{key}", value=param.default, options=param.allowed_values,
                                clearable=False,
                            )
                        ], className="param-select"),
                    ],
                    className="param-row-stacked",
                )
            )

        # layout = html.Div(children=divs)
        return divs

class DEPage(DashPage):
    def __init__(self, dataset, order):
        super().__init__("pages.de", "DE", "de", order)
        self.dataset = dataset
        self.components.update(
            main_figure=DE.DEVolcano(dataset=self.dataset, page_id=self.page_id, loc_class="main"),
        )
        self.components.update(
            secondary_figure=DEHistogram(
                self.dataset, page_id=self.page_id, loc_class="secondary",
                select_groupby_cid=self.components["main_figure"].children["select_groupby"].cid,
                select_reference_cid=self.components["main_figure"].children["select_reference"].cid,
            )
        )
        self.actions.update(
            de_apply=ApplyDE(CID(self.page_id, "static", "de_apply"), self.dataset),
        )

    def create_layout(self):
        self.components["top_sidebar"] = Sidebar(
            page_id=self.page_id, loc_class="main",
            title="Differential Expression Settings", create_btn=True,
            params_children=self.actions["de_apply"].get_sidebar_params(),
        )

        self.components["bot_sidebar"] = Sidebar(
            page_id=self.page_id, loc_class="bottom",
            title="Empty", create_btn=False,
            params_children=[],
        )

        layout = [
            html.Div(
                className="top", children=[
                    self.components["top_sidebar"].create_layout(),
                    self.components["main_figure"].create_layout(),
                    self.components["secondary_figure"].create_layout()
                ]
            ),
            html.Div(
                className="bottom",
                children=[
                    self.components["bot_sidebar"].create_layout()
                ],
            ),
        ]
        return layout


from django.shortcuts import render,redirect
from .models import *
from .forms import *

# Create your views here.
def index(request):
    student = Student.objects.order_by("first_name")
    diction={'title':"index",'student':student}
    return render(request,"FirstApp/index.html",context=diction)

def studentform(request):
    form = StudentForm

    if request.method == "POST":
        form = StudentForm(request.POST)
        if form.is_valid():
            form.save(commit=True)
            return redirect("/")

    diction={'title':"studentform",'student':form}
    return render(request,"FirstApp/studentform.html",context=diction)

def student_info(request,student_id):
    student_info = Student.objects.get(pk = student_id)
    dict = {'student':student_info}
    return render(request,"FirstApp/studentinfo.html",context=dict)

def student_update(request,student_id):
    student_info = Student.objects.get(id=student_id)
    form = StudentForm(instance=student_info)
    if request.method =="POST":
        form = StudentForm(request.POST,instance=student_info)

        if form.is_valid():
            form.save(commit=True)
            return index(request)

    diction = {'student':form}
    return render(request,"FirstApp/update.html",context=diction)

def student_delete(request,student_id):
    student = Student.objects.get(pk=student_id).delete()
    diction = {'msg':'delete done !'}
    return index(request)
    return render(request,"FirstApp/delete.html",context=diction)


#!./env/bin/python3

# Imports
from csv import reader
from sys import argv
from keyValClient import KeyValClient

# A function that creates an instance of a KeyValClient
def main():
    arguments = argv[1:]

    if len(arguments) != 2:
        print("client <serverAddress> <port>")
        return

    serverAddress = arguments[0]
    port = int(arguments[1])

    testOperationsPath = "data/kvp-operations.csv"

    keyValClient = KeyValClient(serverAddress, port)

    with open(testOperationsPath, newline="\n") as operationsFile:
        operationReader = reader(operationsFile, delimiter=",")
        for operation in operationReader:
            command = operation[0]
            if command == "PUT":
                keyValClient.put(operation[1], operation[2])
            elif command == "GET":
                keyValClient.get(operation[1])
            elif command == "DELETE":
                keyValClient.delete(operation[1])
            else:
                print(command + " is not a valid command")

if __name__ == "__main__":
    main()


import numpy as np
import time
import logging
from tqdm import tqdm
import h5py
import os
from pathlib import Path

def names_to_pair(name0, name1):
    return '_'.join((name0.replace('/', '-'), name1.replace('/', '-')))

def load_pairs(args):
    args.pair_dir = Path(args.pair_dir, args.benchmark_name)
    args.db_pairs_path = args.pair_dir / args.pairs[0]
    args.query_pairs_path = args.pair_dir / args.pairs[1]
    if not args.db_pairs_path.exists():
        print(f'{args.db_pairs_path} does not exist!!')
        return None
    if not args.db_pairs_path.exists():
        print(f'{args.query_pairs_path} does not exist!!')
        return None

    # Load pairs
    print(f'Pair list: {args.pairs}')
    db_pairs = []
    query_pairs = []
    with open(args.db_pairs_path) as f:
        db_pairs += f.readlines()
    with open(args.query_pairs_path) as f:
        query_pairs += f.readlines()
    print(f'Loaded pairs db:{len(db_pairs)} query:{len(query_pairs)}')
    pair_list = db_pairs + query_pairs
    return pair_list

def init_paths(args):
    # Define experiment tags
    if args.qt_psize > 0:
        args.qt_tag = f'qt{args.qt_psize}d{args.qt_dthres}sc{args.sc_thres}'
        if args.qt_unique:
                args.qt_tag += 'uni'
    else:
        args.qt_tag = f'sc{args.sc_thres}'

    db_pair_tag = args.pairs[0].replace('db-pairs-', '').replace('.txt', '')
    query_pair_tag = args.pairs[1].replace('pairs-query-', '').replace('.txt', '')
    args.pair_tag = db_pair_tag + query_pair_tag

    # Output paths
    output_dir = Path('outputs', args.benchmark_name, args.model_tag, args.conf_tag)
    if not output_dir.exists():
        os.makedirs(output_dir)
    args.output_dir = output_dir
    args.empty_sfm = Path('outputs', args.benchmark_name, 'empty_sfm')

    # Result dir for sfm models and localization results
    result_dir = output_dir / f'{args.pair_tag}_{args.qt_tag}'
    if not result_dir.exists():
        os.makedirs(result_dir)
    logging.info(f'Result folder: {result_dir}')
    args.result_dir = result_dir
    args.result_sfm = result_dir / 'sfm_final'
    return args

def init_empty_sfm(args):
    from immatch.utils.colmap.data_parsing import (
        create_empty_model_from_nvm_and_database, create_empty_model_from_reference_model
    )

    if args.empty_sfm.exists():
        logging.info('Empty sfm existed.')
        return
    dataset_dir = args.dataset_dir

    if args.benchmark_name == 'robotcar':
        create_empty_model_from_nvm_and_database(
            dataset_dir / '3D-models/all-merged/all.nvm',
            dataset_dir / '3D-models/overcast-reference.db',
            args.empty_sfm
        )
    elif args.benchmark_name in ['aachen']:
        # Original Aachen
        logging.info('Init empty sfm from nvm for aachen...')
        create_empty_model_from_nvm_and_database(
            dataset_dir  / '3D-models/aachen_cvpr2018_db.nvm',
            dataset_dir  / 'database.db',
            args.empty_sfm,
            dataset_dir / '3D-models/database_intrinsics.txt',
        )
    elif args.benchmark_name in ['aachen_v1.1']:
        # Aachen v1.1
        logging.info('Init empty sfm from bins for aachenv1.1...')
        create_empty_model_from_reference_model(
            dataset_dir / '3D-models/aachen_v_1_1',
            args.empty_sfm
        )
    else:
        logging.error(f'Invalid benchmark {args.benchmark_name}!!')

def reconstruct_database_pairs(args):
    from third_party.hloc.hloc import triangulation

    # Reconstruct database pairs
    if (args.result_sfm / 'model' / 'images.bin').exists():
        logging.info('Reconstruction existed.')
        return
    logging.info('\nReconstructing database images....')
    triangulation.main(
        args.result_sfm,
        args.empty_sfm,
        args.im_dir,
        args.db_pairs_path,
        args.result_dir / 'keypoints.h5',
        args.result_dir /'matches.h5',
        colmap_path=args.colmap)
    logging.info('Finished reconstruction.')

def localize_queries(args):
    from third_party.hloc.hloc import localize_sfm

    # Localize query pairs
    for ransac_thresh in args.ransac_thres:
        localize_txt = f'{args.model_tag}_{args.conf_tag}.{args.pair_tag}.{args.qt_tag}.r{ransac_thresh}.txt'
        if args.covis_cluster:
            localize_txt = localize_txt.replace('txt', 'covis.txt')
        logging.info(f'Localize queries...')
        print('>>>>', localize_txt)
        localize_sfm.main(
            args.result_sfm / 'model',
            args.dataset_dir / 'queries/*_queries_with_intrinsics.txt',
            args.query_pairs_path,
            args.result_dir / 'keypoints.h5',
            args.result_dir / 'matches.h5',
            args.result_dir / localize_txt,
            ransac_thresh=ransac_thresh,
            covisibility_clustering=args.covis_cluster,
            changed_format=True,
            benchmark=args.benchmark_name
        )

def get_grouped_ids(array):
    # Group array indices based on its values
    # all duplicates are grouped as a set
    idx_sort = np.argsort(array)
    sorted_array = array[idx_sort]
    vals, ids, count = np.unique(sorted_array, return_counts=True, return_index=True)
    res = np.split(idx_sort, ids[1:])
    return res

def get_unique_matches_ids(match_ids, scores):
    if len(match_ids.shape) == 1:
        return [0]

    k1s = match_ids[:, 0]
    k2s = match_ids[:, 1]
    isets1 = get_grouped_ids(k1s)
    isets2 = get_grouped_ids(k2s)

    uid1s = []
    for ids in isets1:
        if len(ids) == 1:
            uid1s.append(ids[0])  # Unique
        else:
            uid1s.append(ids[scores[ids].argmax()])
    uid2s = []
    for ids in isets2:
        if len(ids) == 1:
            uid2s.append(ids[0])  # Unique
        else:
            uid2s.append(ids[scores[ids].argmax()])
    uids = list(set(uid1s).intersection(uid2s))
    return uids

def quantize_keypoints(fpts, kp_data, psize=48, dthres=4):
    """Keypoints quantization algorithm.
    The image is divided into cells, where each cell represents a psize*psize local patch.
    Each input point has its linked coarse point (patch region).
    For all points inside a patch region, those points with distances smaller than the given
    threshold will be merged and represented by their mean pixel.

    Args:
        - fpts: the set of input keypoint coordinates, shape (N, 2)
        - kp_data: the keypoint data dict linked to an image
        - psize: the size to divide an image into multiple patch regions
        - dthres: the distance threshold (in pixels) for merging points within the same patch region
    Return:
        - fpt_ids: the keypoint ids of the input points
    """

    # kp_data: {'kps':[], 'kp_means': kp_dict}
    fpt_ids = []
    cpts = fpts // psize * psize   # Point coordinates (x, y)
    for cpt, fpt in zip(cpts, fpts):
        cpt = tuple(cpt)
        kps = kp_data['kps']
        kp_dict = kp_data['kp_means']  # {cpt : {'means':[], 'kids':[]}}
        if cpt not in kp_dict:
            kid = len(kps)
            kps.append(fpt)  # Insert another keypoint
            kp_dict[cpt] = {'means':[fpt], 'kids':[kid]}  # Init 1st center
        else:
            kids = kp_dict[cpt]['kids']
            centers = kp_dict[cpt]['means']  # N, 2
            dist = np.linalg.norm(fpt - np.array(centers), axis=1)
            cid = np.argmin(dist)
            if dist[cid] < dthres:
                centers[cid] = (centers[cid] + fpt) / 2   # Update center
                kid = kids[cid]
                kps[kid] = centers[cid]  # Update key point value
            else:
                kid = len(kps)
                kps.append(fpt)  # Insert another keypoint
                centers.append(fpt)  # Insert as a new center
                kids.append(kid)
        fpt_ids.append(kid)
    return fpt_ids

def compute_keypoints(pts, kp_data):
    kps = kp_data['kps']
    kp_dict = kp_data['kpids']
    pt_ids = []
    for pt in pts:
        key = tuple(pt)
        if key not in kp_dict:
            kid = len(kps)   # 0-based, the next inserting index
            kps.append(pt)
            kp_dict[key] = kid
        else:
            kid = kp_dict[key]
        pt_ids.append(kid)
    return pt_ids

def match_pairs_with_keys_exporth5(matcher, pairs, pair_keys, match_file, debug=False):
    # Pairwise matching
    num_matches = []
    match_times = []
    start_time = time.time()

    with h5py.File(match_file, 'a') as fmatch:
        matched = list(fmatch.keys())
        print(f'\nLoad match file, existing matches {len(matched)}')
        print(f'Start matching, total {len(pairs)} pairs...')
        for pair, key in tqdm(zip(pairs, pair_keys), total=len(pairs), smoothing=.1):
            im1_path, im2_path = pair
            if key in matched:
                num_matches.append(len(fmatch[key]['matches']))
                continue

            try:
                t0 = time.time()
                match_res = matcher(im1_path, im2_path)
                match_times.append(time.time() - t0)
            except:
                print(f'##Failed matching on {key}')
                continue

            matches = match_res[0]
            scores = match_res[3]
            N = len(matches)
            num_matches.append(N)

            # Add print for easy debugging
            if debug:
                print(f'{pair} matches: {N}')

            # Save matches
            grp = fmatch.create_group(key)
            grp.create_dataset('matches', data=matches)
            grp.create_dataset('scores', data=scores)
        total_time = time.time() - start_time
        mean_time = np.mean(match_times) if len(match_times) > 0 else 0.0
        print(f'Finished matched pairs: {len(fmatch)} num_matches:{np.mean(num_matches):.2f} '
              f'match_time/pair:{mean_time:.2f}s time:{total_time:.2f}s.')

def match_pairs_exporth5(pair_list, matcher, im_dir, output_dir, debug=False):
    # Construct pairs and pair keys
    pairs = []
    pair_keys = []
    pair_keys_set = set()
    for pair_line in tqdm(pair_list, smoothing=.1):
        name0, name1 = pair_line.split()
        key = names_to_pair(name0, name1)
        key_inv = names_to_pair(name1, name0)
        if key_inv in pair_keys_set:
            continue

        pair_keys.append(key)
        pair_keys_set.add(key)
        pair = (str(im_dir / name0), str(im_dir / name1))
        pairs.append(pair)

    match_file = output_dir/'matches_raw.h5'
    match_pairs_with_keys_exporth5(matcher, pairs, pair_keys, match_file, debug=debug)

def process_matches_and_keypoints_exporth5(pair_list, output_dir, result_dir,
                                           sc_thres=0.25, qt_dthres=4, qt_psize=48,
                                           qt_unique=True):
    """
    This function should be executed after running match_pairs_exporth5(), which save the
    precomputed the raw matches and their scores in a hdf5.
    This function first filters out the less confident matches based on the given score threshold.
    Then the keypoints are computed accordingly from the filtered matches by finding the unique set
    of points that have been matched for each image.
    Afterwards, matches are represented by pairs of keypoint ids.
    We further provide an option to quantize keypoints, where keypoints are closer than
    a given distance will be merged into one.
    For the methods that directly obtain pixel-level matches without having an explicit keypoint
    detection stage, such quantization could be helpful or necessary to enable proper stability
    for the triangulation step of a localization pipeline.
    Notice, such quantization sacrifices the pixel-wise accuracy, so the methods with
    specific keypoint detection (SuperPoint, D2Net, ..etc) or the methods that produce
    patch-level matches (NCNet, SparseNCNet) should not use it.

    Args:
        - pair_list: list of pair strings
        - output_dir: the directory where matches_raw.h5 is saved
        - result_dir: the output directory to save processed matches and keypoints
        - sc_thres: the score threshold to filter less confident matches
        - qt_dthres, qt_psize: args for quantization, set qt_psize as 0 can skip the quantization.
        - qt_unique: flag to maintain the uniqueness of matches after quantization

    Nothing is returned. The processed keypoints are saved as keypoints.h5 and matches (represented by the
    keypoints ids) are saved as matches.h5 in the result directory.
    """
    # Select matches from the raw matches and quantize keypoints
    if (result_dir/'keypoints.h5').exists():
        logging.info('Result matches and keypoints already existed, skip')
        return

    match_file = h5py.File(output_dir/'matches_raw.h5', 'r')
    all_kp_data = {}
    logging.info('Start parse matches and quantize keypoints ...')
    with h5py.File(result_dir/'matches.h5', 'w') as res_fmatch:
        for pair in tqdm(pair_list, smoothing=.1):
            name0, name1 = pair.split()
            pair = names_to_pair(name0, name1)

            if pair not in match_file:
                continue

            matches = match_file[pair]['matches'].__array__()
            scores = match_file[pair]['scores'].__array__()
            valid = np.where(scores >= sc_thres)[0]
            matches = matches[valid]
            scores = scores[valid]

            # Compute match ids and quantize keypoints
            match_ids = matches_to_keypoint_ids(
                matches, scores, name0, name1, all_kp_data,
                qt_dthres, qt_psize, qt_unique
            )

            # Save matches
            grp = res_fmatch.create_group(pair)
            grp.create_dataset('matches0', data=match_ids)
        num_pairs = len(res_fmatch.keys())

    # Save keypoints
    with h5py.File(result_dir/'keypoints.h5', 'w') as res_fkp:
        logging.info(f'Save keypoints from {len(all_kp_data)} images...')
        for name in tqdm(all_kp_data, smoothing=.1):
            kps = np.array(all_kp_data[name]['kps'], dtype=np.float32)
            kgrp = res_fkp.create_group(name)
            kgrp.create_dataset('keypoints', data=kps)
    logging.info(f'Finished quantization, match pairs:{num_pairs}')
    match_file.close()

def matches_to_keypoint_ids(matches, scores, name0, name1, all_kp_data,
                            qt_dthres=-1, qt_psize=-1, qt_unique=True):
    if len(matches) == 0:
        return np.empty([0, 2], dtype=np.int32)

    if qt_psize > 0 and qt_dthres > 0:
        # Compute keypoints jointly with quantization
        if name0 not in all_kp_data:
            all_kp_data[name0] = {'kps':[], 'kp_means':{}}
        if name1 not in all_kp_data:
            all_kp_data[name1] = {'kps':[], 'kp_means':{}}

        id1s = quantize_keypoints(matches[:, 0:2], all_kp_data[name0],
                                  psize=qt_psize, dthres=qt_dthres)
        id2s = quantize_keypoints(matches[:, 2:4], all_kp_data[name1],
                                  psize=qt_psize, dthres=qt_dthres)
        match_ids = np.dstack([id1s, id2s]).reshape(-1, 2) # N, 2

        # Remove n-to-1 matches after quantization
        if qt_unique and len(match_ids) > 1:
            uids = get_unique_matches_ids(match_ids, scores)
            match_ids = match_ids[uids]
            uids = get_unique_matches_ids(match_ids, scores)
            match_ids = match_ids[uids]
    else:
        # Compute keypoints without quantization
        if name0 not in all_kp_data:
            all_kp_data[name0] = {'kps':[], 'kpids':{}}
        if name1 not in all_kp_data:
            all_kp_data[name1] = {'kps':[], 'kpids':{}}

        id1s = compute_keypoints(matches[:, 0:2], all_kp_data[name0])
        id2s = compute_keypoints(matches[:, 2:4], all_kp_data[name1])
        match_ids = np.dstack([id1s, id2s]).reshape(-1, 2)

    return match_ids


#Exercício Python 20: O mesmo professor do desafio 19 quer sortear a ordem de
# apresentação de trabalhos dos alunos. Faça um programa que leia o nome dos
# quatro alunos e mostre a ordem sorteada.
import random
from random import shuffle
import sys

op = 'S'
while(op =='S'):
    a1 = input('Informe o nome do aluno 1: ').upper()
    a2 = input('Informe o nome do aluno 2: ').upper()
    a3 = input('Informe o nome do aluno 3: ').upper()
    a4 = input('Informe o nome do aluno 4:').upper()
    lista =  [a1,a2,a3,a4]
    ordem = random.shuffle(lista)

    print("Ordem dos trabalhos " ,lista)

    op = input('\n Deseja continuar executando? S = Sim ou N = não: ' ).upper()

else:
    print('Saindo da aplicação ...')
    sys.exit()


import json, random
from src.GameObjects.Card.Card import Card
from src.GameObjects.Card.CardType import CardType
from src.GameObjects.Card.CardAttribute.DrinkAttribute import DrinkAttribute
from src.GameObjects.Card.CardAttribute.FoodAttribute import FoodAttribute
from src.GameObjects.Card.CardAttribute.SweetAttribute import SweetAttribute
from src.GameObjects.Card.CardAttribute.FruitAttribute import FruitAttribute
from src.GameObjects.Card.CardAttribute.AnyAttribute import AnyAttribute

"""
Summary:

Quest Structure
Name: Name of the Quest
QuestCode: Code of the quest and its attribute number as follows

Fo - Food
Dr - Drink
Sw - Sweet
Fr - Fruit

Attribute number see CardAttribute in GameObject Section

Range:
adjacent - near cards, bidirection
all - all card in the field

### Quest Checking is available in "src > GameObjects > Board > Board.py"

"""

class Quest:
    def __init__(
        self, quest, customize=False, name=None, range=None, condition=None, reward=None
    ):
        self.name = quest["name"]
        self.range = quest["range"].upper()
        self.condition = []
        self.reward = int(quest["reward"])

        # Render Area
        quest_code_overall = quest["questcode"].split(";")

        for q in quest_code_overall:
            card_type = ""
            card_attrib = ""
            card_attribute_pool = []
            if q[0:2] == "Fo":
                card_type = CardType.FOOD
                for attribute in FoodAttribute:
                    card_attribute_pool.append(attribute)
            elif q[0:2] == "Dr":
                card_type = CardType.DRINK
                for attribute in DrinkAttribute:
                    card_attribute_pool.append(attribute)
            elif q[0:2] == "Fr":
                card_type = CardType.FRUIT
                for attribute in FruitAttribute:
                    card_attribute_pool.append(attribute)
            elif q[0:2] == "Sw":
                card_type = CardType.SWEET
                for attribute in SweetAttribute:
                    card_attribute_pool.append(attribute)
            elif q[0:2] == "An":
                card_type = CardType.ANY
                for attribute in AnyAttribute:
                    card_attribute_pool.append(attribute)
            else:
                raise TypeError("Cannot render quest" + q["name"])

            attrib_num = int(q[2:])

            for a in card_attribute_pool:
                if a.value == attrib_num:
                    card_attrib = a
                    break
            else:
                raise TypeError("Invalid Attribute Number of " + str(attrib_num))

            self.condition.append(Card(card_type, card_attrib))

    def view_quest(self):
        card_outstr = ""
        for card in self.condition:
            card_outstr += str(card.view_card()) + ";"
        return self.name + " " + self.range + " Condition:" + card_outstr

    def get_quest(self):
        return {
            "name": self.name,
            "range": self.range,
            "condition": self.condition,
            "reward": self.reward,
        }


import win32process
import time
import csv
import pandas as pd
import pymouse,pykeyboard,os,sys
from pymouse import *
import pyautogui
from pykeyboard import PyKeyboard
import pyperclip

m = PyMouse()
k = PyKeyboard()

handle = win32process.CreateProcess("C:\\Users\student\\AppData\\Local\Programs\\Cisco Spark\\CiscoCollabHost.exe",'', None , None , 0 ,win32process. CREATE_NO_WINDOW , None , None ,win32process.STARTUPINFO())
time.sleep(2)
m.click(1000,504,1,1)
time.sleep(0.5)
k.type_string("26427466208")

k.press_key(k.tab_key)
time.sleep(0.5)
k.press_key(k.tab_key)

time.sleep(0.5)

k.type_string("Liao Bo Hao") # 目前只能輸入英文 需要中文再調整
k.press_key(k.tab_key)
time.sleep(0.5)
k.press_key(k.tab_key)
time.sleep(0.5)
k.type_string("請輸入自己的email")
k.press_key(k.enter_key)
time.sleep(2)
k.press_key(k.enter_key)
time.sleep(2)
k.press_key(k.enter_key)
time.sleep(4)
k.type_string("BDSE28@iSpan")
k.press_key(k.enter_key)
k.press_key(k.enter_key)
k.press_key(k.enter_key)


#This is to "split" the words in a String like "someWordsHere" into "some" "Words" "Here"

z = "findLongestWord"

words = []

start = 0
for i in z:
    if i.isupper() == True:
        pos = z.index(i)
        word = z[start:pos]
        start = pos

        words.append(word)

word = z[start:]
words.append(word)

print (words)


#!/bin/python

import sys

a,b,c,d,e = input().strip().split(' ')
a,b,c,d,e = [int(a),int(b),int(c),int(d),int(e)]
r=[a,b,c,d,e]
l=[a,b,c,d,e]
g=[a,b,c,d,e]
min1= min(l)
max1= max(l)
minsum=0
maxsum=0
c=1
d=1
e=[]
z=[]
for i in range(len(r)):
    if min1==r[i] and c==1:
        del l[i]
        k=l
        c=2
    elif max1==r[i] and d==1:
        del g[i]
        z=g
        d=2

minsum=sum(z)
maxsum=sum(k)
print(minsum,end=" ")
print(maxsum)