content
stringlengths
7
1.05M
def setup(): #this is your canvas size size(1000,1000) #fill(34,45,56,23) #background(192, 64, 0) stroke(255) colorMode(RGB) strokeWeight(1) #rect(150,150,150,150) def draw(): x=mouseX y=mouseY ix=width-x iy=height-y px=pmouseX py=pmouseY background(0,0,0) #rect(150,150,150,150) strokeWeight(5) line(x,y,ix,iy) #line(x,y,px,py) strokeWeight(120) point(40,x) if (mousePressed == True): if (mouseButton == LEFT): fill(196,195,106,255) #box(200,500,500) strokeWeight(0) rectMode(CENTER) rect(height/2,width/2,ix,100) strokeWeight(0) fill(144,135,145) rectMode(CORNERS) rect(mouseX-10,iy-10,width/2,height/2) fill(155,211,211) rectMode(CORNER) rect(mouseX,mouseY,50,50) fill(205,126,145) ellipseMode(CORNER) ellipse(px,py,35,35) #colorMode(RGB,100,100,100,100) fill(80,98,173,188) ellipseMode(CORNERS) ellipse(x*.75,y*.75,35,35) frameRate(12) println(str(mouseX)+"."+str(mouseY)) println(pmouseX-mouseX) print("why is it there?") if (x>500): fill(255,160) rect(0,0,x,height) else: fill(255,160) rect(0,0,width-ix,height) if ((x>250) and (x<500) and (y>500) and (y<1000)): fill(255) rect(250,500,250,500) fill(245,147,188) rectMode(CORNER) rect(mouseX,mouseY,50,50) if ((x>0) and (x<250) and (y>500) and (y<1000)): fill(255) rect(0,500,250,500) fill(20,126,145) ellipseMode(CORNER) ellipse(px,py,35,35) if (mousePressed and (x>500)): background(255,255,255) fill(200) rectMode(CENTER) rect(width/2,height/2,500,500) #colorMode(RGB,100,100,100,100) ellipseMode(CORNERS) fill(170,170,170,255) strokeWeight(4) ellipse(width/2-125,height/2-125,width/2-75,height/2-75) ellipse(width/2+75,height/2-125,width/2+125,height/2-75) a = width/2 b = height/2 strokeWeight(7) noFill() curve(a-125,1.4*b-125,a-50,1.4*b-95,a+50,1.4*b-95,a+125,1.4*b-125)
def binary_search(coll, elem): low = 0 high = len(coll) - 1 while low <= high: middle = (low + high) // 2 guess = coll[middle] if guess == elem: return middle if guess > elem: high = middle - 1 else: low = middle + 1 return None print(binary_search([1, 3, 5, 7, 9], 0)) print(binary_search([1, 3, 5, 7, 9], 7))
# Time Complexity => O(n^2 + log n) ; log n for sorting class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: output = [] nums.sort() for i in range(len(nums)-2): if i>0 and nums[i]==nums[i-1]: continue j = i+1 k = len(nums)-1 while j<k: temp = nums[i] + nums[j] + nums[k] if temp == 0: output.append([nums[i],nums[j],nums[k]]) while j<k and nums[j]==nums[j+1]: j+=1 while j<k and nums[k]==nums[k-1]: k-=1 j+=1 k-=1 elif temp>0: k-=1 else: j+=1 return output
# input 3 number and calculate middle number def Middle_3Num_Calc(a, b, c): if a >= b: if b >= c: return b elif a <= c: return a else: return c elif a > c: return a elif b > c: return c else: return b def Middle_3Num_Calc_ver2(a, b, c): if (b >= a and c <= a) or (b <= a and c >= a): return a elif (a > b and c < b) or (a < b and c > b): return b return c print('Calculate middle number') a = int(input('Num a: ')) b = int(input('Num b: ')) c = int(input('Num c: ')) print(f'Middle Num is {Middle_3Num_Calc(a, b, c)}.')
# -*- coding: utf-8 -*- class Null(object): def __init__(self, *args, **kwargs): return None def __call__(self, *args, **kwargs): return self def __getattr__(self, name): return self def __setattr__(self, name, value): return self def __delattr__(self, name): return self def __repr__(self): return "<Null>" def __str__(self): return "Null"
batch_size = 32 epochs = 200 lr = 0.01 momentum = 0.9 no_cuda =False cuda_id = '0' seed = 1 log_interval = 10 l2_decay = 5e-4 class_num = 31 param = 0.3 bottle_neck = True root_path = "/data/zhuyc/OFFICE31/" source_name = "dslr" target_name = "amazon"
def solution(record): Change = "Change" entry = {"Enter": " entered .", "Leave": " left." } recs = [] for r in record: r = r.split(" ") recs.append(r) # Change user id for all record first. for r in recs: uid = "" nickname = "" if (Change in r): uid = r[1] nickname = r[2] for r in recs: if (uid in r): r[2] = nickname # Create user data db - {"uid": "nickname"} user_db = {} for r in recs: user_db[r[1]] = r[-1] answer = [] for r in recs: if (Change not in r): message = "" message = f"{user_db[r[1]]}{entry[r[0]]}" answer.append(message) print(message) return answer
with open("input4.txt") as f: raw = f.read() pp = raw.split("\n\n") ppd = list() for p in pp: p = p.replace("\n", " ") p = p.strip() if not p: continue pairs = p.split(" ") ppd.append({s.split(":")[0]: s.split(":")[1] for s in pairs}) def isvalid(p): if not {"byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid"}.issubset(ks): return False print(p) if not len(p["byr"]) == 4: return False if not (1920 <= int(p["byr"]) <= 2002): return False if not (2010 <= int(p["iyr"]) <= 2020): return False if not (2020 <= int(p["eyr"]) <= 2030): return False if p["hgt"].endswith("cm"): num = p["hgt"].split("cm")[0] if not 150 <= int(num) <= 193: return False elif p["hgt"].endswith("in"): num = p["hgt"].split("in")[0] if not (59 <= int(num) <= 76): return False else: return False if not p["hcl"].startswith("#"): return False if not len(p["hcl"]) == 7: return False for c in p["hcl"][1:]: if not c in "abcdef0123456789": return False if not p["ecl"] in ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]: return False if not len(p["pid"]) == 9: return False for c in p["pid"]: if not c in "0123456789": return False return True ok = 0 for p in ppd: ks = set(p.keys()) if isvalid(p): ok += 1 print(ok)
class Block(object): def __init__(self, block): self.block = block def get_block(self): return self.block def set_block(self, new_block): self.block = new_block
# Author: Nic Wolfe <[email protected]> # URL: http://code.google.com/p/sickbeard/ # # This file is part of Sick Beard. # # Sick Beard is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Sick Beard is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Sick Beard. If not, see <http://www.gnu.org/licenses/>. # all regexes are case insensitive ep_regexes = [ ('standard_repeat', # Show.Name.S01E02.S01E03.Source.Quality.Etc-Group # Show Name - S01E02 - S01E03 - S01E04 - Ep Name ''' ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator s(?P<season_num>\d+)[. _-]* # S01 and optional separator e(?P<ep_num>\d+) # E02 and separator ([. _-]+s(?P=season_num)[. _-]* # S01 and optional separator e(?P<extra_ep_num>\d+))+ # E03/etc and separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('fov_repeat', # Show.Name.1x02.1x03.Source.Quality.Etc-Group # Show Name - 1x02 - 1x03 - 1x04 - Ep Name ''' ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator (?P<season_num>\d+)x # 1x (?P<ep_num>\d+) # 02 and separator ([. _-]+(?P=season_num)x # 1x (?P<extra_ep_num>\d+))+ # 03/etc and separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('standard', # Show.Name.S01E02.Source.Quality.Etc-Group # Show Name - S01E02 - My Ep Name # Show.Name.S01.E03.My.Ep.Name # Show.Name.S01E02E03.Source.Quality.Etc-Group # Show Name - S01E02-03 - My Ep Name # Show.Name.S01.E02.E03 ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator s(?P<season_num>\d+)[. _-]* # S01 and optional separator e(?P<ep_num>\d+) # E02 and separator (([. _-]*e|-)(?P<extra_ep_num>\d+))* # additional E03/etc [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('fov', # Show_Name.1x02.Source_Quality_Etc-Group # Show Name - 1x02 - My Ep Name # Show_Name.1x02x03x04.Source_Quality_Etc-Group # Show Name - 1x02-03-04 - My Ep Name ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (?P<season_num>\d+)x # 1x (?P<ep_num>\d+) # 02 and separator (([. _-]*x|-)(?P<extra_ep_num>\d+))* # additional x03/etc [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('scene_date_format', # Show.Name.2010.11.23.Source.Quality.Etc-Group # Show Name - 2010-11-23 - Ep Name ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (?P<air_year>\d{4})[. _-]+ # 2010 and separator (?P<air_month>\d{2})[. _-]+ # 11 and separator (?P<air_day>\d{2}) # 23 and separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group '''), ('stupid', # tpz-abc102 ''' (?P<release_group>.+?)-\w+?[\. ]? # tpz-abc (?P<season_num>\d{1,2}) # 1 (?P<ep_num>\d{2})$ # 02 '''), ('bare', # Show.Name.102.Source.Quality.Etc-Group ''' ^(?P<series_name>.+?)[. _-]+ # Show_Name and separator (?P<season_num>\d{1,2}) # 1 (?P<ep_num>\d{2}) # 02 and separator ([. _-]+(?P<extra_info>(?!\d{3}[. _-]+)[^-]+) # Source_Quality_Etc- (-(?P<release_group>.+))?)?$ # Group '''), ('verbose', # Show Name Season 1 Episode 2 Ep Name ''' ^(?P<series_name>.+?)[. _-]+ # Show Name and separator season[. _-]+ # season and separator (?P<season_num>\d+)[. _-]+ # 1 episode[. _-]+ # episode and separator (?P<ep_num>\d+)[. _-]+ # 02 and separator (?P<extra_info>.+)$ # Source_Quality_Etc- '''), ('season_only', # Show.Name.S01.Source.Quality.Etc-Group ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator s(eason[. _-])? # S01/Season 01 (?P<season_num>\d+)[. _-]* # S01 and optional separator [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group ''' ), ('no_season_general', # Show.Name.E23.Test # Show.Name.Part.3.Source.Quality.Etc-Group # Show.Name.Part.1.and.Part.2.Blah-Group # Show Name Episode 3 and 4 ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (e(p(isode)?)?|part|pt)[. _-]? # e, ep, episode, or part (?P<ep_num>(\d+|[ivx]+)) # first ep num ([. _-]+((and|&|to)[. _-]+)? # and/&/to joiner ((e(p(isode)?)?|part|pt)[. _-]?)? # e, ep, episode, or part (?P<extra_ep_num>(\d+|[ivx]+)))* # second ep num [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group ''' ), ('no_season', # Show Name - 01 - Ep Name # 01 - Ep Name ''' ^((?P<series_name>.+?)[. _-]+)? # Show_Name and separator (?P<ep_num>\d{2}) # 02 [. _-]*((?P<extra_info>.+?) # Source_Quality_Etc- ((?<![. _-])-(?P<release_group>[^-]+))?)?$ # Group ''' ), ]
# encoding: utf-8 # Copyright 2012 California Institute of Technology. ALL RIGHTS # RESERVED. U.S. Government Sponsorship acknowledged. '''EDRN RDF — Errors and other exceptional conditions''' class RDFUpdateError(Exception): '''An abstract exception indicating a problem during RDF updates.''' def __init__(self, rdfSource, message): super(Exception, self).__init__('%s (RDF Source at "%s")' % (message, '/'.join(rdfSource.getPhysicalPath()))) class NoGeneratorError(RDFUpdateError): '''Exception indicating that an RDF source doesn't have any generator set up for it.''' def __init__(self, rdfSource): super(NoGeneratorError, self).__init__(rdfSource, 'No RDF generator configured') class NoUpdateRequired(RDFUpdateError): '''A quasi-exceptional condition that indicates no RDF update is necessary.''' def __init__(self, rdfSource): super(NoUpdateRequired, self).__init__(rdfSource, 'No change to RDF required') class MissingParameterError(RDFUpdateError): '''An error that tells that some required parameters to update RDF are not present.''' def __init__(self, rdfSource, parameter): super(MissingParameterError, self).__init__(rdfSource, 'Missing parameter: %s' % parameter) class SourceNotActive(RDFUpdateError): '''Error that tells that we cannot update a source that is not marked as active''' def __init__(self, rdfSource): super(SourceNotActive, self).__init__(rdfSource, 'Source is not active')
''' Problem 48 @author: Kevin Ji ''' def self_power_with_mod(number, mod): product = 1 for _ in range(number): product *= number product %= mod return product MOD = 10000000000 number = 0 for power in range(1, 1000 + 1): number += self_power_with_mod(power, MOD) number %= MOD print(number)
# Code for demo_03 def captureInfoCam(): GPIO.setwarnings(False) # Ignore warning for now GPIO.setmode(GPIO.BOARD) # Use physical pin numbering subprocess.call(['fswebcam -r 640x480 --no-banner /home/pi/Desktop/image.jpg', '-1'], shell=True) #Azure face_uri = "https://raspberrycp.cognitiveservices.azure.com/vision/v1.0/analyze?visualFeatures=Faces&language=en" pathToFileInDisk = r'/home/pi/Desktop/image.jpg' with open( pathToFileInDisk, 'rb' ) as f: data = f.read() headers = { "Content-Type": "application/octet-stream" ,'Ocp-Apim-Subscription-Key': '7e9cfbb244204fb994babd6111235269'} try: response = requests.post(face_uri, headers=headers, data=data) faces = response.json() #pprint(faces) age = faces['faces'][0].get('age') gender = faces['faces'][0].get('gender') datosUsuario = [age, gender] except requests.exceptions.ConnectionError: return None except IndexError: return None else: return datosUsuario
wagons = int(input()) wagons_list = [0 for _ in range(wagons)] command = input().split() while "End" not in command: if "add" in command: wagons_list[-1] += int(command[1]) elif "insert" in command: wagons_list[int(command[1])] += int(command[2]) elif "leave" in command: wagons_list[int(command[1])] -= int(command[2]) command = input().split() print(wagons_list)
# Copyright (C) 2019-2020 Petr Pavlu <[email protected]> # SPDX-License-Identifier: MIT """StorePass exceptions.""" class StorePassException(Exception): """Base StorePass exception.""" class ModelException(StorePassException): """Exception when working with a model.""" class StorageException(StorePassException): """Base storage exception.""" class StorageReadException(StorageException): """Error reading a password database.""" class StorageWriteException(StorageException): """Error writing a password database."""
#Exercício Python 48: Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500. soma = 0 cont = 0 for n in range(1, 501, 2): if n % 3 == 0: soma = soma + n cont = cont + 1 print('A soma de todos os {} valores ímpares divíveis e por 3 entre 0 e 500 é {}'.format(cont, soma))
class Solution(object): def average(self, salary): """ :type salary: List[int] :rtype: float """ # Runtime: 24 ms # Memory: 13.4 MB # In Python 2, you need to convert the divisor/dividend into float in order to get a float answer return (sum(salary) - min(salary) - max(salary)) / float(len(salary) - 2)
# -------------- ##File path for the file file_path def read_file(path): file = open(file_path, 'r') sentence = file.readline() file.close() return sentence sample_message = read_file(file_path) # -------------- #Code starts here #Function to fuse message def fuse_msg(message_a,message_b): #Integer division of two numbers quot=(int(message_b)//int(message_a)) #Returning the quotient in string format return str(quot) #Calling the function to read file message_1=read_file(file_path_1) print(message_1) #Calling the function to read file message_2=read_file(file_path_2) print(message_2) #Calling the function 'fuse_msg' secret_msg_1=fuse_msg(message_1,message_2) #Printing the secret message print(secret_msg_1) #Code ends here with open(file_path, "rb") as fp: print(fp.read()) with open(file_path_1, "rb") as fp: print(fp.read()) with open(file_path_2, "rb") as fp: print(fp.read()) # -------------- #Code starts here #Code starts here message_3 = read_file(file_path_3) print(message_3) def substitute_msg(message_c): if(message_c == 'Red'): sub = 'Army General' elif(message_c == 'Green'): sub = 'Data Scientist' elif(message_c == 'Blue'): sub = 'Marine Biologist' return sub secret_msg_2 = substitute_msg(message_3) print(secret_msg_2) # -------------- # File path for message 4 and message 5 file_path_4 file_path_5 message_4 = read_file(file_path_4) message_5 = read_file(file_path_5) def compare_msg(message_d, message_e): a_list = message_d.split() b_list = message_e.split() c_list = [i for i in a_list if i not in b_list] final_msg = " ".join(c_list) return(final_msg) secret_msg_3 = compare_msg(message_4, message_5) print(secret_msg_3) # -------------- #Code starts here file_path_6 message_6 = read_file(file_path_6) print(message_6) def extract_msg(message_f): a_list = message_f.split() even_word = lambda x: len(x)%2==0 b_list = filter(even_word, a_list) final_msg = " ".join(b_list) return final_msg secret_msg_4 = extract_msg(message_6) print(secret_msg_4) # -------------- message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2] final_path= user_data_dir + 'secret_msg.txt' secret_msg = " ".join(message_parts) print(user_data_dir) def write_file(secret_msg, path): f = open(path, 'a+') f.write(secret_msg) f.close() write_file(secret_msg, final_path) print(secret_msg)
class Solution: def partitionLabels(self, string): """O(N) time | O(1) space""" chars = {} for i, char in enumerate(string): if char in chars: chars[char][1] = i else: chars[char] = [i, i] partitions = [] i = prev = 0 while i < len(string): char = string[i] i = chars[char][1] while char: for c, pos in chars.items(): if pos[0] <= i and pos[1] > i: i = pos[1] else: char = None partitions.append(i - prev + 1) i += 1 prev = i return partitions # Even better, idea from: # https://leetcode.com/problems/partition-labels/discuss/298474/Python-two-pointer-solution-with-explanation class Solution: def partitionLabels(self, string): """O(N) time | O(1) space""" chars = {c:i for i,c in enumerate(string)} left = right = 0 partitions = [] for i, char in enumerate(string): right = max(right, chars[char]) if i == right: partitions.append(right - left + 1) left = right + 1 return partitions
# 3.uzdevums my_name = str(input('Enter sentence ')) words = my_name.split() rev_list = [word[::-1] for word in words] rev_string=" ".join(rev_list) result=rev_string.capitalize() print(result) print(" ".join([w[::-1] for w in my_name.split()]).capitalize())
# def math(num1, num2, operation='add'): # if(operation == "mult"): # return num1 * num2 # if(operation == "div"): # return num1 / num2 # if(operation == "sub"): # return num1 - num2 # if(operation == "add"): # return num1 + num2 # else: # print("not a valid opreation") # num1 = int(input("input number1:")) # num2 = int(input("input number2:")) # operation = input("write the opreation :add,sub,mult,div:") # val = math(num1, num2, operation) # print(val) # num1 and num2 are parameters # def add(num1, num2): # return num1 + num2 # 100 and 20 are arguments # x = add(100, 20) # print(x) def multiply(num1, num2): return num1 * num2 y = multiply(10, 20) print(y)
""" Control Flow II - SOLUTION """ # Write a Python program that prints all the numbers from 0 to 6 except 3 and 6. Note : Use 'continue' statement. for i in range(6): if (i == 3 or i ==6): continue print(i,end=' ') print("\n")
""" Euclidean algorithm (greatest common divisor (GCD)) """ def euclidean(a, b): while a != 0 and b != 0: if a > b: a = a % b else: b = b % a gcd = a or b return gcd def test_euclidean(): """ Tests """ assert(euclidean(30, 18) == 6) assert(euclidean(10, 10) == 10) assert(euclidean(0, 0) == 0) if __name__ == '__main__': print('GCD for 30 and 18 is ', euclidean(30, 18))
tamanho = int(input('Informe o tamanho do arquivo em MB ')) velocidade = int(input('informe a velocidade em Mbps ')) tempo = tamanho/velocidade tempo = tempo/60 if tempo < 1: print('Levará menos de 1 minuto ') else: print('Levará aproximadamente %d minutos' %(int(tempo)))
""" Classe: Classes devem comecar com a Letra Maiuscula (camel case : ExemploPessoa) É a base da OO. É a fôrma (fôrma de gelo) que define como nossos objetos se comportam. As vezes é utilizado como sinonimo de "tipo". Funcao: Funcoes devem comecar com a letra minuscula (snake_case : exemplo_pessoa) def: (Metodo) É o 1º atributo das Classes É uma funcao que pertence a uma classe. Sempre conectada a um objeto. Deve sempre declarar o 1º parametro que será o objeto a ser recebido ("self" ou qualquer outro nome, mas no Python usam a palavra "self") """ class Pessoa: """ "olhos = 2" é um "atributo default" ou "Atributo de Classe". É criado fora do "__init__" pois este atributo nao varia, independente da "pessoa". Criado fora ele ocupa menos memória. """ # atributos comuns a todos da "classe Pessoa" sao criados fora da "def" para economizar memoria # Sao chamados "atributos default" ou "atributos de classe" olhos = 2 def __init__(self, *filhos, nome=None, idade=35): # "__init__" é um 'construtor' e ele permite criar a funcionalidade inicial que sua classe terá !!! self.idade = idade self.nome = nome self.filhos = list(filhos) # "self.nome" é # "nome" é # "self" pode ser qualquer palavra, mas em Python sempre usamos a palavra "self" como parametro. def cumprimentar(self): return f"Olá {id(self)}" # DECORATOR é um metodo que independe de qual objeto está sendo executado. # Assim nao precisa receber nenhum atributo "()" na funcao. # Comeca com "@" e fica acima de "funcoes" e "métodos". @staticmethod def metodo_estatico(): return 42 # Tambem é um DECORATOR # Mas aqui é passado um atributo de nome padronizado "cls" # Usado qdo quer acessar dados da propria classe. @classmethod def nome_e_atributos_de_classes(cls): return f"{cls} - olhos {cls.olhos}" class Homem(Pessoa): def cumprimentar(self): cumprimentar_da_classe = super().cumprimentar() return f"{cumprimentar_da_classe}. Aperto de mao" if __name__ == "__main__": # sandro = Pessoa('Ordnas') """O objeto complexo 'sandro' é do tipo 'Pessoa'""" sandro = Pessoa(nome="Sandro") """O objeto complexo 'sandro' é passado como um atributo para o objeto 'enoque' """ enoque = Pessoa(sandro, nome="Enoque") """Abaixo nao é a forma usual de se executar um método ("def").""" print( Pessoa.cumprimentar(enoque) ) # Esta nao é a forma usual de se executar um método ("def"). """A forma usual é: Ao chamar um "metodo" a partir do "objeto", nao precisa passá-lo como 1º parametro, o Python passa o objeto "p" como 1º parametro implicitamente!!! """ print( enoque.cumprimentar() ) # Ao chamar um "metodo" a partir do "objeto", nao precisa passá-lo # como 1º parametro, o Python passa o objeto "p" como 1º parametro implicitamente!!! print(id(enoque)) # Checando o "id" # print(sandro.nome) # sandro.nome = 'Sandro' print("Nome do Pai:\n\t", enoque.nome) print("Idade do Pai:\n\t", enoque.idade) # print(enoque.filhos) for filho in enoque.filhos: print("Imprimindo os filhos de Enoque:\n\t", filho.nome) """Um atributo especial '__dict__' usado para checar todos os atributos de instancia (todoa aqueles criados no '__init__' quanto aqueles criatos dinamicamente""" print("\t", enoque.__dict__) print("\t", sandro.__dict__) """ Criacao do 'atributo dinamico' 'sobrenome'""" enoque.sobrenome = "Passos" """ Deletando o 'atributo dinamico' 'filhos'""" del enoque.filhos """ Inserindo o atributo "olhos" em "enoque" ele passa a fazer parte do "__dict__" do objeto "enoque" e o "__dict__" do objeto "sandro" nao foi comprometido """ enoque.olhos = 1 print( 'Criado "atrib dinam" "sobrenome", retirado o "atrib dinam" "filhos" em "enoque":\n\t', enoque.__dict__, ) print("\t", sandro.__dict__) print("Numero de olhos da Pessoa:\n\t", Pessoa.olhos) print("Numero de olhos de Sandro:\n\t", sandro.olhos) print("Numero de olhos de Enoque:\n\t", enoque.olhos) print( 'Verificando que o id deste atributo "olhos" é o mesmo acessando da sua classe ou da \ninstancia de ' '"Pessoa", exceto o atributo do objeto "enoque":\n\t', id(Pessoa.olhos), id(sandro.olhos), id(enoque.olhos), ) """Após deletar o atributo do objeto "enoque" e nao da classe "Pessoa" todos passarao a ter o mesmo "id".""" del enoque.olhos print( 'Após deletar o atributo do objeto "enoque" e nao da classe "Pessoa" todos passarao a ter o ' 'mesmo "id":\n\t', id(Pessoa.olhos), id(sandro.olhos), id(enoque.olhos), ) print(Pessoa.metodo_estatico(), sandro.metodo_estatico()) print(Pessoa.nome_e_atributos_de_classes(), sandro.nome_e_atributos_de_classes()) """ Atributos de Instância: Criados normalmente dentro do método "__init__" Atributos Dinâmicos: Criados através da atribuição e removidos atraves da palavra reservada "del". Atributos de Classe: ou "Atributo Default", é criado fora do "__init__", pois nao vai variar independente da "Classe" e assim ocupa menos espaço na memória (é o mesmo para todos os objetos). """
def binary_search(arr, target): low, high = 0, len(arr)-1 while low < high: mid = (low + high)/2 if arr[mid] == target: return mid elif arr[mid] > target: high = mid - 1 else: low = mid + 1 try: if arr[high] == target: return high else: return -1 except IndexError as e: return -1
MOD_ID = 'id' MOD_RGB = 'rgb' MOD_SS_DENSE = 'semseg_dense' MOD_SS_CLICKS = 'semseg_clicks' MOD_SS_SCRIBBLES = 'semseg_scribbles' MOD_VALIDITY = 'validity_mask' SPLIT_TRAIN = 'train' SPLIT_VALID = 'val' MODE_INTERP = { MOD_ID: None, MOD_RGB: 'bilinear', MOD_SS_DENSE: 'nearest', MOD_SS_CLICKS: 'sparse', MOD_SS_SCRIBBLES: 'sparse', MOD_VALIDITY: 'nearest', }
nmbr = 3 if nmbr % 2 == 0: print("%d is even" % nmbr) elif nmbr == 0: print("%d is zero" % nmbr) else: print("%d is odd" % nmbr) free = "free"; print("I am free") if free == "free" else print("I am not free") # Nested Conditions nmbr = 4 if nmbr % 2 == 0: if nmbr % 4 == 0: print("I can pass all the condititions!") if nmbr > 0 and nmbr % 1 == 0: print("Vow I can pass here too!")
class Book: """ Model for Book object """ def __init__(self, title, author): self.title = title self.author = author self.bookmark = None self.read = False def setBookmark(self, page): """ Sets bookmark attribute of a book to given page """ self.bookmark = page def read(self): """ Changes read status of a book """ self.read = True
class Node: def __init__(self, key): self.left = None self.right = None self.val = key def insert(root, key): if root is None: return Node(key) else: if root.val == key: return root elif root.val < key: root.right = insert(root.right, key) else: root.left = insert(root.left, key) return root def inorder(root): if root: inorder(root.left) print(root.val) inorder(root.right) if __name__ == "__main__": """ from timeit import timeit r = Node(50) r = insert(r, 30) r = insert(r, 20) r = insert(r, 40) r = insert(r, 70) r = insert(r, 60) r = insert(r, 80) print(timeit(lambda: inorder(r), number=10000)) # 0.4426064440012851 """
#!/usr/bin/python3 """ Part of speech tagging in python using Hidden Markov Model. POS tagging using Hidden Markov model (Viterbi algorithm) """ __author__ = "Sunil" __copyright__ = "Copyright (c) 2017 Sunil" __license__ = "MIT License" __email__ = "[email protected]" __version__ = "0.1" class PennTreebank(object): """ Dictionary of all tags in the Penn tree bank. Can be used to look up penn tree bank codeword to human understandable Parts of speech """ tagset = defaultdict ( lambda: '#unknown#', { "CC" : "Coordinating conjunction", "CD" : "Cardinal number", "DT" : "Determiner", "EX" : "Existential there", "FW" : "Foreign word", "IN" : "Preposition or subordinating conjunction", "JJ" : "Adjective", "JJR" : "Adjective, comparative", "JJS" : "Adjective, superlative", "LS" : "List item marker", "MD" : "Modal", "NN" : "Noun, singular or mass", "NNS" : "Noun, plural", "NNP" : "Proper noun, singular", "NNPS" : "Proper noun, plural", "PDT" : "Predeterminer", "POS" : "Possessive ending", "PRP" : "Personal pronoun", "PRP$" : "Possessive pronoun", "RB" : "Adverb", "RBR" : "Adverb, comparative", "RBS" : "Adverb, superlative", "RP" : "Particle", "SYM" : "Symbol", "TO" : "to", "UH" : "Interjection", "VB" : "Verb, base form", "VBD" : "Verb, past tense", "VBG" : "Verb, gerund or present participle", "VBN" : "Verb, past participle", "VBP" : "Verb, non-3rd person singular present", "VBZ" : "Verb, 3rd person singular present", "WDT" : "Wh-determiner", "WP" : "Wh-pronoun", "WP$" : "Possessive wh-pronoun", "WRB" : "Wh-adverb" } ) @classmethod def lookup(cls, codedTag): """ look up coded tag and return human understanable POS. No exception hanlding required because of defaultdict """ return cls.tagset[codedTag]
DEBUG = True SECRET_KEY = 'topsecret' #SQLALCHEMY_DATABASE_URI = 'postgresql://yazhu:root@localhost/matcha' # SQLALCHEMY_DATABASE_URI = 'postgresql://jchung:@localhost/matcha' SQLALCHEMY_DATABASE_URI = 'postgresql://root:1234@localhost/matcha' SQLALCHEMY_TRACK_MODIFICATIONS = False ACCOUNT_ACTIVATION = False ROOT_URL = 'localhost:5000' REDIRECT_HTTP = False
"""Defines a node for link-based data structures""" class Node: """A node in the linked list""" def __init__(self, next=None, data=None): self.next = next self.data = data def __eq__(self, other): return self.data == other.data def __repr__(self): return repr(self.data)
# abrir y leer archivo f = open ('input.txt','r') mensaje = f.read() f.close() map_squares_trees = mensaje.split('\n') # print(map_squares_trees) # cantidad de elementos (square or tree) por cada fila lenght_of_one_line = len(map_squares_trees[0]) pos_columna = 3 pos_linea = 0 iteraciones = 0 tree = 0 # con [1:] ignoro el primer elemento de la lista for i in map_squares_trees[1:]: # ahora busco que todas las columnas no sean mayores de 11, # para ello siempre hago el modulo sobre 11 de las posiciones # de la columna, así si al sumar 3 casillas sale 12, se refiere a # que es la posición 1 de la siguiente fila # recordar que empiezo a contar desde 0 las filas pos_columna = pos_columna % (lenght_of_one_line) if(i[pos_columna]=="#"): tree = tree + 1 pos_columna = pos_columna + 3 iteraciones = iteraciones + 1 print(tree)
PURCHASE_NO_CLIENT_STATE = 0 PURCHASE_WAITING_STATE = 1 PURCHASE_PLAYAGAIN_STATE = 2 PURCHASE_EXIT_STATE = 3 PURCHASE_DISCONNECTED_STATE = 4 PURCHASE_UNREPORTED_STATE = 10 PURCHASE_REPORTED_STATE = 11 PURCHASE_CANTREPORT_STATE = 12 PURCHASE_COUNTDOWN_TIME = 120
# 14. Write a program in Python to calculate the volume of a sphere rad=int(input("Enter radius of the sphere: ")) vol=(4/3)*3.14*(rad**3) print("Volume of the sphere= ",vol)
''' Created on Aug 10, 2017 @author: Itai Agmon ''' class ReportElementType(): REGULAR = "regular" LINK = "lnk" IMAGE = "img" HTML = "html" STEP = "step" START_LEVEL = "startLevel" STOP_LEVEL = "stopLevel" class ReportElementStatus(): SUCCESS = "success" WARNING = "warning" FAILURE = "failure" ERROR = "error" class ReportElement(object): def __init__(self): self.parent = None self.title = "" self.message = "" self.status = ReportElementStatus.SUCCESS self.time = "" self.element_type = ReportElementType.REGULAR def set_status(self, status): if status != ReportElementStatus.ERROR and \ status != ReportElementStatus.FAILURE and \ status != ReportElementStatus.WARNING and \ status != ReportElementStatus.SUCCESS: raise ValueError("Illegal status %s" % status) if status == ReportElementStatus.ERROR: self.status = status elif status == ReportElementStatus.FAILURE: if self.status != ReportElementStatus.ERROR: self.status = status elif status == ReportElementStatus.WARNING: if self.status != ReportElementStatus.ERROR and self.status != ReportElementStatus.FAILURE: self.status = status def set_type(self, element_type): if element_type != ReportElementType.REGULAR and \ element_type != ReportElementType.LINK and \ element_type != ReportElementType.IMAGE and \ element_type != ReportElementType.HTML and \ element_type != ReportElementType.STEP and \ element_type != ReportElementType.START_LEVEL and \ element_type != ReportElementType.STOP_LEVEL: raise ValueError("Illegal element type %s" % element_type) self.element_type = element_type def dict(self): d = {} d["title"] = self.title d["message"] = self.message d["status"] = self.status d["time"] = self.time d["status"] = str(self.status) d["type"] = str(self.element_type) return d class TestDetails(object): def __init__(self, uid): self.uid = uid self.report_elements = [] self.level_elements_stack = [] self.execution_properties = {} def add_element(self, element): if type(element) is not ReportElement: raise TypeError("Can only add report elements") element.parent = self if element.element_type is None: element.element_type = ReportElementType.REGULAR self.report_elements.append(element) if element.element_type == ReportElementType.START_LEVEL: self.level_elements_stack.append(element) elif element.element_type == ReportElementType.STOP_LEVEL: self.level_elements_stack.pop() if element.status != ReportElementStatus.SUCCESS: for e in self.level_elements_stack: e.set_status(element.status) def dict(self): d = {} d["uid"] = self.uid d["reportElements"] = [] for element in self.report_elements: d["reportElements"].append(element.dict()) return d
{ "targets": [ { "target_name": "strings", "sources": ["main.cpp"], "cflags": ["-Wall", "-Wextra", "-ansi", "-O3"], "include_dirs" : ["<!(node -e \"require('nan')\")"] } ] }
# @Title: 图片平滑器 (Image Smoother) # @Author: KivenC # @Date: 2018-07-14 14:09:11 # @Runtime: 600 ms # @Memory: N/A class Solution(object): def imageSmoother(self, M): """ :type M: List[List[int]] :rtype: List[List[int]] """ R, C = len(M), len(M[0]) res = [[0 for _ in range(C)] for _ in range(R)] for r in range(R): for c in range(C): count = 0 for i in (r-1, r, r+1): for j in (c-1, c, c+1): if i >= 0 and i < R and j >= 0 and j < C: count += 1 res[r][c] += M[i][j] res[r][c] //= count return res
class Solution: def groupAnagrams(self, strs: List[str]) -> List[List[str]]: anagrams = {} for str in strs: key = ''.join(sorted(str)) if key not in anagrams: anagrams[key] = [] anagrams[key].append(str) return list(anagrams.values())
class Car: # Class-level wheels = 4 def __init__(self, manufacturer: str, model: str, color: str, mileage: int): # Instance-level self.manufacturer = manufacturer self.model = model self.color = color self.mileage = mileage # Method def add_mileage(self, miles: int) -> str: self.mileage += miles print(f"The car has {miles} miles on it.") my_car = Car("Audi", "R8", "Blue", 1000) print(f"I just bought a {my_car.color} {my_car.manufacturer} {my_car.model}") print(f"My new car's mileage is {my_car.mileage}") print("Adding 500 miles to my car...") my_car.add_mileage(500) print(f"My new car's mileage is {my_car.mileage}")
def gcd(a, b): while b != 0: a, b = b, a % b return a def lcm(a, b, g): return a * b // g A, B = (int(term) for term in input().split()) g = gcd(A, B) print(g) print(lcm(A, B, g))
def solution(a, b): answer = 0 for x,y in zip(a,b): answer+=x*y return answer
AVAILABLE_OPTIONS = [('doc_m2m_prob_threshold', 'Probability threshold for showing document to mass2motif links'), ('doc_m2m_overlap_threshold', 'Threshold on overlap score for showing document to mass2motif links'), ('log_peakset_intensities', 'Whether or not to log the peakset intensities (true,false)'), # ('peakset_matching_tolerance', 'Tolerance to use when matching peaksets'), ('heatmap_minimum_display_count', 'Minimum number of instances in a peakset to display it in the heatmap'), # ('default_doc_m2m_score', # 'Default score to use when extracting document <-> mass2motif matches. Use either "probability" or "overlap_score", or "both"'), ('heatmap_normalisation','how to normalise the rows in the heatmap: none, standard, max')]
phi, d, t, coll = input().split() phi = float(phi) phi_1 = phi - 0.01 phi_2 = phi + 0.01 print(str(phi) + " " + "0.00001" + " " + "0.1 " + str(t) + " 10 20")
n = int(input()) len_n = len(str(n)) # n의 자릿수 파악( ex 123 : 3자릿수) sum = 0 for i in range(len_n-1): sum += 9 * (10 ** i) * (i+1) # ex)3자릿수라면(123) 두자릿수까지의 경우의수 계산 nums = n - (10 ** (len_n-1)) + 1 # ex) 3자리수라면 n - 100 +1 을 통해 100~n 사이의 개수 구하기 sum += nums * len_n # ex) 3자릿수 개수 * 3 -> 세자릿수 숫자들의 길이 print(sum)
class usuario(object): def __init__(self, nombre, apellido, edad, genero): self.nombre = nombre self.apellido = apellido self.edad = edad self.genero = genero def descripcion_usuario(self): print("Nombre: " + self.nombre.title() + "\nApellido: " + self.apellido.title() + "\nEdad: " + str(self.edad) + "\nGenero: " + self.genero) def greet_usuario(self): print("Bienvenido: " + self.nombre.title() + " " + self.apellido.title()) class privilegios(object): def __init__(self): self.privilegios = [] def obtener_privilegios(self, *list_privilegios): self.privilegios = list_privilegios def imprime_privilegios(self): print("Los Privilegios del Admin son: ") for priv in self.privilegios: print("- " + priv) class admin(usuario): def __init__(self, nombre, apellido, edad, genero): super(admin, self).__init__(nombre, apellido, edad, genero) self.privilegios = privilegios() administrador_n = admin('Rosa', 'Sanchez', 18, 'F') print(administrador_n.descripcion_usuario()) administrador_n.privilegios.obtener_privilegios('Puede Agregar Publicaciones', 'Puede Eliminar Publicaciones') administrador_n.privilegios.imprime_privilegios()
# Ley d'Hondt def hondt(votes, n): """ Ley d'Hondt; coefficient: c_i = V_i / (s_i + 1) V_i = total number of votes obtained by party i s_i = number of seats assigned to party i (initially 0) """ s = [0] * len(votes) for i in range(n): c = [v[j] / (s[j] + 1) for j in range(len(s))] s[c.index(max(c))] += 1 return s # Example v = [340000, 280000, 160000, 60000, 15000] # votes for each party n = 155 # number of seats print(hondt(v, n))
class Class1(object): def __init__(self): pass def test1(self): return 5 class Class2(object): def test1(self): return 6 class Class3(object): def test1(self, x): return self.test2(x)-1 def test2(self, x): return 2*x a = Class1() print(a.test1()) a = Class2() print(a.test1()) a = Class3() print(a.test1(3)) print(a.test2(3))
n = str(input('Digite seu nome completo:')).strip() nome = n.split() print ('É um prezer te conhecer!') print ('seu primeiro nome é {}'.format(nome[0])) print ('Seu último nome é {}'.format(nome[len(nome)-1]))
# -*- coding: utf-8 -*- """ sphinxpapyrus ~~~~~~~~~~~~~ Sphinx extensions. :copyright: Copyright 2018 by nakandev. :license: MIT, see LICENSE for details. """ __import__('pkg_resources').declare_namespace(__name__)
class Tee: def __init__(self, f, f_tee): self.f = f self.f_tee = f_tee def read(self, nbytes): buf = self.f.read(nbytes) self.f_tee.write(buf) return buf def write(self, buf): self.f_tee.write(buf) self.f.write(buf) def flush(self): self.f.flush()
''' This is all the calculation for the main window '''
__title__ = 'lottus' __description__ = 'An ussd library that will save you time' __version__ = '0.0.4' __author__ = 'Benjamim Chambule' __author_email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2021 Benjamim Chambule'
extra_annotations = \ { 'ai': [ 'artificial intelligence', 'machine learning', 'statistical learning', 'statistical model', 'supervised model', 'unsupervised model', 'computer vision', 'image analysis', 'object recognistion', 'object detection', 'image segmentation', 'deep learning', 'cognitive computing', 'neural network', 'classification model', 'regression model', 'classifier', 'reinforcment learning' ], 'tech': [ 'digital health', 'ehealth', 'digital medicine', 'mhealth', 'digital healthcare', 'digital biomarker', 'telemedicine' ], 'medicine': [ 'health occupations', 'health occupation', 'health professions', 'health profession', 'profession, health', 'professions, health', 'health occup', 'medicine', 'medical specialities', 'medical speciality', 'speciality, medical', 'specialities, medical', 'specialties, medical', 'medical specialty', 'specialty, medical', 'medical specialties', 'med specialties', 'med specialty', 'specialty med', 'specialties med', 'med specialities', 'specialities med', 'addiction psychiatry', 'psychiatry, addiction', 'addiction medicine', 'medicine, addiction', 'adolescent medicine', 'medicine, adolescent', 'hebiatrics', 'ephebiatrics', 'med adolescent', 'adolescent med', 'aerospace medicine', 'medicine, aerospace', 'med aerospace', 'aerospace med', 'aviation medicine', 'medicine, aviation', 'med aviation', 'aviation med', 'medicine, space', 'space medicine', 'med space', 'space med', 'allergy specialty', 'specialty, allergy', 'allergy and immunology', 'allergy, immunology', 'immunology, allergy', 'allergy immunology', 'immunology allergy', 'immunology and allergy', 'allergy immunol', 'immunol allergy', 'immunology', 'immunol', 'immunochemistry', 'immunochem', 'anesthesiology', 'anesthesiol', 'bariatric medicine', 'medicine, bariatric', 'behavioral medicine', 'medicine, behavioral', 'med behavioral', 'behavioral med', 'health psychology', 'health psychologies', 'psychologies, health', 'psychology, health', 'health psychol', 'psychol health', 'clinical medicine', 'medicine, clinical', 'clin med', 'med clin', 'evidence-based medicine', 'evidence based medicine', 'medicine, evidence based', 'medicine, evidence-based', 'evidence based med', 'med evidence based', 'precision medicine', 'medicine, precision', 'p health', 'p-health', 'p-healths', 'personalized medicine', 'medicine, personalized', 'individualized medicine', 'medicine, individualized', 'community medicine', 'medicine, community', 'med community', 'community med', 'dermatology', 'dermatol', 'disaster medicine', 'medicine, disaster', 'emergency medicine', 'medicine, emergency', 'med emergency', 'emergency med', 'emergency medicine, pediatric', 'medicine, pediatric emergency', 'pediatric emergency medicine', 'forensic medicine', 'medicine, forensic', 'med forensic', 'forensic med', 'medicine, legal', 'legal medicine', 'legal med', 'med legal', 'forensic genetics', 'genetics, forensic', 'genetic, forensic', 'forensic genetic', 'forensic pathology', 'pathology, forensic', 'forensic pathol', 'pathol forensic', 'general practice', 'practice, general', 'family practice', 'family practices', 'practices, family', 'practice, family', 'genetics, medical', 'medical genetics', 'med genet', 'genet med', 'geography, medical', 'medical geography', 'geomedicine', 'nosogeography', 'geogr med', 'med geogr', 'topography, medical', 'medical topography', 'med topogr', 'topogr med', 'geriatrics', 'gerontology', 'gerontol', 'international health problems', 'health problem, international', 'international health problem', 'problem, international health', 'health problems, international', 'problems, international health', 'world health', 'health, world', 'worldwide health', 'health, worldwide', 'healths, international', 'international healths', 'international health', 'health, international', 'global health', 'health, global', 'hospital medicine', 'medicine, hospital', 'integrative medicine', 'medicine, integrative', 'internal medicine', 'medicine, internal', 'internal med', 'med internal', 'cardiology', 'cardiol', 'vascular medicine', 'medicine, vascular', 'angiology', 'cardiovascular disease specialty', 'disease specialty, cardiovascular', 'specialty, cardiovascular disease', 'endocrinology', 'endocrinol', 'endocrinology and metabolism specialty', 'metabolism and endocrinology specialty', 'gastroenterology', 'gastroenterol', 'hepatology', 'hepatol', 'hematology', 'hematol', 'infectious disease medicine', 'disease medicine, infectious', 'medicine, infectious disease', 'infectious diseases specialty', 'infectious disease specialties', 'infectious disease specialty', 'infectious diseases specialties', 'specialties, infectious diseases', 'specialties, infectious disease', 'specialty, infectious disease', 'diseases specialty, infectious', 'specialty, infectious diseases', 'medical oncology', 'oncology, medical', 'med oncol', 'oncol med', 'clinical oncology', 'oncology, clinical', 'nephrology', 'nephrol', 'pulmonary medicine', 'medicine, pulmonary', 'pneumology', 'pneumonology', 'pulmonology', 'med pulm', 'pulm med', 'pneumonol', 'pneumol', 'pulmonol', 'respiratory medicine', 'medicine, respiratory', 'rheumatology', 'rheumatol', 'sleep medicine specialty', 'medicine specialties, sleep', 'sleep medicine specialties', 'specialties, sleep medicine', 'medicine specialty, sleep', 'specialty, sleep medicine', 'military medicine', 'medicine, military', 'med military', 'military med', 'molecular medicine', 'medicines, molecular', 'molecular medicines', 'medicine, molecular', 'naval medicine', 'medicine, naval', 'nautical medicine', 'medicine, nautical', 'med nautical', 'nautical med', 'med naval', 'naval med', 'submarine medicine', 'medicine, submarine', 'med submarine', 'submarine med', 'neurology', 'neurol', 'neuropathologist', 'neuropathologists', 'neuropathology', 'neuropathologies', 'neurotology', 'neuro-otology', 'neuro otology', 'otoneurology', 'osteopathic medicine', 'medicine, osteopathic', 'med osteopathic', 'osteopathic med', 'osteopathic manipulative medicine', 'manipulative medicine, osteopathic', 'medicine, osteopathic manipulative', 'palliative medicine', 'medicine, palliative', 'palliative care medicine', 'medicine, palliative care', 'med palliative', 'palliative med', 'pathology', 'pathologies', 'pathol', 'forensic pathology', 'pathology, forensic', 'forensic pathol', 'pathol forensic', 'neuropathologist', 'neuropathologists', 'neuropathology', 'neuropathologies', 'pathology, clinical', 'clinical pathology', 'clin pathol', 'pathol clin', 'pathology, molecular', 'molecular pathologies', 'pathologies, molecular', 'molecular pathology', 'molecular diagnostics', 'diagnostic, molecular', 'molecular diagnostic', 'diagnostics, molecular', 'diagnostic molecular pathology', 'diagnostic molecular pathologies', 'molecular pathologies, diagnostic', 'pathologies, diagnostic molecular', 'molecular pathology, diagnostic', 'pathology, diagnostic molecular', 'pathology, surgical', 'surgical pathology', 'pathol surg', 'surg pathol', 'telepathology', 'telepathol', 'pediatrics', 'neonatology', 'neonatol', 'emergency medicine, pediatric', 'medicine, pediatric emergency', 'pediatric emergency medicine', 'perinatology', 'perinatol', 'perioperative medicine', 'medicine, perioperative', 'physical and rehabilitation medicine', 'physical medicine and rehabilitation', 'physical medicine', 'medicine, physical', 'physiatry', 'physiatrics', 'med physical', 'physical med', 'habilitation', 'rehabilitation', 'rehabil', 'psychiatrist', 'psychiatrists', 'psychiatry', 'adolescent psychiatry', 'psychiatry, adolescent', 'biological psychiatry', 'psychiatry, biological', 'biologic psychiatry', 'psychiatry, biologic', 'psychiatry biol', 'biol psychiatry', 'child psychiatry', 'psychiatry, child', 'community psychiatry', 'psychiatry, community', 'social psychiatry', 'psychiatry, social', 'forensic psychiatry', 'psychiatry, forensic', 'jurisprudence, psychiatric', 'psychiatric jurisprudence', 'geriatric psychiatry', 'psychiatry, geriatric', 'psychogeriatrics', 'military psychiatry', 'psychiatry, military', 'neuropsychiatry', 'environment, preventive medicine and public health', 'environment, preventive medicine & public health', 'envir prev med public health', 'public health', 'health, public', 'community health', 'health, community', 'epidemiology', 'epidemiol', 'preventive medicine', 'medicine, preventive', 'preventative medicine', 'medicine, preventative', 'med prev', 'prev med', 'preventive care', 'care, preventive', 'preventative care', 'care, preventative', 'radiology', 'radiol', 'atomic medicine', 'medicine, atomic', 'nuclear medicine', 'medicine, nuclear', 'med atomic', 'atomic med', 'med nuclear', 'nuclear med', 'radiology, nuclear', 'nuclear radiology', 'nuclear radiol', 'radiol nuclear', 'therapeutic radiology', 'radiology, therapeutic', 'radiol ther', 'ther radiol', 'radiation oncology', 'oncology, radiation', 'oncol rad', 'rad oncol', 'radiology, interventional', 'interventional radiology', 'interventional radiol', 'radiol interventional', 'regenerative medicine', 'regenerative medicines', 'medicines, regenerative', 'medicine, regenerative', 'regenerative med', 'reproductive medicine', 'medicine, reproductive', 'med reproductive', 'reproductive med', 'andrology', 'androl', 'gynecology', 'gynecol', 'social medicine', 'medicine, social', 'med social', 'social med', 'specialties, surgical', 'surgical specialties', 'specialties surg', 'surg specialties', 'colon and rectal surgery specialty', 'surgery specialty, colon and rectal', 'colorectal surgery', 'surgery, colorectal', 'surg specialty colon rectal', 'colon rectal surg specialty', 'colorectal surg', 'surg colorectal', 'colon surgery specialty', 'specialty, colon surgery', 'surgery specialty, colon', 'specialty colon surg', 'surg specialty colon', 'colon surg specialty', 'proctology', 'rectal surgery specialty', 'specialty, rectal surgery', 'surgery specialty, rectal', 'rectal surg specialty', 'specialty rectal surg', 'surg specialty rectal', 'proctol', 'surgery', 'general surgery', 'surgery, general', 'surg', 'gynecology', 'gynecol', 'neurosurgery', 'neurosurgeries', 'neurosurg', 'obstetrics', 'ophthalmology', 'ophthalmol', 'orthognathic surgery', 'orthognathic surgeries', 'surgeries, orthognathic', 'surgery, orthognathic', 'orthopedics', 'otolaryngology', 'otorhinolaryngology', 'otolaryngol', 'otorhinolaryngol', 'otology', 'otol', 'laryngology', 'surgery, plastic', 'plastic surgery', 'plastic surg', 'surg plastic', 'surgery, cosmetic', 'cosmetic surgery', 'surg cosmetic', 'cosmetic surg', 'esthetic surgery', 'esthetic surgeries', 'surgeries, esthetic', 'surgery, esthetic', 'esthetic surg', 'surg esthetic', 'surgical oncology', 'oncology, surgical', 'thoracic surgery', 'surgery, thoracic', 'surg thoracic', 'thoracic surg', 'surgery, cardiac', 'cardiac surgery', 'heart surgery', 'surgery, heart', 'surg cardiac', 'cardiac surg', 'surg heart', 'heart surg', 'traumatology', 'traumatol', 'surgical traumatology', 'traumatology, surgical', 'urology', 'urol', 'sports medicine', 'medicine, sport', 'sport medicine', 'medicine, sports', 'med sports', 'med sport', 'sport med', 'sports med', 'sports nutritional sciences', 'nutritional science, sports', 'science, sports nutritional', 'sports nutritional science', 'nutritional sciences, sports', 'sciences, sports nutritional', 'sports nutrition sciences', 'nutrition science, sports', 'science, sports nutrition', 'sports nutrition science', 'nutrition sciences, sports', 'sciences, sports nutrition', 'exercise nutritional sciences', 'exercise nutritional science', 'nutritional science, exercise', 'science, exercise nutritional', 'nutritional sciences, exercise', 'sciences, exercise nutritional', 'veterinary sports medicine', 'sports medicines, veterinary', 'medicine, sports veterinary', 'medicine, veterinary sports', 'sports medicine, veterinary', 'sports veterinary medicine', 'veterinary medicine, sports', 'telemedicine', 'telemed', 'telehealth', 'ehealth', 'mobile health', 'health, mobile', 'mhealth', 'telepathology', 'telepathol', 'teleradiology', 'teleradiol', 'telerehabilitation', 'remote rehabilitation', 'rehabilitations, remote', 'remote rehabilitations', 'rehabilitation, remote', 'telerehabilitations', 'virtual rehabilitation', 'rehabilitations, virtual', 'virtual rehabilitations', 'rehabilitation, virtual', 'tele-rehabilitation', 'tele rehabilitation', 'tele-rehabilitations', 'theranostic nanomedicine', 'nanomedicines, theranostic', 'theranostic nanomedicines', 'nanomedicine, theranostic', 'theranostics', 'theranostic', 'emporiatrics', 'travel medicine', 'medicine, travel', 'medicine, emporiatric', 'emporiatric medicine', 'tropical medicine', 'medicine, tropical', 'med tropical', 'tropical med', 'vaccinology', 'venereology', 'venereol', 'wilderness medicine', 'medicine, wilderness' ], }
num = int(input()) numdict = { 1: 'one', 2: 'two', 3: 'three', 4: 'four', 5: 'five', 6: 'six', 7: 'seven', 8: 'eight', 9: 'nine' } print(numdict.get(num, 'number too big'))
# -*- coding: utf-8 -*- class FormFactory(type): """This is the factory required to gather every Form components""" def __init__(cls, name, bases, dct): cls.datas={} for k,v in dct.items(): if k[0]!="_": cls.datas[k]=v return type.__init__(cls, name, bases, dct) class Form(object): def __init__(self, action="", method="post", **kw): """You have to provide the form's action, the form's method and some additional parameters. You can put any type of form's parameter expect "class" which must be written "class_" """ self.errors={} self.values={} self.action=action self.method=method self.parameters="" for k,v in kw.items(): if k=="class_": self.parameters+=' class="%s"' % (v) else: self.parameters+=' %s="%s"' % (k, v) self.submit_text="" def submit(self, buttons): """Generate self.submit_text parameters must be a list of (value, name, params). params is here a string sample: <fieldset class="submit"> <input type="submit" value="send" name="bt1"/> <input type="submit" value="cancel" name="bt1"/> <fieldset> """ res='<fieldset class="submit">' for value, name, params in buttons: res+='<input type="submit" value="%s" name="%s" %s/>' % (value, name, params) res+="</fieldset>" self.submit_text=res def render_error(self, name): """generate a list of error messages. sample: <ul class="errorlist"> <li><rong value</li> </ul> """ err="""<ul class="errorlist">""" for error in self.errors[name]: err+="<li>%s</li>" % error err+="</ul>" return "<div>%s</div>" % err def render_form(self, form_fields): """Generate the html's form with all fields provided and the self.submit_text previously generated. This is the main method to generate the form. Parameter is a list of field's names you want to see in the form. """ res='<form action="%s" method="%s" %s>\n' % (self.action, self.method, self.parameters) res+="<fieldset>\n<ol>\n" for name in form_fields: obj=self.datas[name] if self.errors.has_key(name): res+= '<li class="error">' errormsg=self.render_error(name)+"\n" else: res+= "<li>" errormsg=None value=self.values.get(name, "") res+= obj.render(name, value) if errormsg: res+=errormsg res+= "</li>\n" res+="</ol>\n</fieldset>\n" res+=self.submit_text res+="</form>\n" return res def validate(self, input_values, form_fields): """Validate the data provided in the 1st parameter (a dictionary) agains the fields provided in the 2nd parameter (a list). and store the values in self.values This is an important medthod that allow you to generate self.values. self.values is the actual result of the form. """ self.errors={} for name in form_fields: obj=self.datas[name] if input_values.has_key(name): data=input_values[name] else: data="" err=obj.isvalid(data) if err: self.errors[name]=err else: self.values[name]=data def render_list(self, records): """Generate a table with a list of possible values associated with this form. 1st parameter must be a list of dictionary. The first column of the generated table will receive the hyperlink: /admin/edit/<table name>/<record id> to the real form """ res="""<table class="tablesorter">\n<thead>\n<tr>""" for name in self._html_list: res+="<th>%s</th>" % name res+="</tr>\n</thead>\n<tbody>" i=1 for data in records: if i%2==0: class_="odd" else: class_="even" res+='<tr class="%s">' % class_ j=1 for name in self._html_list: obj=self.datas[name] if j==1: pk_path=[] for key in self._dbkey: pk_path.append(unicode(data[key])) res+="""<td %s><a href="/admin/edit/%s/%s">%s</a></td>""" % (obj.list_attrs,self.__class__.__name__, "/".join(pk_path),unicode(data[name] or "")) else: res+="<td %s>%s</td>" % (obj.list_attrs, unicode(data[name] or "")) j+=1 res+="</tr>\n" i+=1 res+="\n</tbody>\n</table>" return res
class Rational: def __init__(self, p, q): self.numerator = p self.denominator = q def __mul__(self, other): return Rational( self.numerator * other.numerator, self.denominator * other.denominator ) def __str__(self): return f"{self.numerator}/{self.denominator}" r0 = Rational(1, 2) print(r0) r1 = Rational(1, 3) print(r1) r2 = r0 * r1 print(r2)
# -*- coding: utf-8 -*- db.define_table('Device', Field('device_id', 'string'), Field('device_name', 'string'), Field('model', 'string'), Field('location', 'string') ) db.Device.device_id.requires = [IS_NOT_EMPTY(),IS_NOT_IN_DB(db, 'Device.device_id')] db.Device.device_name.requires = IS_NOT_EMPTY() db.define_table('User_Device', Field('user_ref_id', 'reference auth_user'), Field('device_ref_id', 'reference Device')) db.define_table('Direction', Field('direction_type', label='Direction'), format="%(direction_type)s") db.define_table('Control_Instruction', Field('device_ref_id', 'reference Device'), Field('onoff_flag', 'boolean', notnull=True, label='Motor ON/OFF', comment='* Check for ON & Uncheck for OFF'), Field('volt_flag', 'string', label='Voltage'), Field('curr_flag', 'string', label='Current'), Field('rot_flag', 'string', label='Rotation', comment='* Insert only integer value [revolution per minute]'), Field('dir_flag', 'reference Direction', label='Direction', requires = IS_IN_DB(db, db.Direction.id,'%(direction_type)s')), Field('freq_flag', 'string', label='Frequency'), Field('off_flag', 'boolean', notnull=True, label='Off') ) db.define_table('Changes', Field('device_ref_id', 'reference Device'), Field('change_flag', 'string') ) db.define_table('Status', Field('device_ref_id', 'reference Device'), Field('created', 'datetime'), Field('last_ping','datetime', requires=IS_NOT_EMPTY()), Field('server_time','datetime', requires=IS_NOT_EMPTY())) db.define_table('Device_States', Field('device_ref_id', 'reference Device'), Field('on_or_off', 'boolean', notnull=True, label='ON/OFF'), Field('voltage', 'string'), Field('current', 'string'), Field('rotation', 'string'), Field('direction', 'reference Direction', requires = IS_IN_DB(db, db.Direction.id,'%(direction_type)s')), Field('frequency', 'string'), Field('off', 'boolean', notnull=True, label='OFF'))
# i = 0 lista = [i]*6 while i < len(lista): lista[i] = int(input('Digite a nota {}: '.format(i+1))) i += 1 print('Notas digitadas') i = 0 while i < len(lista): print(lista[i]) i += 1 i = 0 s = 0 while i < len(lista): s += lista[i] i += 1 media = s/(i) print('Média: {:.2f}'.format(media))
lista = [1753, 1858, 1860, 1978, 1758, 1847, 2010, 1679, 1222, 1723, 1592, 1992, 1865, 1635, 1692, 1653, 1485, 848, 1301, 1818, 1872, 1883, 1464, 2002, 1736, 1821, 1851, 1299, 1627, 1698, 1713, 1676, 1673, 1448, 1939, 1506, 1896, 1710, 1677, 1894, 1645, 1454, 1972, 1687, 265, 1923, 1666, 1761, 1386, 2006, 1463, 1759, 1460, 1722, 1670, 1731, 1732, 1976, 1564, 1380, 1981, 1998, 1912, 1479, 1500, 167, 1904, 1689, 1810, 1675, 1811, 1671, 1535, 1624, 1638, 1848, 1646, 1795, 1717, 1803, 1867, 1794, 1774, 1245, 1915, 1601, 1656, 1472, 1700, 1887, 1869, 1876, 1561, 1743, 1900, 1574, 1400, 1950, 1893, 1576, 1903, 1747, 1560, 1445, 1652, 633, 1970, 1812, 1807, 1788, 1948, 1588, 1639, 1719, 1680, 1773, 1890, 1347, 1344, 1456, 1691, 1842, 1585, 1953, 410, 1791, 485, 1412, 1994, 1799, 1955, 1554, 1661, 1708, 1824, 1553, 1993, 1911, 1515, 1545, 856, 1685, 1982, 1954, 1480, 1709, 1428, 1829, 1606, 1613, 1941, 1483, 1513, 1664, 1801, 1720, 1984, 1575, 1805, 1833, 1418, 1882, 1746, 483, 1674, 1467, 1453, 523, 1414, 1800, 1403, 1946, 1868, 1520, 1861, 1580, 1995, 1960, 1625, 1411, 1558, 1817, 1854, 1617, 1478, 735, 1593, 1778, 1809, 1584, 1438, 1845, 1712, 1655, 1990, 1578, 1703, 1895, 1765, 1572] def find_two_2020(lista): result = None for i in lista: for j in lista: if i + j == 2020: result = i * j return result def find_three_2020(lista): result = None for i in lista: for j in lista: for k in lista: if j + i + k == 2020: result = j * i * k return result result = find_three_2020(lista) print(result) def find_sum(lista, num): for i in lista: need = abs(i-num) if need in lista: return [i, need] lista = [1, 2, 4, 9, 5, 4] print(find_sum(lista, 8))
class helloworld: def hello(self): print("This is my first task !") def run(): helloworld().hello()
# dp class Solution: def lengthOfLIS(self, nums: 'List[int]') -> 'int': if len(nums) < 2: return len(nums) dp = [1] * (len(nums) + 1) for i in range(1, len(nums)): for j in range(0, i): if nums[i] > nums[j]: dp[i] = max(dp[i], dp[j] + 1) return max(dp)
class Configuration: """ Configuration file for Twitter Sentiment """ def __init__(self): self.color = "#00A8E0" self.total_gauge_color = "#FF0102" self.image_path = "static/icon.jpeg" self.default_model = "twitter_sentiment_model" self.title = "Twitter Sentiment" self.subtitle = "Searches twitter hashtags and sentiment analysis" self.icon = "UpgradeAnalysis" self.boxes = { "banner": "1 1 -1 1", "logo": "11 1 -1 1", "navbar": "4 1 -1 1", "search_click": "11 2 2 1", "search_tab": "1 2 10 1", "credentials": "-1 -1 -1 -1" } self.tweet_row_indexes = ['3', '9', '15', '21', '27'] self.tweet_column_indexes = ['1', '4', '7', '10'] self.max_tweet_count = 12 self.default_search_text = 'AI' self.ask_for_access_text = "Apply for access : <a href=\"https://developer.twitter.com/en/apply-for-access\" " \ "target='_blank'\">Visit developer.twitter.com!</a>" self.popularity_terms = {'neg': 'Negative', 'neu': 'Neutral', 'pos': 'Positive', 'compound': 'Compound'}
# -*- coding: utf-8 -*- """ Created on Wed Jun 3 17:48:06 2020 @author: Fernando """ # A = [14,13,12,11,10,9,8,7,6,5,4,3,2,1] A = [3,2,1] B = [] C = [] count = 0 def towers_of_hanoi(A,B,C,n): global count if n == 1: disk = A.pop() C.append(disk) count +=1 else: towers_of_hanoi(A,C,B,n-1) print(f'First call {A,B,C}') towers_of_hanoi(A,B,C,1) print(f'Second call {A,B,C}') towers_of_hanoi(B,A,C,n-1) print(f'Third call {A,B,C}') return count towers_of_hanoi(A,B,C,3)
def test_udp_header_with_counter(api, b2b_raw_config, utils): """ Configure a raw udp flow with, - Non-default Counter Pattern values of src and dst Port address, length, checksum - 100 frames of 74B size each - 10% line rate Validate, - tx/rx frame count is as expected - all captured frames have expected src and dst Port address """ api.set_config(api.config()) flow = b2b_raw_config.flows[0] packets = 100 size = 74 flow.packet.ethernet().ipv4().udp() eth, ip, udp = flow.packet[0], flow.packet[1], flow.packet[2] eth.src.value = "00:0c:29:1d:10:67" eth.dst.value = "00:0c:29:1d:10:71" ip.src.value = "10.10.10.1" ip.dst.value = "10.10.10.2" udp.src_port.increment.start = 5000 udp.src_port.increment.step = 2 udp.src_port.increment.count = 10 udp.dst_port.decrement.start = 6000 udp.dst_port.decrement.step = 2 udp.dst_port.decrement.count = 10 flow.duration.fixed_packets.packets = packets flow.size.fixed = size flow.rate.percentage = 10 flow.metrics.enable = True utils.start_traffic(api, b2b_raw_config) utils.wait_for( lambda: results_ok(api, size, packets, utils), "stats to be as expected", ) captures_ok(api, b2b_raw_config, size, utils) def results_ok(api, size, packets, utils): """ Returns true if stats are as expected, false otherwise. """ port_results, flow_results = utils.get_all_stats(api) frames_ok = utils.total_frames_ok(port_results, flow_results, packets) bytes_ok = utils.total_bytes_ok(port_results, flow_results, packets * size) return frames_ok and bytes_ok def captures_ok(api, cfg, size, utils): """ Returns normally if patterns in captured packets are as expected. """ src = [src_port for src_port in range(5000, 5020, 2)] dst = [dst_port for dst_port in range(6000, 5980, -2)] cap_dict = utils.get_all_captures(api, cfg) assert len(cap_dict) == 1 for k in cap_dict: i = 0 j = 0 for packet in cap_dict[k]: assert utils.to_hex(packet[34:36]) == hex(src[i]) assert utils.to_hex(packet[36:38]) == hex(dst[i]) assert len(packet) == size i = (i + 1) % 10 j = (j + 1) % 2
''' Dict with attr access to keys. Usage: pip install adict from adict import adict d = adict(a=1) assert d.a == d['a'] == 1 See all features, including ajson() in adict.py:test(). adict version 0.1.7 Copyright (C) 2013-2015 by Denis Ryzhkov <[email protected]> MIT License, see http://opensource.org/licenses/MIT ''' #### adict class adict(dict): def __getattr__(self, name): try: return self[name] except KeyError: raise self.__attr_error(name) def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): try: del self[name] except KeyError: raise self.__attr_error(name) def __attr_error(self, name): return AttributeError("type object '{subclass_name}' has no attribute '{attr_name}'".format(subclass_name=type(self).__name__, attr_name=name)) def copy(self): return adict(self) #### ajson def ajson(item): return ( adict((name, ajson(value)) for name, value in item.iteritems()) if isinstance(item, dict) else [ajson(value) for value in item] if isinstance(item, list) else item ) #### test def test(): d = adict(a=1) # Create from names and values. assert d == adict(dict(a=1)) # Create from dict. assert d.a == d['a'] == 1 # Get by attr and by key. d.b = 2 # Set by attr. assert d.b == d['b'] == 2 d['c'] = 3 # Set by key. assert d.c == d['c'] == 3 d.update(copy=3) # Set reserved name by update(). d['copy'] = 3 # Set reserved name by key. assert d['copy'] == 3 # Get reserved name by key. assert isinstance(d.copy(), adict) # copy() is adict too. assert d.copy().a == d.a == 1 # Really. assert d.copy() is not d # But not the same object. del d.a # Delete by attr. assert 'a' not in d # Check membership. try: d.a # Exception on get, has no attribute 'a'. raise Exception('AttributeError expected') except AttributeError as e: # Exception is of correct type. assert str(e) == "type object 'adict' has no attribute 'a'" # And correct message. try: del d.a # Exception on delele, has no attribute 'a'. raise Exception('AttributeError expected') except AttributeError as e: # Exception is of correct type. assert str(e) == "type object 'adict' has no attribute 'a'" # And correct message. class SubClass(adict): pass try: SubClass().a # Exception in SubClass. except AttributeError as e: # Exception is of correct type. assert str(e) == "type object 'SubClass' has no attribute 'a'" # And correct message. j = ajson({"e": ["f", {"g": "h"}]}) # JSON with all dicts converted to adicts. assert j.e[1].g == 'h' # Get by attr in JSON. print('OK') if __name__ == '__main__': test()
soma = 0 sMMenos20 = 0 idadevelho = 0 for i in range(1, 5): nome = input('Escreva o nome da {}° pessoa: '.format(i)) idade = int(input('Escreva a sua idade: ')) gen = input('Escreva seu gênero: [F/M/NB] ').upper() print('='*30) soma = soma + idade if gen == 'F' and idade < 20: sMMenos20 = sMMenos20 + 1 if gen == 'M': if i == 1: velhoNome = nome idadevelho = idade else: if idade > idadevelho: idadevelho = idade velhoNome = nome media = soma/4 print('='*50) print('A média de idade do grupo é {:.1f} anos'.format(media)) print('No grupo existem {} mulheres com menos de 20 anos.'.format(sMMenos20)) print('O homem mais velho é o {} e tem {} anos'.format(velhoNome,idadevelho))
while True: n = int(input()) if n == 0: break x, y = [int(g) for g in str(input()).split()] for j in range(n): a, b = [int(g) for g in str(input()).split()] if a == x or b == y: print('divisa') else: if x < a: if y < b: print('NE') else: print('SE') else: if y < b: print('NO') else: print('SO')
str(print('\033[0;34mBem-vindo ao site de empréstimo bancário!\033[m')) valor = float(input('Qual será o valor da casa desejada?R$')) sal = float(input('Qual é a sua remenuração mensal?R$')) ano = int(input('Em quantos anos você pretende pagar o imóvel?')) a = ano * 12 #1 ano = 12 meses pres = valor/a #prestação é o valor da casa dividido pelo número de meses if pres > sal*0.3: #prestação menor que 30% do salario print('\033[0;31mA prestação é de R${:.2f} e está excendendo 30% de sua remuneração mensal,o empréstimo foi negado.'.format(pres)) else: print('\033[0;32mA prestação é de R${:.2f}.'.format(pres))
""" TW3: Sliced to Order Mohammed Elhaj Sohrab Rajabi Andrew Nalundasan Teamwork exercise 3 code """ # user inputs user_text = input('Enter some text, please: ') start_position = int(input('Slice starting position (zero for beginning): ')) end_position = int(input('Slice ending position (can be negative to count from end): ')) stride = int(input('Stride: ')) print('Your text:', user_text) # step 2: add delimiter '|' slice = '|' + user_text[start_position:end_position:stride] + '|' print('You want to slice it from', start_position, 'to', end_position, 'which is', slice) # step 3: setup prefix and suffix using slicing prefix = '|' + user_text[:start_position:stride] + '|' print('Prefix: ', prefix) suffix = '|' + user_text[end_position::stride] + '|' print('Suffix: ', suffix) # step 4: put it all together print(user_text[:start_position:stride] + '|' + user_text[start_position:end_position:stride] + '|' + user_text[end_position::stride])
''' По данному натуральному n вычислите сумму 1**3+2**3+3**3+...+n**3. ''' n = int(input()) sum1 = 0 for i in range(1, n + 1): sum1 += i ** 3 print(sum1)
# Módulo criptomat # Dominio público def mcd(a, b): # Devuelve el MCD de dos números a y b mediante # el algoritmo de Euclides while a != 0: a, b = b % a, a return b def invMod(a, m): # Devuelve el inverso modular de a mod m, que es el # número x tal que a * x mod m = 1 if mcd(a, m) != 1: return None # a y m no son coprimos. No existe el inverso # Cálculo mediante el algoritmo extendido de Euclides: u1, u2, u3 = 1, 0, a v1, v2, v3 = 0, 1, m while v3 != 0: q = u3 // v3 v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3 return u1 % m
def normalizable_feature(mean, std): """Decorator for features to specify default normalization. Args: mean: The mean value for the feature. std: The standard deviation for the feature. """ def _normalizable_feature(func): func.normal_mean = mean func.normal_std = std return func return _normalizable_feature def tokenizable_feature(tokens): """Decorator for features to specify default tokens. Args: tokens: The default set of tokens for the feature. """ def _tokenizable_feature(func): func.tokens = tokens return func return _tokenizable_feature
''' - Leetcode problem: 98 - Difficulty: Medium - Brief problem description: Given a binary tree, determine if it is a valid binary search tree (BST). Assume a BST is defined as follows: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: 2 / \ 1 3 Input: [2,1,3] Output: true Example 2: 5 / \ 1 4 / \ 3 6 Input: [5,1,4,null,null,3,6] Output: false Explanation: The root node's value is 5 but its right child's value is 4. - Solution Summary: Have to keep the lower bound and higher bound - Used Resources: --- Bo Zhou ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: return self.checkBST(root, None, None) def checkBST(self, root, low, high): if root is None: return True result = True if low and root.val <= low: return False if high and root.val >= high: return False if high: result = result and self.checkBST(root.left, low, min(high, root.val)) else: result = result and self.checkBST(root.left, low, root.val) if low: result = result and self.checkBST(root.right, max(low, root.val), high) else: result = result and self.checkBST(root.right, root.val, high) return result
""" Write a program to accept a character from the user and display whether it is a special character, digit or an alphabet. The program should continue as long as the juser wishes to. """ x = "Y" while x == "y": check = input("Enter a character: ") if check >= 'a' and check <= 'z' or check >= 'A' and check <= 'Z': print("It is an alphabet") elif check >= '0' and check <= '9': print("It is a digit") else: print("It is a special character") x = input("Do you wish to continue? Y / N ?") if x == "y" or x == "Y": continue else: print("Thank you for using our program. ") break
class TapeEnvWrapper: def __init__(self, env): self.__env = env self.__factors = self.__get_factors() def reset(self): return self.__env.reset() def step(self, action): action = self.__undiscretise(action) next_state, reward, done, info = self.__env.step(action) return next_state, reward, done, info def render(self): self.__env.render() def close(self): self.__env.close() def get_random_action(self): action = self.__env.action_space.sample() total = 0 pointer = 0 for dim in action: total += dim * self.__factors[pointer] pointer += 1 return total def get_total_actions(self): total = 1 for dim in self.__env.action_space: total *= dim.n return total def get_total_states(self): return self.__env.observation_space.n def __undiscretise(self, action): act = [0, 0, 0] for i in range(2, -1, -1): act[i] = action // self.__factors[i] action = action % self.__factors[i] return tuple(act) def __get_factors(self): factors = [] for i in range(len(self.__env.action_space)): factors.append(self.__get_factor(i, self.__env.action_space)) return factors def __get_factor(self, pos, action_space): if pos == 0: return 1 if pos == 1: return action_space[0].n return action_space[pos-1].n * self.__get_factor(pos - 1, action_space) def seed(self, seed=None, set_action_seed=True): if set_action_seed: self.__env.action_space.seed(seed) return self.__env.seed(seed)
class Solution: def solve(self, n): if n == 0: return '0' remainders = [] while n: n, r = divmod(n, 3) remainders.append(str(r)) return ''.join(reversed(remainders))
# # PySNMP MIB module CISCO-ITP-GSP2-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ITP-GSP2-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:03:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint") cgspInstNetwork, = mibBuilder.importSymbols("CISCO-ITP-GSP-MIB", "cgspInstNetwork") CItpTcPointCode, CItpTcLinkSLC, CItpTcLinksetId, CItpTcAclId, CItpTcNetworkName, CItpTcXuaName = mibBuilder.importSymbols("CISCO-ITP-TC-MIB", "CItpTcPointCode", "CItpTcLinkSLC", "CItpTcLinksetId", "CItpTcAclId", "CItpTcNetworkName", "CItpTcXuaName") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") InetAddressType, InetPortNumber, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetPortNumber", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") Gauge32, Integer32, MibIdentifier, Bits, Counter32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, IpAddress, Unsigned32, ModuleIdentity, iso, ObjectIdentity, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Integer32", "MibIdentifier", "Bits", "Counter32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "IpAddress", "Unsigned32", "ModuleIdentity", "iso", "ObjectIdentity", "TimeTicks") TimeStamp, TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "TextualConvention", "DisplayString", "RowStatus") ciscoGsp2MIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 332)) ciscoGsp2MIB.setRevisions(('2008-07-09 00:00', '2007-12-18 00:00', '2004-05-26 00:00', '2003-08-07 00:00', '2003-03-03 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoGsp2MIB.setRevisionsDescriptions(('Added Context Table for Probless Monitor feature.', 'Added Processor Number to cgsp2LocalPeerTable for SAMI interfaces.', 'Added following object to provide information related to Non-stop Operations function. cgsp2OperMtp3Offload, cgsp2OperRedundancy', 'Add new table to support MTP3 errors', 'Initial version of this MIB module.',)) if mibBuilder.loadTexts: ciscoGsp2MIB.setLastUpdated('200807090000Z') if mibBuilder.loadTexts: ciscoGsp2MIB.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoGsp2MIB.setContactInfo('Cisco Systems, Inc Customer Service Postal: 170 W. Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: [email protected]') if mibBuilder.loadTexts: ciscoGsp2MIB.setDescription('The MIB for providing information specified in ITU Q752 Monitoring and Measurements for signalling System No. 7(SS7) Network. This information can be used to manage messages transported over SS7 Network via Cisco IP Transfer Point. The Cisco IP Transfer Point (ITP) is a hardware and software solution that transports SS7 traffic using IP. Each ITP node provides function similar to SS7 signalling point. The relevant ITU documents describing this technology is the ITU Q series, including ITU Q.700: Introduction to CCITT signalling System No. 7 and ITU Q.701 Functional description of the message transfer part (MTP) of signalling System No. 7. The ITP Quality of Service (QoS) model allows the definition of 8 QoS classes, 0 through 7. QoS classes can be assigned only SCTP links. Only one QoS class can be assigned to an SCTP link. Class 0 will be designated as the default class. Packets that are not classified to a designated QoS class will get assigned to the default class. Each provisioned QoS class can be assigned an IP precedence value or a Differential Services Code Point (DSCP). The default class is initialized to IP precedence zero (0). The default class initial TOS setting can be changed through the command line interface. The Type of Service (TOS) byte in the IP header will be set to the IP precedence or DSCP that is assigned to class. Every packet forwarded over an SCTP link that was provisioned for a given QoS class will have the TOS byte set.') ciscoGsp2MIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 0)) ciscoGsp2MIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 1)) ciscoGsp2MIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 2)) cgsp2Events = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1)) cgsp2Qos = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2)) cgsp2LocalPeer = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3)) cgsp2Mtp3Errors = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 4)) cgsp2Operation = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 5)) cgsp2Context = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6)) class Cgsp2TcQosClass(TextualConvention, Unsigned32): description = 'The quality of service classification to be assigned to the IP packets used to transport the SS7 messages. Zero is a special value and is reserved to carry all traffic that does not specify a Qos or when exact match of the specified Qos is not available.' status = 'current' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(0, 7) class Cgsp2EventIndex(TextualConvention, Unsigned32): description = 'A monotonically increasing integer for the sole purpose of indexing events. When it reaches the maximum value the agent flushes the event table and wraps the value back to 1. Where lower values represent older entries and higher values represent newer entries.' status = 'current' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(1, 2147483647) class CItpTcContextId(TextualConvention, Unsigned32): description = 'Each context is assigned an unique identifier starting with one and are monotonically increased by one.' status = 'current' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(1, 4294967295) class CItpTcContextType(TextualConvention, Integer32): description = 'Indicate type or resources ....' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 6)) namedValues = NamedValues(("unknown", 0), ("cs7link", 1), ("asp", 6)) cgsp2EventTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 1), ) if mibBuilder.loadTexts: cgsp2EventTable.setStatus('current') if mibBuilder.loadTexts: cgsp2EventTable.setDescription('A table used to provide information about all types of events on a signalling point.') cgsp2EventTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-ITP-GSP-MIB", "cgspInstNetwork"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventType")) if mibBuilder.loadTexts: cgsp2EventTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2EventTableEntry.setDescription('A table of SS7 events generated and received by a specific signalling point.') cgsp2EventType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("as", 1), ("asp", 2), ("mtp3", 3), ("pc", 4)))) if mibBuilder.loadTexts: cgsp2EventType.setStatus('current') if mibBuilder.loadTexts: cgsp2EventType.setDescription("The type of event history as follows. 'as' - Application Service 'asp' - Application Service Process 'mtp3' - Message Transport Protocol Level 3 'pc' - Point-code") cgsp2EventLoggedEvents = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 1, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventLoggedEvents.setStatus('current') if mibBuilder.loadTexts: cgsp2EventLoggedEvents.setDescription('The number of events that have been logged.') cgsp2EventDroppedEvents = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 1, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventDroppedEvents.setStatus('current') if mibBuilder.loadTexts: cgsp2EventDroppedEvents.setDescription('The number of events that could not be logged due to unavailable resources.') cgsp2EventMaxEntries = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 1, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readwrite") if mibBuilder.loadTexts: cgsp2EventMaxEntries.setStatus('current') if mibBuilder.loadTexts: cgsp2EventMaxEntries.setDescription('The upper limit on the number of events that the event history can contain. A value of 0 will prevent any event history from being retained. When this table is full, the oldest entry will be deleted as a new entry is added.') cgsp2EventMaxEntriesAllowed = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 1, 1, 5), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventMaxEntriesAllowed.setStatus('current') if mibBuilder.loadTexts: cgsp2EventMaxEntriesAllowed.setDescription('This object specifies the maximum number of events that can be specified for cgsp2EventMaxEntries object.') cgsp2EventAsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 2), ) if mibBuilder.loadTexts: cgsp2EventAsTable.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAsTable.setDescription('A table of Application Service events generated per signalling point.') cgsp2EventAsTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-ITP-GSP-MIB", "cgspInstNetwork"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventAsName"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventAsIndex")) if mibBuilder.loadTexts: cgsp2EventAsTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAsTableEntry.setDescription('An entry is added to this table for each application service event associated with a particular application service. The table contains the latest number of events defined by the cgsp2EventMaxEntries object. Once the table is full, the oldest entry is removed and a new entry is created to accommodate the new event.') cgsp2EventAsName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 2, 1, 1), CItpTcXuaName()) if mibBuilder.loadTexts: cgsp2EventAsName.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAsName.setDescription('The application server name. This name has only local significance.') cgsp2EventAsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 2, 1, 2), Cgsp2EventIndex()) if mibBuilder.loadTexts: cgsp2EventAsIndex.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAsIndex.setDescription('Index into application service event history.') cgsp2EventAsText = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 2, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventAsText.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAsText.setDescription('A brief description of the application service event in text format.') cgsp2EventAsTimestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 2, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventAsTimestamp.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAsTimestamp.setDescription('The value of sysUpTime at the time of the application service event was processed.') cgsp2EventAspTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 3), ) if mibBuilder.loadTexts: cgsp2EventAspTable.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAspTable.setDescription('A table of application service process events generated per signalling point.') cgsp2EventAspTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 3, 1), ).setIndexNames((0, "CISCO-ITP-GSP-MIB", "cgspInstNetwork"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventAspName"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventAspIndex")) if mibBuilder.loadTexts: cgsp2EventAspTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAspTableEntry.setDescription('An entry is added to this table for each application service process event associated with a particular application service process. The table contains the latest number of events defined by the cgsp2EventMaxEntries object. Once the table is full, the oldest entry is removed and a new entry is created to accommodate the new event.') cgsp2EventAspName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 3, 1, 1), CItpTcXuaName()) if mibBuilder.loadTexts: cgsp2EventAspName.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAspName.setDescription('The application server process name. This name has only local significance.') cgsp2EventAspIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 3, 1, 2), Cgsp2EventIndex()) if mibBuilder.loadTexts: cgsp2EventAspIndex.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAspIndex.setDescription('Index into application service process event history.') cgsp2EventAspText = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 3, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventAspText.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAspText.setDescription('A brief description of the application service process event in text format.') cgsp2EventAspTimestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 3, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventAspTimestamp.setStatus('current') if mibBuilder.loadTexts: cgsp2EventAspTimestamp.setDescription('The value of sysUpTime at the time of the application service process event was received.') cgsp2EventMtp3Table = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 4), ) if mibBuilder.loadTexts: cgsp2EventMtp3Table.setStatus('current') if mibBuilder.loadTexts: cgsp2EventMtp3Table.setDescription('A table of MTP3 events generated per signalling point.') cgsp2EventMtp3TableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 4, 1), ).setIndexNames((0, "CISCO-ITP-GSP-MIB", "cgspInstNetwork"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventMtp3Index")) if mibBuilder.loadTexts: cgsp2EventMtp3TableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2EventMtp3TableEntry.setDescription('An MTP3 event that was previously generated by this signalling point. An entry is added to this table for each SS7 event generated on the managed system. The table contains the latest number of events defined by the cgsp2EventMaxEntries object. Once the table is full, the oldest entry is removed and a new entry is created to accommodate the new event.') cgsp2EventMtp3Index = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 4, 1, 1), Cgsp2EventIndex()) if mibBuilder.loadTexts: cgsp2EventMtp3Index.setStatus('current') if mibBuilder.loadTexts: cgsp2EventMtp3Index.setDescription('Index into MTP3 event history.') cgsp2EventMtp3Text = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 4, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventMtp3Text.setStatus('current') if mibBuilder.loadTexts: cgsp2EventMtp3Text.setDescription('A brief description of the SS7 event in text format. Each event provides information of state transitions specific to the MTP3 protocol.') cgsp2EventMtp3Timestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 4, 1, 3), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventMtp3Timestamp.setStatus('current') if mibBuilder.loadTexts: cgsp2EventMtp3Timestamp.setDescription('The value of sysUpTime at the time of the event was received by MTP3 layer.') cgsp2EventPcTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 5), ) if mibBuilder.loadTexts: cgsp2EventPcTable.setStatus('current') if mibBuilder.loadTexts: cgsp2EventPcTable.setDescription('A table of point-code events generated per signalling point.') cgsp2EventPcTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 5, 1), ).setIndexNames((0, "CISCO-ITP-GSP-MIB", "cgspInstNetwork"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventPc"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2EventPcIndex")) if mibBuilder.loadTexts: cgsp2EventPcTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2EventPcTableEntry.setDescription('An entry is added to this table for each point-code event. The table contains the latest number of events defined by the cgsp2EventMaxEntries object. Once the table is full, the oldest entry is removed and a new entry is created to accommodate the new event.') cgsp2EventPc = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 5, 1, 1), CItpTcPointCode()) if mibBuilder.loadTexts: cgsp2EventPc.setStatus('current') if mibBuilder.loadTexts: cgsp2EventPc.setDescription('The point code number.') cgsp2EventPcIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 5, 1, 2), Cgsp2EventIndex()) if mibBuilder.loadTexts: cgsp2EventPcIndex.setStatus('current') if mibBuilder.loadTexts: cgsp2EventPcIndex.setDescription('Index into point-code event history.') cgsp2EventPcText = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 5, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventPcText.setStatus('current') if mibBuilder.loadTexts: cgsp2EventPcText.setDescription('A brief description of the point-code event in text format.') cgsp2EventPcTimestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 1, 5, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2EventPcTimestamp.setStatus('current') if mibBuilder.loadTexts: cgsp2EventPcTimestamp.setDescription('The value of sysUpTime at the time of the point-code event was received.') cgsp2QosTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1), ) if mibBuilder.loadTexts: cgsp2QosTable.setStatus('current') if mibBuilder.loadTexts: cgsp2QosTable.setDescription('A table of information related to the defining Quality of Service to transport SS7 packets using SCTP/IP. Entries are added to this table via cgsp2QosRowStatus in accordance with the RowStatusconvention.') cgsp2QosTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1, 1), ).setIndexNames((0, "CISCO-ITP-GSP-MIB", "cgspInstNetwork"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2QosClass")) if mibBuilder.loadTexts: cgsp2QosTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2QosTableEntry.setDescription('Each entry define information relate to a Quality of Service class as needed to transport SS7 packets using SCTP/IP.') cgsp2QosClass = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1, 1, 1), Cgsp2TcQosClass()) if mibBuilder.loadTexts: cgsp2QosClass.setStatus('current') if mibBuilder.loadTexts: cgsp2QosClass.setDescription('The quality of service class that can be defined to transport SS7 Packets using SCTP/IP.') cgsp2QosType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ipPrecedence", 1), ("ipDscp", 2)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2QosType.setStatus('current') if mibBuilder.loadTexts: cgsp2QosType.setDescription('Enumerated list of QoS type that can be defined. A value ipPrecedence suggests that IP Type of Service (TOS) is based on cgsp2QosPrecedenceValue. A value ipDscp suggests that IP Type of Service (TOS) is based on cgsp2QosIpDscp.') cgsp2QosPrecedenceValue = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 7))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2QosPrecedenceValue.setStatus('current') if mibBuilder.loadTexts: cgsp2QosPrecedenceValue.setDescription('A value to assign to the IP TOS bits in the IP datagram that carries one or more SS7 packets. The IP Precedence value is specified if cgsp2QosType is ipPrecedence, otherwise it is -1.') cgsp2QosIpDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 63))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2QosIpDscp.setReference('Differentiated Services is described and defined in the RFCs: 2474, 2475, 2597, and 2598.') if mibBuilder.loadTexts: cgsp2QosIpDscp.setStatus('current') if mibBuilder.loadTexts: cgsp2QosIpDscp.setDescription('DiffServ CodePoint (DSCP) value to assign to the IP TOS bits in the IP datagram that carries one or more SS7 packets. DSCP provides scalable mechanisms to classify packets into groups or classes that have similar QoS requirements and then gives these groups the required treatment at every hop in the network. The DSCP value is specified if cgsp2QosType is ipDscp, otherwise it is -1.') cgsp2QosAclId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1, 1, 5), CItpTcAclId()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2QosAclId.setStatus('current') if mibBuilder.loadTexts: cgsp2QosAclId.setDescription('ITP Access lists can be used to use information specific to SS7 packets to assign an Qos class. A value of zero indicates that no access control list is present.') cgsp2QosRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 2, 1, 1, 6), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2QosRowStatus.setStatus('current') if mibBuilder.loadTexts: cgsp2QosRowStatus.setDescription('The object is used by a management station to create or delete the row entry in cgsp2QosTable following the RowStatus textual convention.') cgsp2LocalPeerTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 1), ) if mibBuilder.loadTexts: cgsp2LocalPeerTable.setStatus('current') if mibBuilder.loadTexts: cgsp2LocalPeerTable.setDescription('A local-peer table used establish SCTP associations. The port will be used to receive and sent requests to establish associations. Entries are added to this table via cgsp2LocalPeerRowStatus in accordance with the RowStatus convention.') cgsp2LocalPeerTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 1, 1), ).setIndexNames((0, "CISCO-ITP-GSP2-MIB", "cgsp2LocalPeerPort")) if mibBuilder.loadTexts: cgsp2LocalPeerTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2LocalPeerTableEntry.setDescription('A list of attributes of the local-peer.') cgsp2LocalPeerPort = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 1, 1, 1), InetPortNumber()) if mibBuilder.loadTexts: cgsp2LocalPeerPort.setStatus('current') if mibBuilder.loadTexts: cgsp2LocalPeerPort.setDescription('The local SCTP port for this local-peer. The value zero is not allowed.') cgsp2LocalPeerSlotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1, 32767)).clone(-1)).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2LocalPeerSlotNumber.setStatus('current') if mibBuilder.loadTexts: cgsp2LocalPeerSlotNumber.setDescription('This value is used to specify to which slot the local-peer will be offloaded. A value of negative one indicates the local-peer is not offloaded.') cgsp2LocalPeerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 1, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2LocalPeerRowStatus.setStatus('current') if mibBuilder.loadTexts: cgsp2LocalPeerRowStatus.setDescription('The object is used by a management station to create or delete a row entry in cgsp2LocalPeerTable following the RowStatus textual convention.') cgsp2LocalPeerProcessorNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2LocalPeerProcessorNumber.setStatus('current') if mibBuilder.loadTexts: cgsp2LocalPeerProcessorNumber.setDescription('This value is used to specify to which processor the local-peer will be offloaded on the line card indicated by cgsp2LocalPeerSlotNumber. For certain line cards like Flexwan, this value corresponds to bay number instead of processor number.') cgsp2LpIpAddrTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 2), ) if mibBuilder.loadTexts: cgsp2LpIpAddrTable.setStatus('current') if mibBuilder.loadTexts: cgsp2LpIpAddrTable.setDescription('A table of Local IP addresses group together to form the local-peer used to establish SCTP associations. For a given local-peer, there can be multiple local IP addresses which are used for the multi-homing feature of the SCTP associations. This table lists out the configured local IP addresses. Entries are added to this table via cgsp2LocalPeerRowStatus in accordance with the RowStatus convention.') cgsp2LpIpAddrTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 2, 1), ).setIndexNames((0, "CISCO-ITP-GSP2-MIB", "cgsp2LocalPeerPort"), (0, "CISCO-ITP-GSP2-MIB", "cgsp2LpIpAddressNumber")) if mibBuilder.loadTexts: cgsp2LpIpAddrTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2LpIpAddrTableEntry.setDescription('A list of attributes of the Local IP addresses for the local-peer.') cgsp2LpIpAddressNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))) if mibBuilder.loadTexts: cgsp2LpIpAddressNumber.setStatus('current') if mibBuilder.loadTexts: cgsp2LpIpAddressNumber.setDescription("This object specifies the index for the instance's IP address.") cgsp2LpIpAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 2, 1, 2), InetAddressType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2LpIpAddressType.setStatus('current') if mibBuilder.loadTexts: cgsp2LpIpAddressType.setDescription('This object contains the type of the local IP address used to create the association.') cgsp2LpIpAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 2, 1, 3), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2LpIpAddress.setStatus('current') if mibBuilder.loadTexts: cgsp2LpIpAddress.setDescription('This object contains the local IP address used to create association associations.') cgsp2LpIpAddressRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 3, 2, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cgsp2LpIpAddressRowStatus.setStatus('current') if mibBuilder.loadTexts: cgsp2LpIpAddressRowStatus.setDescription('The object is used by a management station to create or delete the row entry in cgsp2LpIpAddrTable following the RowStatus textual convention.') cgsp2Mtp3ErrorsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 4, 1), ) if mibBuilder.loadTexts: cgsp2Mtp3ErrorsTable.setStatus('current') if mibBuilder.loadTexts: cgsp2Mtp3ErrorsTable.setDescription('A table of MTP3 errors that have occurred on all Signalling Point supported by this device.') cgsp2Mtp3ErrorsTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 4, 1, 1), ).setIndexNames((0, "CISCO-ITP-GSP2-MIB", "cgsp2Mtp3ErrorsType")) if mibBuilder.loadTexts: cgsp2Mtp3ErrorsTableEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2Mtp3ErrorsTableEntry.setDescription('A list of attributes used to provide a summary of the various MTP3 errors encountered by the device.') cgsp2Mtp3ErrorsType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 4, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))) if mibBuilder.loadTexts: cgsp2Mtp3ErrorsType.setStatus('current') if mibBuilder.loadTexts: cgsp2Mtp3ErrorsType.setDescription('This object specifies the index for the various error types.') cgsp2Mtp3ErrorsDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 4, 1, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2Mtp3ErrorsDescription.setStatus('current') if mibBuilder.loadTexts: cgsp2Mtp3ErrorsDescription.setDescription('A brief description of the MTP3 error in text format.') cgsp2Mtp3ErrorsCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 4, 1, 1, 3), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2Mtp3ErrorsCount.setStatus('current') if mibBuilder.loadTexts: cgsp2Mtp3ErrorsCount.setDescription('Number of errors encountered for this type of MTP3 error as described in cgsp2Mtp3ErrorsDescription object.') cgsp2ContextTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1), ) if mibBuilder.loadTexts: cgsp2ContextTable.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextTable.setDescription('DCS(Data Collector Server) use ContextId as index to get additional information about the resource being monitoring. This table provides informations used to identify the resource(link or ASP).') cgsp2ContextEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1), ).setIndexNames((0, "CISCO-ITP-GSP2-MIB", "cgsp2ContextIdentifier")) if mibBuilder.loadTexts: cgsp2ContextEntry.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextEntry.setDescription('Each entry (conceptual row) represents a resource(Link or ASP) that can be monitored by the the Probeless Monitor Feature. Each are added to deleted from this table as Link and ASP are configured.') cgsp2ContextIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1, 1), CItpTcContextId()) if mibBuilder.loadTexts: cgsp2ContextIdentifier.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextIdentifier.setDescription('The unique Id for LINK or ASP to Application') cgsp2ContextType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1, 2), CItpTcContextType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2ContextType.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextType.setDescription('This object indicate the type of resource Link or ASP.') cgsp2ContextLinksetName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1, 3), CItpTcLinksetId()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2ContextLinksetName.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextLinksetName.setDescription('The name of the Linkset in which the link is configured and this object only applies when the cgsp2ContextType indicates the resource is a Link.') cgsp2ContextSlc = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1, 4), CItpTcLinkSLC()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2ContextSlc.setReference('ITU Q.704 Signalling network functions and messages. ANSI T1.111 Telecommunications - Signalling system No. 7 (SS7)-Message Transfer Part (MTP).') if mibBuilder.loadTexts: cgsp2ContextSlc.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextSlc.setDescription('The Signalling Link Code for this link.This object only applies when the cgsp2ContextType indicates the resource is an Link.') cgsp2ContextAsName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1, 5), CItpTcXuaName()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2ContextAsName.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextAsName.setDescription('The Aplication server name.This object only applies when the cgsp2ContextType indicates the resource is an ASP.') cgsp2ContextAspName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1, 6), CItpTcXuaName()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2ContextAspName.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextAspName.setDescription('The Application Server Process Name.This object only applies when the cgsp2ContextType indicates the resource is an ASP.') cgsp2ContextNetworkName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 6, 1, 1, 7), CItpTcNetworkName()).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2ContextNetworkName.setStatus('current') if mibBuilder.loadTexts: cgsp2ContextNetworkName.setDescription('The Network name configure for the instance in ITP') cgsp2OperMtp3Offload = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 5, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("main", 1), ("offload", 2))).clone('main')).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2OperMtp3Offload.setStatus('current') if mibBuilder.loadTexts: cgsp2OperMtp3Offload.setDescription("Indicates location of MTP3 management function as follows. 'main' - MTP3 Management function operates only on main processor. 'offload' - MTP3 Management function operates on main processor and other available processors.") cgsp2OperRedundancy = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 332, 1, 5, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("local", 2), ("distributed", 3))).clone('none')).setMaxAccess("readonly") if mibBuilder.loadTexts: cgsp2OperRedundancy.setStatus('current') if mibBuilder.loadTexts: cgsp2OperRedundancy.setDescription("The redundancy capability of devices for signalling points defined on this device as follows. 'none' - Device is not configured to support redundancy features. 'local' - Device provides redundancy by using backup processor on same device. 'distributed' - Device provides redundancy by using processors on two or more different physical device.") ciscoGsp2MIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 1)) ciscoGsp2MIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2)) ciscoGsp2MIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 1, 1)).setObjects(("CISCO-ITP-GSP2-MIB", "ciscoGsp2EventsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2QosGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2LocalPeerGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2MIBCompliance = ciscoGsp2MIBCompliance.setStatus('deprecated') if mibBuilder.loadTexts: ciscoGsp2MIBCompliance.setDescription('The compliance statement for entities which implement the CISCO-ITP-GSP2-MIB.my MIB') ciscoGsp2MIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 1, 2)).setObjects(("CISCO-ITP-GSP2-MIB", "ciscoGsp2EventsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2QosGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2LocalPeerGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2Mtp3ErrorsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2MIBComplianceRev1 = ciscoGsp2MIBComplianceRev1.setStatus('deprecated') if mibBuilder.loadTexts: ciscoGsp2MIBComplianceRev1.setDescription('The compliance statement for entities which implement the CISCO-ITP-GSP2-MIB.my MIB') ciscoGsp2MIBComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 1, 3)).setObjects(("CISCO-ITP-GSP2-MIB", "ciscoGsp2EventsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2QosGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2LocalPeerGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2Mtp3ErrorsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2OperationGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2MIBComplianceRev2 = ciscoGsp2MIBComplianceRev2.setStatus('deprecated') if mibBuilder.loadTexts: ciscoGsp2MIBComplianceRev2.setDescription('The compliance statement for entities which implement the CISCO-ITP-GSP2-MIB.my MIB') ciscoGsp2MIBComplianceRev3 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 1, 4)).setObjects(("CISCO-ITP-GSP2-MIB", "ciscoGsp2EventsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2QosGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2Mtp3ErrorsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2OperationGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2LocalPeerGroupSup1")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2MIBComplianceRev3 = ciscoGsp2MIBComplianceRev3.setStatus('deprecated') if mibBuilder.loadTexts: ciscoGsp2MIBComplianceRev3.setDescription('The compliance statement for entities which implement the CISCO-ITP-GSP2-MIB.my MIB') ciscoGsp2MIBComplianceRev4 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 1, 5)).setObjects(("CISCO-ITP-GSP2-MIB", "ciscoGsp2EventsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2QosGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2LocalPeerGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2Mtp3ErrorsGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2OperationGroup"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2LocalPeerGroupSup1"), ("CISCO-ITP-GSP2-MIB", "ciscoGsp2ContextGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2MIBComplianceRev4 = ciscoGsp2MIBComplianceRev4.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2MIBComplianceRev4.setDescription('The compliance statement for entities which implement the CISCO-ITP-GSP2-MIB.my MIB') ciscoGsp2EventsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2, 1)).setObjects(("CISCO-ITP-GSP2-MIB", "cgsp2EventLoggedEvents"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventDroppedEvents"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventMaxEntries"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventMaxEntriesAllowed"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventMtp3Text"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventMtp3Timestamp"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventAsText"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventAsTimestamp"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventAspText"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventAspTimestamp"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventPcText"), ("CISCO-ITP-GSP2-MIB", "cgsp2EventPcTimestamp")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2EventsGroup = ciscoGsp2EventsGroup.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2EventsGroup.setDescription('SS7 Event objects.') ciscoGsp2QosGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2, 2)).setObjects(("CISCO-ITP-GSP2-MIB", "cgsp2QosType"), ("CISCO-ITP-GSP2-MIB", "cgsp2QosPrecedenceValue"), ("CISCO-ITP-GSP2-MIB", "cgsp2QosIpDscp"), ("CISCO-ITP-GSP2-MIB", "cgsp2QosAclId"), ("CISCO-ITP-GSP2-MIB", "cgsp2QosRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2QosGroup = ciscoGsp2QosGroup.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2QosGroup.setDescription('SS7 Quality of Service objects.') ciscoGsp2LocalPeerGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2, 3)).setObjects(("CISCO-ITP-GSP2-MIB", "cgsp2LocalPeerSlotNumber"), ("CISCO-ITP-GSP2-MIB", "cgsp2LocalPeerRowStatus"), ("CISCO-ITP-GSP2-MIB", "cgsp2LpIpAddressType"), ("CISCO-ITP-GSP2-MIB", "cgsp2LpIpAddress"), ("CISCO-ITP-GSP2-MIB", "cgsp2LpIpAddressRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2LocalPeerGroup = ciscoGsp2LocalPeerGroup.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2LocalPeerGroup.setDescription('SS7 Local Peer objects.') ciscoGsp2Mtp3ErrorsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2, 4)).setObjects(("CISCO-ITP-GSP2-MIB", "cgsp2Mtp3ErrorsDescription"), ("CISCO-ITP-GSP2-MIB", "cgsp2Mtp3ErrorsCount")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2Mtp3ErrorsGroup = ciscoGsp2Mtp3ErrorsGroup.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2Mtp3ErrorsGroup.setDescription('SS7 MTP3 Error objects.') ciscoGsp2OperationGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2, 5)).setObjects(("CISCO-ITP-GSP2-MIB", "cgsp2OperMtp3Offload"), ("CISCO-ITP-GSP2-MIB", "cgsp2OperRedundancy")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2OperationGroup = ciscoGsp2OperationGroup.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2OperationGroup.setDescription('SS7 operation redundancy objects.') ciscoGsp2LocalPeerGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2, 6)).setObjects(("CISCO-ITP-GSP2-MIB", "cgsp2LocalPeerProcessorNumber")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2LocalPeerGroupSup1 = ciscoGsp2LocalPeerGroupSup1.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2LocalPeerGroupSup1.setDescription('SS7 Local Peer supplemental object to ciscoGsp2LocalPeerGroup.') ciscoGsp2ContextGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 332, 2, 2, 7)).setObjects(("CISCO-ITP-GSP2-MIB", "cgsp2ContextType"), ("CISCO-ITP-GSP2-MIB", "cgsp2ContextLinksetName"), ("CISCO-ITP-GSP2-MIB", "cgsp2ContextSlc"), ("CISCO-ITP-GSP2-MIB", "cgsp2ContextAsName"), ("CISCO-ITP-GSP2-MIB", "cgsp2ContextAspName"), ("CISCO-ITP-GSP2-MIB", "cgsp2ContextNetworkName")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoGsp2ContextGroup = ciscoGsp2ContextGroup.setStatus('current') if mibBuilder.loadTexts: ciscoGsp2ContextGroup.setDescription('ContextTable object to ciscoGsp2ContextGroup.') mibBuilder.exportSymbols("CISCO-ITP-GSP2-MIB", cgsp2EventMtp3Timestamp=cgsp2EventMtp3Timestamp, cgsp2QosAclId=cgsp2QosAclId, cgsp2OperRedundancy=cgsp2OperRedundancy, cgsp2Events=cgsp2Events, CItpTcContextId=CItpTcContextId, cgsp2LocalPeerPort=cgsp2LocalPeerPort, cgsp2Context=cgsp2Context, ciscoGsp2Mtp3ErrorsGroup=ciscoGsp2Mtp3ErrorsGroup, cgsp2ContextAspName=cgsp2ContextAspName, cgsp2QosType=cgsp2QosType, cgsp2EventAspTableEntry=cgsp2EventAspTableEntry, cgsp2QosIpDscp=cgsp2QosIpDscp, cgsp2ContextLinksetName=cgsp2ContextLinksetName, cgsp2Qos=cgsp2Qos, cgsp2LocalPeerTable=cgsp2LocalPeerTable, cgsp2EventAsName=cgsp2EventAsName, cgsp2EventMtp3Text=cgsp2EventMtp3Text, ciscoGsp2MIB=ciscoGsp2MIB, cgsp2LocalPeerProcessorNumber=cgsp2LocalPeerProcessorNumber, ciscoGsp2MIBCompliances=ciscoGsp2MIBCompliances, cgsp2ContextTable=cgsp2ContextTable, cgsp2LpIpAddressNumber=cgsp2LpIpAddressNumber, cgsp2Mtp3ErrorsType=cgsp2Mtp3ErrorsType, ciscoGsp2MIBComplianceRev4=ciscoGsp2MIBComplianceRev4, cgsp2EventMtp3Table=cgsp2EventMtp3Table, cgsp2EventPcIndex=cgsp2EventPcIndex, cgsp2EventTableEntry=cgsp2EventTableEntry, cgsp2EventMaxEntriesAllowed=cgsp2EventMaxEntriesAllowed, cgsp2ContextNetworkName=cgsp2ContextNetworkName, cgsp2LpIpAddressRowStatus=cgsp2LpIpAddressRowStatus, cgsp2EventAspTimestamp=cgsp2EventAspTimestamp, ciscoGsp2MIBNotifs=ciscoGsp2MIBNotifs, cgsp2EventDroppedEvents=cgsp2EventDroppedEvents, cgsp2OperMtp3Offload=cgsp2OperMtp3Offload, cgsp2EventAsTableEntry=cgsp2EventAsTableEntry, cgsp2EventAsIndex=cgsp2EventAsIndex, cgsp2QosTable=cgsp2QosTable, ciscoGsp2MIBGroups=ciscoGsp2MIBGroups, cgsp2EventAsTable=cgsp2EventAsTable, cgsp2Mtp3ErrorsTableEntry=cgsp2Mtp3ErrorsTableEntry, cgsp2LpIpAddress=cgsp2LpIpAddress, Cgsp2EventIndex=Cgsp2EventIndex, cgsp2EventAspText=cgsp2EventAspText, ciscoGsp2LocalPeerGroup=ciscoGsp2LocalPeerGroup, cgsp2ContextEntry=cgsp2ContextEntry, cgsp2EventTable=cgsp2EventTable, cgsp2ContextSlc=cgsp2ContextSlc, cgsp2QosPrecedenceValue=cgsp2QosPrecedenceValue, cgsp2EventAsTimestamp=cgsp2EventAsTimestamp, cgsp2EventAspName=cgsp2EventAspName, cgsp2ContextIdentifier=cgsp2ContextIdentifier, cgsp2EventMtp3TableEntry=cgsp2EventMtp3TableEntry, ciscoGsp2MIBComplianceRev3=ciscoGsp2MIBComplianceRev3, cgsp2LocalPeer=cgsp2LocalPeer, ciscoGsp2LocalPeerGroupSup1=ciscoGsp2LocalPeerGroupSup1, cgsp2EventPcTable=cgsp2EventPcTable, cgsp2Mtp3Errors=cgsp2Mtp3Errors, cgsp2EventMtp3Index=cgsp2EventMtp3Index, cgsp2EventLoggedEvents=cgsp2EventLoggedEvents, cgsp2EventType=cgsp2EventType, ciscoGsp2MIBComplianceRev2=ciscoGsp2MIBComplianceRev2, cgsp2EventAspIndex=cgsp2EventAspIndex, ciscoGsp2EventsGroup=ciscoGsp2EventsGroup, cgsp2Mtp3ErrorsCount=cgsp2Mtp3ErrorsCount, cgsp2ContextType=cgsp2ContextType, cgsp2LocalPeerTableEntry=cgsp2LocalPeerTableEntry, cgsp2Operation=cgsp2Operation, PYSNMP_MODULE_ID=ciscoGsp2MIB, ciscoGsp2MIBCompliance=ciscoGsp2MIBCompliance, cgsp2EventPcText=cgsp2EventPcText, CItpTcContextType=CItpTcContextType, cgsp2EventMaxEntries=cgsp2EventMaxEntries, cgsp2EventPcTableEntry=cgsp2EventPcTableEntry, cgsp2QosClass=cgsp2QosClass, cgsp2LpIpAddrTableEntry=cgsp2LpIpAddrTableEntry, cgsp2QosRowStatus=cgsp2QosRowStatus, cgsp2Mtp3ErrorsTable=cgsp2Mtp3ErrorsTable, cgsp2EventAsText=cgsp2EventAsText, cgsp2QosTableEntry=cgsp2QosTableEntry, Cgsp2TcQosClass=Cgsp2TcQosClass, cgsp2LpIpAddrTable=cgsp2LpIpAddrTable, cgsp2LpIpAddressType=cgsp2LpIpAddressType, cgsp2EventAspTable=cgsp2EventAspTable, cgsp2ContextAsName=cgsp2ContextAsName, cgsp2Mtp3ErrorsDescription=cgsp2Mtp3ErrorsDescription, ciscoGsp2MIBComplianceRev1=ciscoGsp2MIBComplianceRev1, cgsp2LocalPeerRowStatus=cgsp2LocalPeerRowStatus, cgsp2EventPcTimestamp=cgsp2EventPcTimestamp, ciscoGsp2MIBObjects=ciscoGsp2MIBObjects, cgsp2LocalPeerSlotNumber=cgsp2LocalPeerSlotNumber, ciscoGsp2ContextGroup=ciscoGsp2ContextGroup, ciscoGsp2MIBConform=ciscoGsp2MIBConform, ciscoGsp2QosGroup=ciscoGsp2QosGroup, ciscoGsp2OperationGroup=ciscoGsp2OperationGroup, cgsp2EventPc=cgsp2EventPc)
{ 'targets': [ { 'target_name': 'discount', 'dependencies': [ 'libmarkdown' ], 'sources': [ 'src/discount.cc' ], 'include_dirs': [ 'deps/discount' ], 'libraries': [ 'deps/discount/libmarkdown.a' ] }, { 'target_name': 'libmarkdown', 'type': 'none', 'actions': [ { 'action_name': 'build_libmarkdown', 'inputs': [ 'deps/discount/Csio.c', 'deps/discount/Makefile.in', 'deps/discount/Plan9/markdown.1', 'deps/discount/Plan9/markdown.2', 'deps/discount/Plan9/markdown.6', 'deps/discount/Plan9/mkfile', 'deps/discount/amalloc.c', 'deps/discount/amalloc.h', 'deps/discount/basename.c', 'deps/discount/configure.inc', 'deps/discount/configure.sh', 'deps/discount/css.c', 'deps/discount/cstring.h', 'deps/discount/docheader.c', 'deps/discount/dumptree.c', 'deps/discount/emmatch.c', 'deps/discount/flags.c', 'deps/discount/generate.c', 'deps/discount/github_flavoured.c', 'deps/discount/html5.c', 'deps/discount/main.c', 'deps/discount/makepage.1', 'deps/discount/makepage.c', 'deps/discount/markdown.1', 'deps/discount/markdown.3', 'deps/discount/markdown.7', 'deps/discount/markdown.c', 'deps/discount/markdown.h', 'deps/discount/mkd-callbacks.3', 'deps/discount/mkd-extensions.7', 'deps/discount/mkd-functions.3', 'deps/discount/mkd-line.3', 'deps/discount/mkd2html.1', 'deps/discount/mkd2html.c', 'deps/discount/mkdio.c', 'deps/discount/mkdio.h.in', 'deps/discount/mktags.c', 'deps/discount/pgm_options.c', 'deps/discount/pgm_options.h', 'deps/discount/resource.c', 'deps/discount/setup.c', 'deps/discount/tags.c', 'deps/discount/tags.h', 'deps/discount/tests/autolink.t', 'deps/discount/tests/automatic.t', 'deps/discount/tests/backslash.t', 'deps/discount/tests/callbacks.t', 'deps/discount/tests/chrome.text', 'deps/discount/tests/code.t', 'deps/discount/tests/compat.t', 'deps/discount/tests/crash.t', 'deps/discount/tests/defects.t', 'deps/discount/tests/div.t', 'deps/discount/tests/dl.t', 'deps/discount/tests/embedlinks.text', 'deps/discount/tests/emphasis.t', 'deps/discount/tests/extrafootnotes.t', 'deps/discount/tests/flow.t', 'deps/discount/tests/footnotes.t', 'deps/discount/tests/functions.sh', 'deps/discount/tests/githubtags.t', 'deps/discount/tests/header.t', 'deps/discount/tests/html.t', 'deps/discount/tests/html5.t', 'deps/discount/tests/links.text', 'deps/discount/tests/linkylinky.t', 'deps/discount/tests/linkypix.t', 'deps/discount/tests/list.t', 'deps/discount/tests/list3deep.t', 'deps/discount/tests/misc.t', 'deps/discount/tests/pandoc.t', 'deps/discount/tests/para.t', 'deps/discount/tests/paranoia.t', 'deps/discount/tests/peculiarities.t', 'deps/discount/tests/pseudo.t', 'deps/discount/tests/reddit.t', 'deps/discount/tests/reparse.t', 'deps/discount/tests/schiraldi.t', 'deps/discount/tests/smarty.t', 'deps/discount/tests/snakepit.t', 'deps/discount/tests/strikethrough.t', 'deps/discount/tests/style.t', 'deps/discount/tests/superscript.t', 'deps/discount/tests/syntax.text', 'deps/discount/tests/tables.t', 'deps/discount/tests/tabstop.t', 'deps/discount/tests/toc.t', 'deps/discount/tests/xml.t', 'deps/discount/theme.1', 'deps/discount/theme.c', 'deps/discount/toc.c', 'deps/discount/tools/checkbits.sh', 'deps/discount/tools/cols.c', 'deps/discount/tools/echo.c', 'deps/discount/version.c.in', 'deps/discount/xml.c', 'deps/discount/xmlpage.c' ], 'outputs': [ 'deps/discount/libmarkdown.a' ], 'action': [ 'eval', 'cd deps/discount && ./configure.sh && make libmarkdown' ], 'message': 'Building libmarkdown...' } ] } ] }
class BTNode: def __init__(self, data = -1, left = None, right = None): self.data = data self.left = left self.right = right class BTree: def __init__(self): self.root = None self.is_comp = True self.num = 0 def is_empty(self): return self.root is None def build(self, preorder, inorder): self.num = len(preorder) self.root = self.recover(preorder, inorder) def recover(self, preorder, inorder): root = BTNode(preorder[0]) if len(preorder) == 0 and len(inorder) == 0: return root idx = inorder.index(preorder[0]) if idx > 0: root.left = self.recover(preorder[1:idx+1], inorder[0:idx]) if len(inorder) - idx - 1 > 0: root.right = self.recover(preorder[idx+1:], inorder[idx+1:]) return root def judge(self): queue = [self.root] i = 0 while len(queue): node = queue.pop(0) if node.left: queue.append(node.left) elif 2 * i + 1 < self.num: self.is_comp = False if node.right: queue.append(node.right) elif 2 * i + 2 < self.num: self.is_comp = False i += 1 def main(): preorder = input().split() inorder = input().split() tree = BTree() tree.build(preorder, inorder) tree.judge() if tree.is_comp is True: print("True") else: print("False") main()
load("//dev-infra/bazel/browsers:browser_archive_repo.bzl", "browser_archive") """ Defines repositories for Firefox that can be used inside Karma unit tests and Protractor e2e tests with Bazel. """ def define_firefox_repositories(): # Instructions on updating the Firefox version can be found in the `README.md` file # next to this file. browser_archive( name = "org_mozilla_firefox_amd64", licenses = ["reciprocal"], # MPL 2.0 sha256 = "601e5a9a12ce680ecd82177c7887dae008d8f33690da43be1a690b76563cd992", # Firefox v84.0 url = "https://ftp.mozilla.org/pub/firefox/releases/84.0/linux-x86_64/en-US/firefox-84.0.tar.bz2", named_files = { "FIREFOX": "firefox/firefox", }, ) browser_archive( name = "org_mozilla_firefox_macos", licenses = ["reciprocal"], # MPL 2.0 sha256 = "4c7bca050eb228f4f6f93a9895af0a87473e03c67401d1d2f1ba907faf87fefd", # Firefox v84.0 url = "https://ftp.mozilla.org/pub/firefox/releases/84.0/mac/en-US/Firefox%2084.0.dmg", named_files = { "FIREFOX": "Firefox.app/Contents/MacOS/firefox", }, ) browser_archive( name = "org_mozilla_geckodriver_amd64", licenses = ["reciprocal"], # MPL 2.0 sha256 = "61bfc547a623d7305256611a81ecd24e6bf9dac555529ed6baeafcf8160900da", # Geckodriver v0.28.0 url = "https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-linux64.tar.gz", named_files = { "GECKODRIVER": "geckodriver", }, ) browser_archive( name = "org_mozilla_geckodriver_macos", licenses = ["reciprocal"], # MPL 2.0 sha256 = "c288ff6db39adfd5eea0e25b4c3e71bfd9fb383eccf521cdd65f67ea78eb1761", # Geckodriver v0.28.0 url = "https://github.com/mozilla/geckodriver/releases/download/v0.28.0/geckodriver-v0.28.0-macos.tar.gz", named_files = { "GECKODRIVER": "geckodriver", }, )
class DockablePane(object,IDisposable): """ A user interface pane that participates in Revit's docking window system. DockablePane(other: DockablePane) DockablePane(id: DockablePaneId) """ def Dispose(self): """ Dispose(self: DockablePane) """ pass def GetTitle(self): """ GetTitle(self: DockablePane) -> str Returns the current title (a.k.a. window caption) of the dockable pane. """ pass def Hide(self): """ Hide(self: DockablePane) If the pane is on screen,hide it. Has no effect on built-in Revit dockable panes. """ pass def IsShown(self): """ IsShown(self: DockablePane) -> bool Identify the pane is currently visible or in a tab. """ pass @staticmethod def PaneExists(id): """ PaneExists(id: DockablePaneId) -> bool Returns true if %id% refers to a dockable pane window that currently exists in the Revit user interface,whether it's hidden or shown. """ pass @staticmethod def PaneIsBuiltIn(id): """ PaneIsBuiltIn(id: DockablePaneId) -> bool Returns true if %id% refers to a built-in Revit dockable pane,rather than one created by an add-in. """ pass @staticmethod def PaneIsRegistered(id): """ PaneIsRegistered(id: DockablePaneId) -> bool Returns true if %id% refers to a built-in Revit dockable pane,or an add-in pane that has been properly registered with %Autodesk.Revit.UI.UIApplication.RegisterDockablePane%. """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: DockablePane,disposing: bool) """ pass def Show(self): """ Show(self: DockablePane) If the pane is not currently visible or in a tab,display the pane in the Revit user interface at its last docked location. """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,*__args): """ __new__(cls: type,other: DockablePane) __new__(cls: type,id: DockablePaneId) """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass Id=property(lambda self: object(),lambda self,v: None,lambda self: None) """The unique identifier for this dockable pane. Get: Id(self: DockablePane) -> DockablePaneId """ IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None) """Specifies whether the .NET object represents a valid Revit entity. Get: IsValidObject(self: DockablePane) -> bool """
# Calculating Page rank. class Graph(): def __init__(self): self.linked_node_map = {} self.PR_map = {} def add_node(self, node_id): if node_id not in self.linked_node_map: self.linked_node_map[node_id] = [] self.PR_map[node_id] = 0 def add_link(self, node1, node2, v): if node1 not in self.linked_node_map: self.add_node(node1) if node2 not in self.linked_node_map: self.add_node(node2) # When Inserting links, weights are already divided by sum. self.linked_node_map[node2].append([node1, v]) # Compute Page Rank def get_PR(self, epoch_num=50, d=0.95): for i in range(epoch_num): for node in self.PR_map: self.PR_map[node] = (1 - d) + d * sum( [self.PR_map[temp_node[0]] * temp_node[1] for temp_node in self.linked_node_map[node]]) return self.PR_map
class NavigationValues: navigation_distance = None navigation_time = None speed_limit = None class Movement: value = None kph = None mph = None def calculate_speed(self): self.kph = self.value * 3.6 self.mph = self.value * 2.25 def __init__(self): self.speed_limit = self.Movement()
def generate_board(): # Generate full, randomized sudoku board pass def generate_section(): # generate a randomized, 3x3 seciont of the board pass class SudokuBoard(object): """ """ def __init__(self, difficulty): super().__init__() self._base_size = 3 self._board_length = self._base_size ** 2 self._difficulty = None self.difficulty = difficulty self._max_solves = None @property def difficulty(self): """(int) Higher levels will provide fewer numbers on the board""" return self._difficulty @difficulty.setter def difficulty(self, difficulty): if difficulty < 0 or difficulty > 10: raise ValueError("difficulty must be an integer between 0 and 10") # TODO: This is no good max_grids = self._board_length ** 2 min_provided = 17 # The theoretical minimum to solve the board self._max_solves = int((max_grids - min_provided) * .01 * difficulty) self._difficulty
""" Author: Omkar Pandit Bankar Date: 10/10/2019 Email: [email protected] """
#066_Varios_numeros_com_flag.py j = soma = 0 while True: num = int(input("Entre com um número: ")) if num == 999: break j += 1 soma += num print(f"A soma dos {j} valores é {soma} e a média é {(soma/j):.2f}")
def is_phone_valid(phone: str) -> bool: if ( phone.isnumeric() and phone.startswith(("6", "7", "8", "9")) and len(phone) == 10 ): return True return False
# !/usr/bin/python3 # 集合类型 # 包含的元素不可重复 # 可以进行集合运算 # 集合为无序 varTypeSet = {"0", "1", "2", "3"} varTypeSet1 = {"2", "3", "4", "5"} print(varTypeSet, varTypeSet1) # 差集 print("差集", end=" ") print(varTypeSet - varTypeSet1, end=" ") print(varTypeSet1 - varTypeSet) # 并集 # 错误示例,不能使用+ # print(varTypeSet + varTypeSet1) print("并集", end=" ") print(varTypeSet | varTypeSet1) # 交集 print("交集", end=" ") print(varTypeSet & varTypeSet1) # 差集的并集 print("差集的并集", end=" ") print(varTypeSet ^ varTypeSet1)
""" An encoded string S is given. To find and write the decoded string to a tape, the encoded string is read one character at a time and the following steps are taken: If the character read is a letter, that letter is written onto the tape. If the character read is a digit (say d), the entire current tape is repeatedly written d-1 more times in total. Now for some encoded string S, and an index K, find and return the K-th letter (1 indexed) in the decoded string. Example 1: Input: S = "leet2code3", K = 10 Output: "o" Explanation: The decoded string is "leetleetcodeleetleetcodeleetleetcode". The 10th letter in the string is "o". Example 2: Input: S = "ha22", K = 5 Output: "h" Explanation: The decoded string is "hahahaha". The 5th letter is "h". Example 3: Input: S = "a2345678999999999999999", K = 1 Output: "a" Explanation: The decoded string is "a" repeated 8301530446056247680 times. The 1st letter is "a". Note: 2 <= S.length <= 100 S will only contain lowercase letters and digits 2 through 9. S starts with a letter. 1 <= K <= 10^9 The decoded string is guaranteed to have less than 2^63 letters. """ class Solution: def decodeAtIndex(self, S, K): """ :type S: str :type K: int :rtype: str """ """ Method 1: Time Limit Exceeded """ # current_ptr = 0 # index_ptr = 0 # tape = '' # while index_ptr < len(S): # if S[index_ptr].isalpha(): # tape += S[index_ptr] # elif S[index_ptr].isdigit(): # temp_tape = '' # for _ in range(1,int(S[index_ptr])): # temp_tape += tape # tape += temp_tape # index_ptr += 1 # # print(tape) # return tape[K-1] """ Method 2: 45 / 45 test cases passed. Status: Accepted Runtime: 56 ms """ size = 0 # #Find the size/length of the resultant string for c in S: if c.isdigit(): size *= int(c) else: size += 1 for c in reversed(S): K %= size if K == 0 and c.isalpha(): return c if c.isdigit(): size /= int(c) else: size -= 1
panjang = int(raw_input("masukan panjang: ")) lebar = int(raw_input("masukan lebar: ")) tinggi = int(raw_input("masukan tinggi: ")) volume = panjang * lebar * tinggi print(volume)
class Node: def __init__(self,data): self.data = data self.left = self.right = None def findPreSuc(root, key): # Base Case if root is None: return # If key is present at root if root.data == key: # the maximum value in left subtree is predecessor if root.left is not None: tmp = root.left while(tmp.right): tmp = tmp.right findPreSuc.pre = tmp # the minimum value in right subtree is successor if root.right is not None: tmp = root.right while(tmp.left): tmp = tmp.left findPreSuc.suc = tmp return # If key is smaller than root's key, go to left subtree if root.data > key : findPreSuc.suc = root findPreSuc(root.left, key) else: # go to right subtree findPreSuc.pre = root findPreSuc(root.right, key) def insert(root,key): if root is None: return Node(key) else: if root.data == key: return if key < root.data: root.left = insert(root.left,key) else: root.right = insert(root.right,key) return root ## Driver code...!!!!! if __name__ == "__main__": root = Node(50) root = insert(root,30) root = insert(root,20) root = insert(root,40) root = insert(root,70) root = insert(root,60) root = insert(root,80) ## take input from user to check for predessor and successor.. findPreSuc.pre = None findPreSuc.suc = None key = int(input()) findPreSuc(root, key) if findPreSuc.pre is not None: print ("Predecessor is", findPreSuc.pre.data) else: print ("No Predecessor") if findPreSuc.suc is not None: print ("Successor is", findPreSuc.suc.data) else: print ("No Successor")
"""" This file stores details of the rsvp. """ RVSPS=[] class Rsvp(): class_count = 1 def __init__(self): self.meetup_id = None self.topic = None self.status = None self.rsvp_id = Rsvp.class_count self.user_id = None Rsvp.class_count +=1 def __repr__(self): return "Rsvp '{}'".format(self.status)
STUDENT_NUMBER_STOP = 999 def parse_correct_answers(record): return record.split(" ") def parse_student_answers(record): parsed = record.split(" ") student = int(parsed[0]) if len(parsed) == 1: return (student, None) else: return (student, parsed[1:]) def calculate_marks(correct, answers): points = 0 for i in range(0, len(correct)): if (answers[i] == "x"): points += 0 elif (answers[i] == correct[i]): points += 1 else: points -= 1 return points def process_students_marks(filename): with open(filename, "r") as answers: correct_answers = parse_correct_answers(answers.readline().strip()) student_number = 0 while (student_number != STUDENT_NUMBER_STOP): student_number, student_answers = parse_student_answers(answers.readline().strip()) if student_number == STUDENT_NUMBER_STOP: continue marks = calculate_marks(correct_answers, student_answers) print("{} {} marks".format(student_number, marks)) if __name__ == "__main__": process_students_marks("question4-data.txt")
class Pessoa: olhos = 2 def __init__(self, *filhos, nome=None, idade=29): self.idade = idade self.nome = nome self.filhos = list(filhos) def cumprimentar(self): return f'Olá, meu nome é {self.nome}' @staticmethod def metodo_estatico(): return 42 @classmethod def nome_e_atributos_de_classe(cls): return f'{cls} - olhos {cls.olhos}' class Homem(Pessoa): def cumprimentar(self): cumprimentar_da_classe = super().cumprimentar() return f'{cumprimentar_da_classe}. Aperto de mão' class Mutante(Pessoa): olhos = 3 if __name__ == '__main__': vinicios = Homem(nome='Vinicios') vitoria = Mutante(vinicios, nome='Vitoria') print(Pessoa.cumprimentar(vitoria)) print(id(vitoria)) print(vitoria.cumprimentar()) print(vitoria.nome) print(vitoria.idade) for filho in vitoria.filhos: print(filho.nome) vitoria.sobrenome = 'Alves' del vitoria.filhos vitoria.olhos = 1 del vitoria.olhos print(vitoria.sobrenome) print(vitoria.__dict__) print(vinicios.__dict__) print(Pessoa.olhos) print(vitoria.olhos) print(vinicios.olhos) print(id(Pessoa.olhos), id(vitoria.olhos), id(vinicios.olhos)) print(Pessoa.metodo_estatico(), vitoria.metodo_estatico(), vinicios.metodo_estatico()) print(Pessoa.nome_e_atributos_de_classe(), vitoria.nome_e_atributos_de_classe(), vinicios.nome_e_atributos_de_classe()) pessoa = Pessoa('Anonimo') print(isinstance(pessoa, Pessoa)) print(isinstance(pessoa, Homem)) print(isinstance(vitoria, Pessoa)) print(isinstance(vitoria, Homem)) print(isinstance(vitoria, Mutante)) print(vitoria.olhos) print(vitoria.cumprimentar()) print(vinicios.cumprimentar())
# Copyright 2021 The Fraud Detection Framework Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND< either express or implied. See the # License for the specific language governing permissions and limitations under # the License. REQUEST_TIMEOUT = (60, 180) MESSAGE_TYPE_INFO = 5 MESSAGE_TYPE_WARNING = 4 MESSAGE_TYPE_ERROR = 3 DB_CONNECTION_STRING = 'postgresql://postgres:password@localhost:5432/fdf' EXCEPTION_WAIT_SEC = 5 SETTING_STATUS_NAME = 'status' SETTING_STATUS_PROCESSING = 'processing' SETTING_STATUS_STOPPED = 'stopped' SETTING_STATUS_RELOAD = 'reload' SETTING_STATUS_CLEAN = 'clean' SETTING_STATUS_PREPARING = 'preparing' SETTING_STATUS_PREPARED = 'prepared' SETTING_STATUS_PAUSED = 'paused' SETTING_REFRESH_DATA_NAME = 'refreshData' SETTING_REFRESH_DATA_TRUE = '1' SETTING_REFRESH_DATA_FALSE = '0' DATA_FOLDER = 'Data' TF_LOG_LEVEL = "2" TYPE_PHOTO_FRAUD_DETECTION = 1 FDF_PYD_PATH = "./fdf" STATUS_NONE = 0 STATUS_COMPLETED = 1
def czynniki_pierwsze(num: int) -> []: factors = [] k = 2 while num > 1: while num % k == 0: factors.append(k) num = num // k k = k + 1 return factors
tmp=input('请输入你要转换的分钟数:') mins=int(tmp)*60 print('%s分钟等于%s秒'%(tmp,mins))
versions = {} def get_by_vid(vid): return versions[vid] def get_by_package(package, version_mode, vid): if not in_cache(package, version_mode, vid): return None return versions[vid][package + version_mode] def in_cache(package, version_mode, vid): package_str = package + version_mode return vid in versions and package_str in versions[vid] def set_package(package, version_mode, vid, version): if (vid not in versions): versions[vid] = {} versions[vid][package + version_mode] = version