content
stringlengths
7
1.05M
test_input_1 = """\ 8 8 WBWBWBWB BWBWBWBW WBWBWBWB BWBBBWBW WBWBWBWB BWBWBWBW WBWBWBWB BWBWBWBW """ test_input_2 = """\ 10 13 BBBBBBBBWBWBW BBBBBBBBBWBWB BBBBBBBBWBWBW BBBBBBBBBWBWB BBBBBBBBWBWBW BBBBBBBBBWBWB BBBBBBBBWBWBW BBBBBBBBBWBWB WWWWWWWWWWBWB WWWWWWWWWWBWB """ test_input_3 = """\ 8 8 BWBWBWBW WBWBWBWB BWBWBWBW WBWBWBWB BWBWBWBW WBWBWBWB BWBWBWBW WBWBWBWB """ test_input_4 = """\ 9 23 BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBW """ # ERROR CASE test_input_7 = """\ 11 12 BWWBWWBWWBWW BWWBWBBWWBWW WBWWBWBBWWBW BWWBWBBWWBWW WBWWBWBBWWBW BWWBWBBWWBWW WBWWBWBBWWBW BWWBWBWWWBWW WBWWBWBBWWBW BWWBWBBWWBWW WBWWBWBBWWBW """ START_WITH_B = "BWBWBWBW" START_WITH_W = "WBWBWBWB" def get_count_diff_two_length8_string(str1, str2): count = 0 for i in range(0,8): if str1[i] != str2[i]: count += 1 return count M, N = input().split() M, N = map(int, (M, N)) input_array = [] for i in range(0, M): input_array.append(input()) number_of_possible_case = (M-7) * (N-7) MAX = 100000000000 min_upperleft_black_counter = MAX min_upperleft_white_counter = MAX flag = True for i in range(0, M-7): test_board = input_array[i:i+8] for j in range(0, N-7): upperleft_black_counter = 0 upperleft_white_counter = 0 for row in range(0, 8): if flag == True: upperleft_black_counter += get_count_diff_two_length8_string(START_WITH_B, test_board[row][j:j+8]) upperleft_white_counter += get_count_diff_two_length8_string(START_WITH_W, test_board[row][j:j+8]) else: upperleft_white_counter += get_count_diff_two_length8_string(START_WITH_B, test_board[row][j:j+8]) upperleft_black_counter += get_count_diff_two_length8_string(START_WITH_W, test_board[row][j:j+8]) flag = not(flag) if min_upperleft_black_counter > upperleft_black_counter: min_upperleft_black_counter = upperleft_black_counter if min_upperleft_white_counter > upperleft_white_counter: min_upperleft_white_counter = upperleft_white_counter if min_upperleft_black_counter > min_upperleft_white_counter: print(min_upperleft_white_counter) else: print(min_upperleft_black_counter)
"""Exercício Python 62: Melhore o DESAFIO 61; pergunte para o usuário se ele quer mostrar mais alguns termos. O programa encerrará quando ele disser que quer mostrar 0 termos.""" # dados do usuário primeiro = int(input('Primeiro termo: ')) razao = int(input('Razão da PA: ')) # variáveis termo = primeiro contador = 1 total = 0 mais = 10 # estruturas aninhadas - while dentro de while while mais != 0: total += mais while contador <= total: print('{} ➞ '.format(termo), end='') termo += razao contador += 1 print('PAUSA') mais = int(input('Quantos termos você quer a mais: ')) print('Progressão finalizada com {} termos exibidos.'.format(contador - 1)) # Guanabara: total
# Write a small program to ask for a name and an age. # When both values have been entered, check if the person # is the right age to go on an 18-30 holiday (they must be # over 18 and under 31). # If they are, welcome them to the holiday, otherwise print # a (polite) message refusing them entry. name = input("Please enter your name: ") age = int(input("How old are you, {0}? ".format(name))) # if 18 <= age < 31: if age >=18 and age <31: print("Welcome to club 18-30 holidays, {0}".format(name)) else: print("I'm sorry, our holidays are only for seriously cool people")
class Phone: def __init__(self, str): str = ''.join([x for x in str if x in '0123456789']) if len(str) == 10: self.number = str elif len(str) == 11 and str[0] == '1': self.number = str[1:] else: raise ValueError('bad format') self.area_code = self.number[:3] if self.area_code[:1] in '01': raise ValueError('bad area code') self.exchange_code = self.number[3:6] if self.exchange_code[:1] in '01': raise ValueError('bad exchange code') def pretty(self): return '({}) {}-{}'.format(self.area_code, self.exchange_code, self.number[-4:])
ABI_ENDPOINT = "https://api.etherscan.io/api?module=contract&action=getabi&address=" POLYGON_ABI_ENDPOINT = ( "https://api.polygonscan.com/api?module=contract&action=getabi&address=" ) ENDPOINT = "" POLYGON_ENDPOINT = "" ATTRIBUTES_FOLDER = "raw_attributes" IMPLEMENTATION_SLOT = ( "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc" ) IPFS_GATEWAY = ""
# Crie um programa que leia quanto dinheiro uma pessoa tem na carteira e mostre quantos dólares ela pode comprar: # Considerando: # USD 1.00 = R$ 5.40 real = float(input('\nQuanto dinheiro você tem na carteira? \nR$ ')) dolar = real / 5.40 print('Com R$ {:.2f} você pode comprar USD {:.2f}\n'.format(real, dolar))
studentdata = {} alldata = [] studentdata['Name'] = str(input("Type the Student's name: ")) studentdata['AVGRADE'] = float(input("Type the Average Grade of the Student: ")) if studentdata['AVGRADE'] < 5: studentdata['Situation'] = ("Reproved") elif studentdata['AVGRADE'] > 5 and studentdata['AVGRADE'] < 7: studentdata['Situation'] = ("Recuperation") else: studentdata['Situation'] = ("Aproved") alldata.append(studentdata.copy()) for x in alldata: for k,v in x.items(): print(f"The {k} is equal to: {v}")
# -*- coding: utf-8 -*- f = open(filename) char = f.read(1) while char: process(char) char = f.read(1) f.close()
b = str(input()).split() d = int(b[0]) c= int(b[1]) e = '.|.' for i in range(1,d,2): print((e*i).center(c,'-')) print(('WELCOME').center(c,'-')) for i in range(d-2,-1,-2): print((e * i).center(c, '-'))
LANGUAGE_CODE = 'ru-RU' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True
fila1="abcdefghi" fila2="jklmnopqr" fila3="stuvwxyz" n=int(input()) for i in range(0,n): flag=True palabras=input() palabras=palabras.strip().split() if (len(palabras[0])==len(palabras[1])): if (palabras[0]==palabras[1]): print("1") pass else: for j in range(0,len(palabras[0])): if palabras[0][j] in fila1: temp=fila1.find(palabras[0][j]) if temp==0: if palabras[1][j]==fila1[temp] or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1]: pass else: flag=False break elif temp==8: if palabras[1][j]==fila1[temp] or palabras[1][j]==fila1[temp-1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp-1]: pass else: flag=False break else: if palabras[1][j]==fila1[temp] or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1] or palabras[1][j]==fila1[temp-1] or palabras[1][j]==fila2[temp-1]: pass else: flag=False break elif palabras[0][j] in fila2: temp=fila2.find(palabras[0][j]) if temp==0: if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp+1]or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila3[temp+1]: pass else: flag=False break elif temp==8: if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila2[temp-1]or palabras[1][j]==fila1[temp-1] or palabras[1][j]==fila3[temp-1]: pass else: flag=False break elif temp==7: if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp+1]or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila3[temp-1]or palabras[1][j]==fila2[temp-1]or palabras[1][j]==fila1[temp-1]: pass else: flag=False break else: if palabras[1][j]==fila2[temp] or palabras[1][j]==fila1[temp] or palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp+1]or palabras[1][j]==fila1[temp+1] or palabras[1][j]==fila3[temp+1] or palabras[1][j]==fila3[temp-1]or palabras[1][j]==fila2[temp-1]or palabras[1][j]==fila1[temp-1]: pass else: flag=False break elif palabras[0][j] in fila3: temp=fila3.find(palabras[0][j]) if temp==0: if palabras[1][j]==fila3[temp] or palabras[1][j]==fila3[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1]: pass else: flag=False break if temp==7: if palabras[1][j]==fila3[temp] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1] or palabras[1][j]==fila3[temp-1] or palabras[1][j]==fila2[temp-1]: pass else: flag=False break else: if palabras[1][j]==fila3[temp] or palabras[1][j]==fila3[temp+1] or palabras[1][j]==fila2[temp] or palabras[1][j]==fila2[temp+1] or palabras[1][j]==fila3[temp-1] or palabras[1][j]==fila2[temp-1]: pass else: flag=False break if flag: print("2") pass else: print("3") pass else: print("3") pass
# Which of the following expressions return the infinity values? # Suppose, the variables inf and nan have been defined. nan = float("nan") inf = float("inf") print(0.0 / inf) # nan print(inf / 2 - inf) # inf print(100 * inf + nan) # inf print(inf - 10 ** 300) # nan print(-inf * inf) # inf # print(inf % 0.0)
# Crie um programa que leia nome, sexo e idade de várias pessoas, # guardando os dados de cada pessoa em um dicionário e todos os # dicionários em uma lista. No final, mostre: # # A) Quantas pessoas foram cadastradas # B) A média de idade # C) Uma lista com as mulheres # D) Uma lista de pessoas com idade acima da média pessoa = dict() conj_pessoas = list() i = 0 while True: print(f'Pessoa {i+1}: ') pessoa['nome'] = input('Nome: ') pessoa['sexo'] = input('Sexo: ') pessoa['idade'] = int(input('Idade: ')) conj_pessoas.append(pessoa.copy()) pessoa.clear() op = input('Deseja adicionar mais uma pessoa? (S / N): ') if op in 'Nn': break i += 1 print(f'\nPessoas cadastradas: {len(conj_pessoas)}') lista_mulheres = list() soma_idades = 0 for c in range(0, len(conj_pessoas)): soma_idades += conj_pessoas[c]['idade'] if conj_pessoas[c]['sexo'] in 'Ff': lista_mulheres.append(conj_pessoas[c].copy()) media = soma_idades/len(conj_pessoas) print(f'Média de idades: {media}') print('Mulheres: ', end='') for c in range(0, len(lista_mulheres)): print(f'{lista_mulheres[c]["nome"]}', end='...') lista_idades_acima_media = list() for c in range(0, len(conj_pessoas)): if conj_pessoas[c]['idade'] > media: lista_idades_acima_media.append(conj_pessoas[c].copy()) print('\nPessoas com idade acima da média: ', end='') for c in range(0, len(lista_idades_acima_media)): print(f'{lista_idades_acima_media[c]["nome"]}', end='...')
lines = open('input.txt', 'r').readlines() # create graph node_hash_list = dict() node_hash_list["start"] = set() for line in lines: p1, p2 = line.strip().split("-") if p2 not in node_hash_list: node_hash_list[p2] = set() if p1 not in node_hash_list: node_hash_list[p1] = set() if not p1 == "end" and not p2 == "start": node_hash_list[p1].add(p2) if not p2 == "end" and not p1 == "start": node_hash_list[p2].add(p1) # traverse graph PART ONE possible_paths = list() path1 = ["start"] possible_paths.append(path1) flag_paths_updated = True while flag_paths_updated: flag_paths_updated = False for path in possible_paths.copy(): if path[-1] == "end": continue # ignore # try to find next move for nextStep in node_hash_list[path[-1]]: copyPath = [p for p in path] if nextStep not in path or nextStep.isupper(): # append path copyPath.append(nextStep) flag_paths_updated = True possible_paths.append(copyPath) possible_paths.remove(path) print("Part 1: ", len(possible_paths)) # PART TWO def small_cave_one_more_visit_allowed(path, nextStep): if nextStep == "end": return True small_caves = set() for name in path: if name.isupper(): continue if name in small_caves: return nextStep not in path small_caves.add(name) return True # traverse graph PART Two possible_paths = list() possible_paths.append(["start"]) possible_path_counter = 0 flag_paths_updated = True while flag_paths_updated: flag_paths_updated = False for path in possible_paths.copy(): if path[-1] == "end": possible_path_counter += 1 possible_paths.remove(path) continue # ignore # try to find next move for nextStep in node_hash_list[path[-1]]: copyPath = [p for p in path] if nextStep.isupper() or small_cave_one_more_visit_allowed(copyPath, nextStep): # append path copyPath.append(nextStep) flag_paths_updated = True possible_paths.append(copyPath) possible_paths.remove(path) print("Paths: ", possible_path_counter)
KEY_TO_SYM = { "ArrowLeft": "Left", "ArrowRight": "Right", "ArrowUp": "Up", "ArrowDown": "Down", "BackSpace": "BackSpace", "Tab": "Tab", "Enter": "Return", # 'Shift': 'Shift_L', # 'Control': 'Control_L', # 'Alt': 'Alt_L', "CapsLock": "Caps_Lock", "Escape": "Escape", " ": "space", "PageUp": "Prior", "PageDown": "Next", "Home": "Home", "End": "End", "Delete": "Delete", "Insert": "Insert", "*": "asterisk", "+": "plus", "|": "bar", "-": "minus", ".": "period", "/": "slash", "F1": "F1", "F2": "F2", "F3": "F3", "F4": "F4", "F5": "F5", "F6": "F6", "F7": "F7", "F8": "F8", "F9": "F9", "F10": "F10", "F11": "F11", "F12": "F12", } INTERACTION_THROTTLE = 100
#!/usr/bin/env python #coding: utf-8 # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of integers def postorderTraversal(self, root): if not root: return [] leftL = self.postorderTraversal(root.left) rightL = self.postorderTraversal(root.right) return leftL + rightL + [root.val]
{ "cells": [ { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "append: 0.09872150200000007\n", "concat: 0.10876064500000027\n", "unpack: 0.14667600099999945\n" ] } ], "source": [ "from timeit import timeit\n", "\n", "append = \"\"\"\n", "array1 = [0, 1, 2]\n", "array1.append(3)\n", "\"\"\"\n", "concat = \"\"\"\n", "array2 = [0, 1, 2]\n", "array2 += [3]\n", "\"\"\"\n", "unpack = \"\"\"\n", "array3 = [0, 1, 2]\n", "array3 = [*array3, 3]\n", "\"\"\"\n", "\n", "print(f\"append: {timeit(append)}\")\n", "print(f\"concat: {timeit(concat)}\")\n", "print(f\"unpack: {timeit(unpack)}\")" ] } ], "metadata": { "interpreter": { "hash": "31f2aee4e71d21fbe5cf8b01ff0e069b9275f58929596ceb00d14d90e3e16cd6" }, "kernelspec": { "display_name": "Python 3.8.2 64-bit", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.12" }, "orig_nbformat": 4 }, "nbformat": 4, "nbformat_minor": 2 }
""" CM, your case/content management system for the internet. Copyright Alex Li 2003. Package structure: cm/ html/ (UI subpackages...) htmllib/ (HTML frontend shared library) model/ (Business Domain subpackages) ... (framework modules...such as database access, security/permission checking, session management) config.py (the configuration file of this web application... Currently it is application-specific AND client-specific) """ __copyright__="" __version__="0.8.4" __date__="2003-08-27"
def method1(): a = [1, 2, 3, 4, 5] for _ in range(1): f = a[0] for j in range(0, len(a) - 1): a[j] = a[j + 1] a[len(a) - 1] = f return a if __name__ == "__main__": """ from timeit import timeit print(timeit(lambda: method1(), number=10000)) 0.008410404003370786 """
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def nodesBetweenCriticalPoints(self, head: Optional[ListNode]) -> List[int]: # init if head: p1 = head p2 = p1.next else: return [-1, -1] if p2: p3 = p2.next else: return [-1, -1] if not p3: return [-1, -1] ind = 1 criticalPoints = [] # loop all nodes while p3: if p1.val > p2.val and p3.val > p2.val: criticalPoints.append(ind) if p1.val < p2.val and p3.val < p2.val: criticalPoints.append(ind) # update nodes tmp3 = p3 tmp2 = p2 p3 = tmp3.next p2 = tmp3 p1 = tmp2 ind += 1 # check criticalPoints to return if len(criticalPoints) < 2: return [-1, -1] else: maxD = criticalPoints[-1] - criticalPoints[0] minD = maxD for i in range(1, len(criticalPoints)): if criticalPoints[i] - criticalPoints[i-1] < minD: minD = criticalPoints[i] - criticalPoints[i-1] return [minD, maxD]
STOP_WORDS = set( """ a acuerdo adelante ademas además afirmó agregó ahi ahora ahí al algo alguna algunas alguno algunos algún alli allí alrededor ambos ante anterior antes apenas aproximadamente aquel aquella aquellas aquello aquellos aqui aquél aquélla aquéllas aquéllos aquí arriba aseguró asi así atras aun aunque añadió aún bajo bastante bien breve buen buena buenas bueno buenos cada casi cierta ciertas cierto ciertos cinco claro comentó como con conmigo conocer conseguimos conseguir considera consideró consigo consigue consiguen consigues contigo contra creo cual cuales cualquier cuando cuanta cuantas cuanto cuantos cuatro cuenta cuál cuáles cuándo cuánta cuántas cuánto cuántos cómo da dado dan dar de debajo debe deben debido decir dejó del delante demasiado demás dentro deprisa desde despacio despues después detras detrás dia dias dice dicen dicho dieron diez diferente diferentes dijeron dijo dio doce donde dos durante día días dónde e el ella ellas ello ellos embargo en encima encuentra enfrente enseguida entonces entre era eramos eran eras eres es esa esas ese eso esos esta estaba estaban estado estados estais estamos estan estar estará estas este esto estos estoy estuvo está están excepto existe existen explicó expresó él ésa ésas ése ésos ésta éstas éste éstos fin final fue fuera fueron fui fuimos gran grande grandes ha haber habia habla hablan habrá había habían hace haceis hacemos hacen hacer hacerlo haces hacia haciendo hago han hasta hay haya he hecho hemos hicieron hizo hoy hubo igual incluso indicó informo informó ir junto la lado largo las le les llegó lleva llevar lo los luego mal manera manifestó mas mayor me mediante medio mejor mencionó menos menudo mi mia mias mientras mio mios mis misma mismas mismo mismos modo mucha muchas mucho muchos muy más mí mía mías mío míos nada nadie ni ninguna ningunas ninguno ningunos ningún no nos nosotras nosotros nuestra nuestras nuestro nuestros nueva nuevas nueve nuevo nuevos nunca o ocho once os otra otras otro otros para parece parte partir pasada pasado paìs peor pero pesar poca pocas poco pocos podeis podemos poder podria podriais podriamos podrian podrias podrá podrán podría podrían poner por porque posible primer primera primero primeros pronto propia propias propio propios proximo próximo próximos pudo pueda puede pueden puedo pues qeu que quedó queremos quien quienes quiere quiza quizas quizá quizás quién quiénes qué realizado realizar realizó repente respecto sabe sabeis sabemos saben saber sabes salvo se sea sean segun segunda segundo según seis ser sera será serán sería señaló si sido siempre siendo siete sigue siguiente sin sino sobre sois sola solamente solas solo solos somos son soy su supuesto sus suya suyas suyo suyos sé sí sólo tal tambien también tampoco tan tanto tarde te temprano tendrá tendrán teneis tenemos tener tenga tengo tenido tenía tercera tercero ti tiene tienen toda todas todavia todavía todo todos total tras trata través tres tu tus tuvo tuya tuyas tuyo tuyos tú u ultimo un una unas uno unos usa usais usamos usan usar usas uso usted ustedes última últimas último últimos va vais vamos van varias varios vaya veces ver verdad verdadera verdadero vez vosotras vosotros voy vuestra vuestras vuestro vuestros y ya yo """.split() )
def maak_fizzbuzz(n): """Zie ook: https://en.wikipedia.org/wiki/Fizz_buzz""" for getal in range(1, n+1): if getal % 3 == 0 and getal % 5 == 0: print("FizzBuzz") elif getal % 3 == 0: print("Fizz") elif getal % 5 == 0: print("Buzz") else: print(getal) maak_fizzbuzz(20)
# posts model # create an empty list posts=[] def posts_db(): return posts
while True: try: n, inSeq = int(input()), input().split() inSeq = ''.join(inSeq) stack = '' def outSeq(inSeq, stack): if len(inSeq) == 0: return [''.join(reversed(stack))] if len(stack) == 0: outLater = outSeq(inSeq[1: ], stack + inSeq[0]) return outLater else: head = stack[-1] outNow = [head+x for x in outSeq(inSeq, stack[ :-1]) if len(x)!=0] outLater = outSeq(inSeq[1: ], stack + inSeq[0]) return outNow + outLater r = outSeq(inSeq, stack) # print(len(r)) r = [' '.join(list(x)) for x in r] print('\n'.join(r)) except: break
GET_USERS = "SELECT users FROM all_users WHERE user_id = '{}'" CREATE_MAIN_TABLE = "CREATE TABLE all_users(user_id text NOT NULL, users text NOT NULL);" ADD_USER = "UPDATE all_users SET users = '{}' WHERE user_id = '{}'" CREATE_USER = "INSERT INTO all_users (user_id, users) VALUES ('{}', ' ')" GET_ALL_IDS = "SELECT user_id from all_users"
class Extractor: def __str__(self): return self.__class__.__name__ class ExtractByCommand(Extractor): def feed(self, command): if not hasattr(self, command['type']): return getattr(self, command['type'])(command)
REGISTERED_METHODS = [ "ACL", "BASELINE-CONTROL", "BIND", "CHECKIN", "CHECKOUT", "CONNECT", "COPY", "DELETE", "GET", "HEAD", "LABEL", "LINK", "LOCK", "MERGE", "MKACTIVITY", "MKCALENDAR", "MKREDIRECTREF", "MKWORKSPACE", "MOVE", "OPTIONS", "ORDERPATCH", "PATCH", "POST", "PRI", "PROPFIND", "PUT", "QUERY", "REBIND", "REPORT", "SEARCH", "TRACE", "UNBIND", "UNCHECKOUT", "UNLINK", "UNLOCK", "UPDATE", "UPDATEREDIRECTREF", "VERSION-CONTROL", ]
"""Linked list module.""" class Node: """Node of a linked list.""" def __init__(self, value, next = None): self.value = value self.next = next class LinkedList: """Linked List data structure.""" def __init__(self, head = None): self.head = head def __iter__(self): """Make this class iterable implementing the "__next__" method.""" self.iter_current = self.head return self def __next__(self): """Get next element while iterating. Must raise "StopIteration" after the last element.""" if self.iter_current is not None: node = self.iter_current self.iter_current = self.iter_current.next return node else: raise StopIteration # def __iter__(self): # """Make this class iterable using a generator.""" # current = self.head # while current is not None: # yield current # current = current.next def insert(self, value): """Insert a new value to the linked list.""" self.head = Node(value, self.head) def size(self): """Get the number of elements in the linked list at the head.""" count = 0 current = self.head while current is not None: count += 1 current = current.next return count def get_head(self): """Get the head node.""" return self.head def get_tail(self): """Get the tail node.""" if self.head is None: return None current = self.head while current.next is not None: current = current.next return current def clear(self): """Empty the linked list.""" self.head = None def remove_head(self): """Remove the head node.""" if self.head is not None: self.head = self.head.next def remove_tail(self): """Remove the tail node.""" if self.head is None: return if self.head.next is None: self.head = None return previous = self.head current = self.head.next while current.next is not None: previous = current current = current.next previous.next = None def insert_tail(self, value): """Insert a new value to the linked list at the tail.""" node = Node(value) tail = self.get_tail() if tail is None: self.head = node else: tail.next = node def get_at(self, index): """Get the element at the specified index.""" count = 0 current = self.head while current is not None: if count == index: return current current = current.next count += 1 return None def remove_at(self, index): """Remove the element at the specified index.""" if self.head is None: return if index == 0: self.head = self.head.next previous = self.get_at(index - 1) if previous is None or previous.next is None: return previous.next = previous.next.next def insert_at(self, index, value): """Insert a new value to the linked list at the specified index.""" if self.head is None or index == 0: self.head = Node(value, self.head) return # Get the node before the specified index or, if it not exists, at the tail. previous = self.get_at(index - 1) or self.get_tail() previous.next = Node(value, previous.next)
pessoa = {} lista = [] toti = m = 0 while True: pessoa.clear() pessoa['nome'] = str(input('Nome: ')).strip().capitalize() while True: pessoa['sexo'] = str(input('Sexo: [M/F] ')).strip().lower()[0] if pessoa['sexo'] in 'mf': break print('ERRO! por favor, digite apenas M ou F.') pessoa['idade'] = int(input('Idade: ')) toti += pessoa['idade'] lista.append(pessoa.copy()) op = ' ' while op not in 'sn': op = str(input('Quer continuar? ')).lower()[0] if op == 'n': print('-='*30) print(lista) print(f'- O grupo tem {len(lista)} pessoas.') m = toti / len(lista) print(f'- A média de idade é de {m:5.2f} anos.') print('- As mulheres cadastradas foram: ', end='') for p in lista: if p['sexo'] in 'f': print(f'{p["nome"]} ', end='/') print() print('- Lista das pessoas que estão acima da média: ', end='') for p in lista: if p['idade'] >= m: print(' ', end='') for k, v in p.items(): print(f'{k} = {v}; ', end='') print() break print('<< ENCERRADO >>')
# coding=utf-8 """Self organizing list (transpose method) Python implementation.""" class Node: def __init__(self, key, val): self.key = key self.val = val self.next = None class SelfOrganizingList: def __init__(self): self.first = None def add_node(self, key, val): if self.first: prev = None current = self.first while current: prev = current current = current.next prev.next = Node(key, val) else: self.first = Node(key, val) def get_node(self, key): prev = None prevprev = None current = self.first while current.key != key: prevprev = prev prev = current current = current.next if prevprev: prevprev.next = current prev.next = current.next current.next = prev return current.val def get_items(self): current = self.first items = [] while current: items.append(current.val) current = current.next return items if __name__ == "__main__": sol = SelfOrganizingList() for x in range(100): sol.add_node(x, x) print(sol.get_items()) for x in range(100): sol.get_node(x % 15) print(sol.get_items()) for x in range(100): sol.get_node(12) print(sol.get_items())
def open_file(): '''Remember to put a docstring here''' while True: file_name = input("Input a file name: ") try: fp = open(file_name) break except FileNotFoundError: print("Unable to open file. Please try again.") continue return fp def main(): count = [0 for i in range(9)] percentages = [0 for i in range(9)] expected_percentages = ['30.1','17.6','12.5','9.7','7.9','6.7','5.8','5.1','4.6'] fp = open_file() for line in fp: line = line.strip() try: number = int(line) except (TypeError, ValueError): pass try: number = int(str(line[0])) except ValueError: pass index = number - 1 count[index]+= 1 line_count = sum(count) print("Digit Percent Benford") for x in range(len(count)): percentages[x] = (count[x]/line_count)*100 print("{:3s} {:>10.1f}% ({:>5s}%) ".format(str(x+1)+":",percentages[x],expected_percentages[x])) main()
class C(object): """Silly example!!!""" def __init__(self): """XXXX""" self._x = None def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") # class property([fget[, fset[, fdel[, doc]]]]) c = C() c.x = 10 # setx print(C.x.__doc__) class C(object): def __init__(self): self._x = None @property def x(self): """I'm the 'x' property.""" return self._x @x.setter def x(self, value): self._x = value @x.deleter def x(self): del self._x c = C() # c.x = 10 # setx print(c.x) # getx # del c.x # delx c.x = 'HELEN' print(C.x.__doc__) # no need instance
# # https://projecteuler.net/problem=4 # # Largest palindrome product # Problem 4 # # A palindromic number reads the same both ways. # The largest palindrome made from the product of two 2-digits numers is 9009 = 91 x 99. # Find the largest palindrome made from the product of two 3-digit numbers. # Solution def reverse(a_string): new_string = '' index = len(a_string) while index: index -= 1 # index = index - 1 new_string += a_string[index] # new_string = new_string + character return new_string def isPalindrome(value): s = str(value) # return s == s[::-1] #It is not valid in Micro Python return s == reverse(s) def problem(limit): maxPalindrome = 0 for x in range(limit): for y in range(limit): value = x * y if isPalindrome(value): if (value > maxPalindrome): # print(value) maxPalindrome = value return maxPalindrome # Asserts print(reverse("demo") == "omed") print(isPalindrome(9008) == False) print(isPalindrome(9009) == True) print(problem(100) == 9009) # print(problem(1000) == 906609) #Computational issues for TI-84
class Player: """ Defines all character related attributes. Used by scripts.py. """ day = 0 timeofday = 6 stats = { 'name': 'Player', 'health': 100, 'speed': 1, 'intelligence': 1, 'rads': 0, } inventory = { 'money': 0, 'food': 10, 'water': 10 } skills = {} buildings = {'shelter': 0, 'shed': 0, 'corral': 0, 'workshop': 0, 'outpost': 0, 'barricade': 0, 'turret': 0, 'farm': 0, }
class ItemModel: def __init__(self): self.vowels = ['A', 'E', 'I', 'O', 'U'] self.rare_letters = ['X', 'J'] self.other_letters = ['B', 'C', 'D', 'F', 'G', 'H', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'Y', 'Z'] self.items = [ {"id": 1, "name": "A", 'costs': {'amount': 1}, "affects": {}}, {"id": 2, "name": "B", 'costs': {'amount': 1}, "affects": {}}, {"id": 3, "name": "C", 'costs': {'amount': 1}, "affects": {}}, {"id": 4, "name": "D", 'costs': {'amount': 1}, "affects": {}}, {"id": 5, "name": "E", 'costs': {'amount': 1}, "affects": {}}, {"id": 6, "name": "F", 'costs': {'amount': 1}, "affects": {}}, {"id": 7, "name": "G", 'costs': {'amount': 1}, "affects": {}}, {"id": 8, "name": "H", 'costs': {'amount': 1}, "affects": {}}, {"id": 9, "name": "I", 'costs': {'amount': 1}, "affects": {}}, {"id": 10, "name": "J", 'costs': {'amount': 1}, "affects": {}}, {"id": 11, "name": "K", 'costs': {'amount': 1}, "affects": {}}, {"id": 12, "name": "L", 'costs': {'amount': 1}, "affects": {}}, {"id": 13, "name": "M", 'costs': {'amount': 1}, "affects": {}}, {"id": 14, "name": "N", 'costs': {'amount': 1}, "affects": {}}, {"id": 15, "name": "O", 'costs': {'amount': 1}, "affects": {}}, {"id": 16, "name": "P", 'costs': {'amount': 1}, "affects": {}}, {"id": 17, "name": "Q", 'costs': {'amount': 1}, "affects": {}}, {"id": 18, "name": "R", 'costs': {'amount': 1}, "affects": {}}, {"id": 19, "name": "S", 'costs': {'amount': 1}, "affects": {}}, {"id": 20, "name": "T", 'costs': {'amount': 1}, "affects": {}}, {"id": 21, "name": "U", 'costs': {'amount': 1}, "affects": {}}, {"id": 22, "name": "V", 'costs': {'amount': 1}, "affects": {}}, {"id": 23, "name": "W", 'costs': {'amount': 1}, "affects": {}}, {"id": 24, "name": "X", 'costs': {'amount': 1}, "affects": {}}, {"id": 25, "name": "Y", 'costs': {'amount': 1}, "affects": {}}, {"id": 26, "name": "Z", 'costs': {'amount': 1}, "affects": {}} ]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Python for AHDA. Part 4, Example 1. Please rename: 'sample_thomas_moore_download.txt' to: 'Moore.txt' """ # Cut a subset of a file F_IN = 'Moore.txt' F_106 = 'Moore_106.txt' F_4170 = 'Moore_4170.txt' # by slicing a string with open(F_IN, 'r', encoding='utf-8', newline='\n') as f_in: raw_text = f_in.read() with open(F_4170, 'w', encoding='utf-8', newline='\n') as f_out: f_out.write(raw_text[:4170]) # alternative by looping through lines with open(F_IN, 'r', encoding='utf-8', newline='\n') as f_in: lines = f_in.readlines() with open(F_106, 'w', encoding='utf-8', newline='\n') as f_out: for i, line in enumerate(lines, start=1): f_out.write(line) if i == 106: break
#-*-coding:utf-8-*- def bmi(w, h): bmi = (w/(h**2))*10000.0 if bmi<15.0 : str = "VSU" elif bmi<16.0: str = "SUN" elif bmi<18.5: str = "UND" elif bmi<25.0: str = "NOR" elif bmi<30.0: str = "OVE" elif bmi<35.0: str = "MOV" elif bmi<40.0: str = "SOV" else: str = "VSO" return str def main(): weight = float(input()) height = float(input()) print(bmi(weight, height)) if __name__ == '__main__': main()
""" Add riverwalls to the domain Gareth Davies, Geoscience Australia 2014+ """ def setup_riverwalls(domain, project): # ######################################################################### # # Add Riverwalls [ must happen after distribute(domain) in parallel ] # # ######################################################################### if not project.riverwalls == {}: domain.riverwallData.create_riverwalls(project.riverwalls, project.riverwall_par) domain.riverwallData.export_riverwalls_to_text( output_dir=project.output_dir + '/' + project.spatial_text_output_dir) return
class Block: """Minecraft PI block description. Can be sent to Minecraft.setBlock/s""" def __init__(self, id, data=0): self.id = id self.data = data def __cmp__(self, rhs): return hash(self) - hash(rhs) def __eq__(self, rhs): return self.id == rhs.id and self.data == rhs.data def __hash__(self): return (self.id << 8) + self.data def withData(self, data): return Block(self.id, data) def __iter__(self): """Allows a Block to be sent whenever id [and data] is needed""" return iter((self.id, self.data)) def __repr__(self): return "Block(%d, %d)"%(self.id, self.data) AIR = Block(0) STONE = Block(1) GRASS = Block(2) DIRT = Block(3) COBBLESTONE = Block(4) WOOD_PLANKS = Block(5) SAPLING = Block(6) BEDROCK = Block(7) WATER_FLOWING = Block(8) WATER = WATER_FLOWING WATER_STATIONARY = Block(9) LAVA_FLOWING = Block(10) LAVA = LAVA_FLOWING LAVA_STATIONARY = Block(11) SAND = Block(12) GRAVEL = Block(13) GOLD_ORE = Block(14) IRON_ORE = Block(15) COAL_ORE = Block(16) WOOD = Block(17) LEAVES = Block(18) GLASS = Block(20) LAPIS_LAZULI_ORE = Block(21) LAPIS_LAZULI_BLOCK = Block(22) SANDSTONE = Block(24) BED = Block(26) RAIL_POWERED = Block(27) RAIL_DETECTOR = Block(28) COBWEB = Block(30) GRASS_TALL = Block(31) DEAD_BUSH = Block(32) WOOL = Block(35) FLOWER_YELLOW = Block(37) FLOWER_CYAN = Block(38) MUSHROOM_BROWN = Block(39) MUSHROOM_RED = Block(40) GOLD_BLOCK = Block(41) IRON_BLOCK = Block(42) STONE_SLAB_DOUBLE = Block(43) STONE_SLAB = Block(44) BRICK_BLOCK = Block(45) TNT = Block(46) BOOKSHELF = Block(47) MOSS_STONE = Block(48) OBSIDIAN = Block(49) TORCH = Block(50) FIRE = Block(51) STAIRS_WOOD = Block(53) CHEST = Block(54) DIAMOND_ORE = Block(56) DIAMOND_BLOCK = Block(57) CRAFTING_TABLE = Block(58) FARMLAND = Block(60) FURNACE_INACTIVE = Block(61) FURNACE_ACTIVE = Block(62) SIGN_STANDING = Block(63) DOOR_WOOD = Block(64) LADDER = Block(65) RAIL = Block(66) STAIRS_COBBLESTONE = Block(67) SIGN_WALL = Block(68) DOOR_IRON = Block(71) REDSTONE_ORE = Block(73) TORCH_REDSTONE = Block(76) SNOW = Block(78) ICE = Block(79) SNOW_BLOCK = Block(80) CACTUS = Block(81) CLAY = Block(82) SUGAR_CANE = Block(83) FENCE = Block(85) PUMPKIN = Block(86) NETHERRACK = Block(87) SOUL_SAND = Block(88) GLOWSTONE_BLOCK = Block(89) LIT_PUMPKIN = Block(91) STAINED_GLASS = Block(95) BEDROCK_INVISIBLE = Block(95) TRAPDOOR = Block(96) STONE_BRICK = Block(98) GLASS_PANE = Block(102) MELON = Block(103) FENCE_GATE = Block(107) STAIRS_BRICK = Block(108) STAIRS_STONE_BRICK = Block(109) MYCELIUM = Block(110) NETHER_BRICK = Block(112) FENCE_NETHER_BRICK = Block(113) STAIRS_NETHER_BRICK = Block(114) END_STONE = Block(121) WOODEN_SLAB = Block(126) STAIRS_SANDSTONE = Block(128) EMERALD_ORE = Block(129) RAIL_ACTIVATOR = Block(157) LEAVES2 = Block(161) TRAPDOOR_IRON = Block(167) FENCE_SPRUCE = Block(188) FENCE_BIRCH = Block(189) FENCE_JUNGLE = Block(190) FENCE_DARK_OAK = Block(191) FENCE_ACACIA = Block(192) DOOR_SPRUCE = Block(193) DOOR_BIRCH = Block(194) DOOR_JUNGLE = Block(195) DOOR_ACACIA = Block(196) DOOR_DARK_OAK = Block(197) GLOWING_OBSIDIAN = Block(246) NETHER_REACTOR_CORE = Block(247)
"""depsgen.bzl """ load("@build_stack_rules_proto//rules:providers.bzl", "ProtoDependencyInfo") def _depsgen_impl(ctx): config_json = ctx.outputs.json output_deps = ctx.outputs.deps config = struct( out = output_deps.path, name = ctx.label.name, deps = [dep[ProtoDependencyInfo] for dep in ctx.attr.deps], ) ctx.actions.write( output = config_json, content = config.to_json(), ) ctx.actions.run( mnemonic = "DepsGenerate", progress_message = "Generating %s deps" % ctx.attr.name, executable = ctx.file._depsgen, arguments = ["--config_json=%s" % config_json.path], inputs = [config_json], outputs = [output_deps], ) return [DefaultInfo( files = depset([config_json, output_deps]), )] depsgen = rule( implementation = _depsgen_impl, attrs = { "deps": attr.label_list( doc = "Top level dependencies to compute", providers = [ProtoDependencyInfo], ), "_depsgen": attr.label( doc = "The depsgen tool", default = "//cmd/depsgen", allow_single_file = True, executable = True, cfg = "host", ), }, outputs = { "json": "%{name}.json", "deps": "%{name}_deps.bzl", }, )
class P: def __init__( self, name, alias ): self.name = name # public self.__alias = alias # private def who(self): print('name : ', self.name) print('alias : ', self.__alias) class X: def __init__( self, x ): self.set_x( x ) def get_x( self ): return self.__x def set_x( self, x ): if x > 1000: self.__x = 1000 elif x < 0: self.__x = 0 else: self.__x = x class Y: def __init__( self, x ): self.x = x # self.x is now the @x.setter @property def x( self ): return self.__x # this is a private variable @x.setter def x( self, x ): if x > 1000: self.__x = 1000 elif x < 0: self.__x = 0 else: self.__x = x class S: def __init__( self, name ): self.name = name def __repr__( self ): return f'{self.__dict__}' def __str__( self ): return f'Name: {self.name}' def __add__( self, other ): return S(f'{self.name} {other.name}') class Deck: def __init__( self, cards ): self.cards = list( cards ) def __getitem__( self, key ): return self.cards[key] def __repr__( self ): return f'{self.__dict__}' p = P('Claus', 'clbo') p.who() print( p.__dict__ ) print( p._P__alias ) p._P__alias = 'wow' print ( p._P__alias ) x1 = X( 3 ) x2 = X( 50 ) x1.set_x( x1.get_x() + x2.get_x() ) print ( x1.get_x() ) y1 = Y( 10 ) y2 = Y( 15 ) print( y1.__dict__ ) print ( y1.x ) y1.x = y1.x + y2.x print ( y1.x ) y1._Y__x = -10 print( y1.x ) s1 = S( "Cristian" ) s2 = S( "Valentin" ) s3 = s1.__add__( s2 ) print( s3 ) d1 = Deck( ["K", "A", 2, 3] ) print( d1 ) print ( d1[0] )
cor_do_alien = 'vermelho' if cor_do_alien == 'verde': print('Você acabou de ganhar 5 pontos!') else: print('Você acabou de ganhar 10 pontos!')
class search: def __init__(): pass def ParseSearch(request): tab = {} if request.len > 0: pass pass def search(request): pass
a = int(input()) b = int(input()) c = int(input()) mul = str(a * b * c) for i in range(0, 10): count = 0 for j in mul: if i == int(j): count += 1 print(count)
#User function Template for python3 # https://gitlab.com/pranav/my-sprints/-/snippets/2215721 ''' Input: a = 5, b = 5, x = 11, # dest = (5, 5), x = 11 Output: 0 | - R - | (-1) * x1 + 1 * x2 = a (-1) * y1 + 1 * y2 = b x1 + x2 + y1 + y2 = x TC: O(1) SC: O(1) --- Exponential TC algorithm: O(1 + 4 + 4^2 + ... + 4^x), SC: O(4^x) 1. Start from 0, 0 2. For each direction posibility: 2.1. Do BFS 2.2. If we touch a,b at any leaf node(after x moves), return 1 else return 0 to_visit.push([0, 0]) step = 0 while(step < x): queue_len = len(to_visit) # number of nodes at this level to be visited id = 0 while(id < queue_len): start = to_visit.pop(0) next_1 = [start[0], start[1] + 1] next_2 = [start[0], start[1] - 1] next_3 = [start[0] + 1, start[1]] next_4 = [start[0] - 1, start[1]] to_visit.push(next_1) to_visit.push(next_2) to_visit.push(next_3) to_visit.push(next_4) id += 1 step += 1 while to_visit: element = to_visit.pop() if (element[0] == a and element[1] == b): return 1 else: continue return 0 --- (a + b) mod x == 0 --- try solving this in 1D: given x units, and 0 starting point, each movement is +1 or -1 given (a, x) return true or false: if a % 2 == 0 and x > a, check x % a == 0, return true else false if a % 2 == 1 and x > a, check x % a == 1 return true ''' class Solution: def canReachBFS(self, a, b, x): to_visit = [] to_visit.append([0, 0]) step = 0 while(step < x): queue_len = len(to_visit) # number of nodes at this level to be visited id = 0 while(id < queue_len): start = to_visit.pop(0) next_1 = [start[0], start[1] + 1] next_2 = [start[0], start[1] - 1] next_3 = [start[0] + 1, start[1]] next_4 = [start[0] - 1, start[1]] to_visit.append(next_1) to_visit.append(next_2) to_visit.append(next_3) to_visit.append(next_4) id += 1 step += 1 while to_visit: element = to_visit.pop() if (element[0] == a and element[1] == b): return 1 else: continue return 0 def canReach(self, a, b, x): # Final solution, TC: O(1), SC: O(1) # code here sum_ab = abs(a) + abs(b) if x < sum_ab: # sanity check return 0 if sum_ab % 2 == x % 2: # (0,0, 8)->1, (0, 0, 7)-> 0 return 1 else: return 0 #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int (input ()) for _ in range (t): a,b,x=map(int,input().split()) ob = Solution() print(ob.canReach(a,b,x)) # } Driver Code Ends
#!/usr/bin/python3 n = int(input()) _ = input() for i in range(n): a = int(input()) print(a*(i+1))
class NanometerPixelConverter: def __init__(self, pitch_nm: float): self._pitch_nm = pitch_nm def to_pixel(self, value_nm: float) -> int: return int(value_nm / self._pitch_nm) def to_nm(self, value_pixel: int) -> float: return value_pixel * self._pitch_nm
#!/usr/bin/env python # Copyright (c) 2011 The WebRTC project authors. All Rights Reserved. # # Use of this source code is governed by a BSD-style license # that can be found in the LICENSE file in the root of the source # tree. An additional intellectual property rights grant can be found # in the file PATENTS. All contributing project authors may # be found in the AUTHORS file in the root of the source tree. __author__ = '[email protected] (Henrik Kjellander)' class DataHelper(object): """ Helper class for managing table data. This class does not verify the consistency of the data tables sent into it. """ def __init__(self, data_list, table_description, names_list, messages): """ Initializes the DataHelper with data. Args: data_list: List of one or more data lists in the format that the Google Visualization Python API expects (list of dictionaries, one per row of data). See the gviz_api.DataTable documentation for more info. table_description: dictionary describing the data types of all columns in the data lists, as defined in the gviz_api.DataTable documentation. names_list: List of strings of what we're going to name the data columns after. Usually different runs of data collection. messages: List of strings we might append error messages to. """ self.data_list = data_list self.table_description = table_description self.names_list = names_list self.messages = messages self.number_of_datasets = len(data_list) self.number_of_frames = len(data_list[0]) def CreateData(self, field_name, start_frame=0, end_frame=0): """ Creates a data structure for a specified data field. Creates a data structure (data type description dictionary and a list of data dictionaries) to be used with the Google Visualization Python API. The frame_number column is always present and one column per data set is added and its field name is suffixed by _N where N is the number of the data set (0, 1, 2...) Args: field_name: String name of the field, must be present in the data structure this DataHelper was created with. start_frame: Frame number to start at (zero indexed). Default: 0. end_frame: Frame number to be the last frame. If zero all frames will be included. Default: 0. Returns: A tuple containing: - a dictionary describing the columns in the data result_data_table below. This description uses the name for each data set specified by names_list. Example with two data sets named 'Foreman' and 'Crew': { 'frame_number': ('number', 'Frame number'), 'ssim_0': ('number', 'Foreman'), 'ssim_1': ('number', 'Crew'), } - a list containing dictionaries (one per row) with the frame_number column and one column of the specified field_name column per data set. Example with two data sets named 'Foreman' and 'Crew': [ {'frame_number': 0, 'ssim_0': 0.98, 'ssim_1': 0.77 }, {'frame_number': 1, 'ssim_0': 0.81, 'ssim_1': 0.53 }, ] """ # Build dictionary that describes the data types result_table_description = {'frame_number': ('string', 'Frame number')} for dataset_index in range(self.number_of_datasets): column_name = '%s_%s' % (field_name, dataset_index) column_type = self.table_description[field_name][0] column_description = self.names_list[dataset_index] result_table_description[column_name] = (column_type, column_description) # Build data table of all the data result_data_table = [] # We're going to have one dictionary per row. # Create that and copy frame_number values from the first data set for source_row in self.data_list[0]: row_dict = { 'frame_number': source_row['frame_number'] } result_data_table.append(row_dict) # Pick target field data points from the all data tables if end_frame == 0: # Default to all frames end_frame = self.number_of_frames for dataset_index in range(self.number_of_datasets): for row_number in range(start_frame, end_frame): column_name = '%s_%s' % (field_name, dataset_index) # Stop if any of the data sets are missing the frame try: result_data_table[row_number][column_name] = \ self.data_list[dataset_index][row_number][field_name] except IndexError: self.messages.append("Couldn't find frame data for row %d " "for %s" % (row_number, self.names_list[dataset_index])) break return result_table_description, result_data_table def GetOrdering(self, table_description): """ Creates a list of column names, ordered alphabetically except for the frame_number column which always will be the first column. Args: table_description: A dictionary of column definitions as defined by the gviz_api.DataTable documentation. Returns: A list of column names, where frame_number is the first and the remaining columns are sorted alphabetically. """ # The JSON data representation generated from gviz_api.DataTable.ToJSon() # must have frame_number as its first column in order for the chart to # use it as it's X-axis value series. # gviz_api.DataTable orders the columns by name by default, which will # be incorrect if we have column names that are sorted before frame_number # in our data table. columns_ordering = ['frame_number'] # add all other columns: for column in sorted(table_description.keys()): if column != 'frame_number': columns_ordering.append(column) return columns_ordering def CreateConfigurationTable(self, configurations): """ Combines multiple test data configurations for display. Args: configurations: List of one ore more configurations. Each configuration is required to be a list of dictionaries with two keys: 'name' and 'value'. Example of a single configuration: [ {'name': 'name', 'value': 'VP8 software'}, {'name': 'test_number', 'value': '0'}, {'name': 'input_filename', 'value': 'foreman_cif.yuv'}, ] Returns: A tuple containing: - a dictionary describing the columns in the configuration table to be displayed. All columns will have string as data type. Example: { 'name': 'string', 'test_number': 'string', 'input_filename': 'string', } - a list containing dictionaries (one per configuration) with the configuration column names mapped to the value for each test run: Example matching the columns above: [ {'name': 'VP8 software', 'test_number': '12', 'input_filename': 'foreman_cif.yuv' }, {'name': 'VP8 hardware', 'test_number': '5', 'input_filename': 'foreman_cif.yuv' }, ] """ result_description = {} result_data = [] for configuration in configurations: data = {} result_data.append(data) for dict in configuration: name = dict['name'] value = dict['value'] result_description[name] = 'string' data[name] = value return result_description, result_data
# 399-evaluate-division.py # # Copyright (C) 2019 Sang-Kil Park <[email protected]> # All rights reserved. # # This software may be modified and distributed under the terms # of the BSD license. See the LICENSE file for details. class Solution: def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]: # Make bidirectional skeleton graph. graph = {e[0]: [] for e in equations} graph.update({e[1]: [] for e in equations}) for k, v in enumerate(equations): graph[v[0]].append({v[1]: values[k]}) graph[v[1]].append({v[0]: 1 / values[k]}) answers = [] def dfs(fr, to, answer) -> bool: if fr not in graph: return False if fr == to: answers.append(answer) return True # Calculate multiplication via graph order. while graph[fr]: to_list = graph[fr].pop() key = list(to_list.keys())[0] answer *= to_list[key] if dfs(key, to, answer): return True answer /= to_list[key] return False for q in queries: graph_backup = copy.deepcopy(graph) # Start dfs to find two variables given. if not dfs(q[0], q[1], answer=1): answers.append(-1) graph = graph_backup return answers
valor = float(input('Qual é o preço normal do produto? ')) print(''' Formas de pagamento disponíveis: [A] À vista no dinheiro ou cheque (10% de desconto) [B] À vista no cartão (5% de desconto) [C] Em até 2x no cartão (preço normal) [D] A partir de 3x vezes no cartão (20% de juros) ''') forma_pagamento = input('Qual é a forma de pagamento? ').strip().upper() opc1 = valor - (valor / 10) opc2 = valor - (valor / 20) opc3 = valor opc4 = valor + (valor / 5) if forma_pagamento == 'A': print(f'O preço será de {opc1} reais.') elif forma_pagamento == 'B': print(f'O preço será de {opc2} reais.') elif forma_pagamento == 'C': print(f'O preço será de {opc3} reais.') elif forma_pagamento == 'D': print(f'O preço será de {opc4} reais.') else: print('erro')
def a_kv(n): return n*n*(-1)**n def sumkv(n): return sum(map(a_kv, range(1, n+1))) def mysum(n): if (n % 2) == 0: k = n / 2 print(2*k*k+k) else: k = (n+1) / 2 print(-2*k*k+k) print(sumkv(1)) print(sumkv(2)) print(sumkv(3)) print(sumkv(4)) mysum(1) mysum(2) mysum(3) mysum(4)
"Utilities for generating starlark source code" def _to_list_attr(list, indent_count = 0, indent_size = 4, quote_value = True): if not list: return "[]" tab = " " * indent_size indent = tab * indent_count result = "[" for v in list: val = "\"{}\"".format(v) if quote_value else v result += "\n%s%s%s," % (indent, tab, val) result += "\n%s]" % indent return result def _to_dict_attr(dict, indent_count = 0, indent_size = 4, quote_key = True, quote_value = True): if not len(dict): return "{}" tab = " " * indent_size indent = tab * indent_count result = "{" for k, v in dict.items(): key = "\"{}\"".format(k) if quote_key else k val = "\"{}\"".format(v) if quote_value else v result += "\n%s%s%s: %s," % (indent, tab, key, val) result += "\n%s}" % indent return result def _to_dict_list_attr(dict, indent_count = 0, indent_size = 4, quote_key = True): if not len(dict): return "{}" tab = " " * indent_size indent = tab * indent_count result = "{" for k, v in dict.items(): key = "\"{}\"".format(k) if quote_key else k result += "\n%s%s%s: %s," % (indent, tab, key, v) result += "\n%s}" % indent return result starlark_codegen_utils = struct( to_list_attr = _to_list_attr, to_dict_attr = _to_dict_attr, to_dict_list_attr = _to_dict_list_attr, )
""" File: largest_digit.py Name: Sharlene Chen ---------------------------------- This file recursively prints the biggest digit in 5 different integers, 12345, 281, 6, -111, -9453 If your implementation is correct, you should see 5, 8, 6, 1, 9 on Console. """ def main(): print(find_largest_digit(12345)) # 5 print(find_largest_digit(281)) # 8 print(find_largest_digit(6)) # 6 print(find_largest_digit(-111)) # 1 print(find_largest_digit(-9453)) # 9 def find_largest_digit(n): """ :param n: the number to be processed and compared with :return: the largest digit in the number """ num = abs(n) initial_largest_digit = num % 10 # set largest digit to the last digit of the number return helper(num, initial_largest_digit) def helper(num,largest_digit): """ This is a helper function that helps find the largest digit with extra variables to assist calculation. The calculation loops through the number by dividing it by 10 repeatedly to separate out each digit, then compares recursively to find the largest digit. :param num: the number to be checked :param largest_digit: the current largest digit :return: the most recent largest digit """ if num == 0: return largest_digit else: last_digit = int(num % 10) #compare from the last digit num = int((num - last_digit) / 10) if last_digit >= largest_digit: return helper(num,last_digit) else: return helper(num,largest_digit) if __name__ == '__main__': main()
""" Project: Author: """ def is_object_has_method(obj, method_name): assert isinstance(method_name, str) maybe_method = getattr(obj, method_name, None) return callable(maybe_method) __all__ = ['is_object_has_method']
def init(): global originlist, ellipselist, adjmatrix, adjcoordinates, valcount,num,dim,iterate, primA adjmatrix = [] # the adjmatrix is the list of edges that being created adjcoordinates = []; # the adjval gives the dimension coordinates (for plotting for the nth point) valcount = -1; # valcount keeps the number of the value of the point being added to the adjacency tree primA = [] #primA stores the terms for the primary axis. The one to traverse along on the first iteration iterate = 100 #Number of slices to cover the ellipsoid in nD space num = 0; dim = 0;
def add_numbers(numbers): result = 0 for i in numbers: result += i #print("number =", i) return result result = add_numbers([1, 2, 30, 4, 5, 9]) print(result)
target_number = 0 increment = 0 while target_number == 0: sum1 = 0 increment += 1 for j in range(1, increment): sum1 += j factors = 0 for k in range(1, int(sum1**.5)+1): if sum1 % k == 0: factors += 1 factors = factors * 2 if factors > 500: target_number = sum1 print(target_number) # 76576500
# Jun - Dangerous Hide-and-Seek : Neglected Rocky Mountain (931000001) if "exp1=1" not in sm.getQRValue(23007): sm.sendNext("Eep! You found me.") sm.sendSay("Eh, I wanted to go further into the wagon, but my head wouldn't fit.") sm.sendSay("Did you find Ulrika and Von yet? Von is really, really good at hiding.\r\n\r\n\r\n\r\n#fUI/UIWindow2.img/QuestIcon/8/0# 5 exp") sm.giveExp(5) sm.addQRValue(23007, "exp1=1") else: sm.sendNext("Did you find Ulrika and Von yet? Von is really, really good at hiding.")
# Create a program that asks the user to enter their name and their age. # Print out a message addressed to them that tells them the year that they will turn 100 years old. print("Insert your name") name = input() print("Insert yor age") age_str = input() age_int = int(age_str) print(f"{name}, you will be {age_int+100} years old in 100 years")
#Conversor de Moedas 29/01/20 real = float(input('Quanto de dinheiro você tem na carteira? R$')) dolar = real / 4.23 #3.27 Dolar do dia do curso euro = real / 4.66 #euro do dia ienejap = real / 25.77 #moeda Japonesa peso = real / 187.37 #Peso Chileno print('Com R${:.2f} você pode comprar US${:.2f} \n Euro {:.2F} \n Iene Japonês {:.2F} \n Peso Chileno {:.2F}'.format(real,dolar,euro,ienejap,peso))
""" Dependencies that are needed for jinja rules """ load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") load("//tools:defs.bzl", "clean_dep") def jinja_deps(): maybe( http_archive, name = "markupsafe_archive", urls = [ "https://files.pythonhosted.org/packages/bf/10/ff66fea6d1788c458663a84d88787bae15d45daa16f6b3ef33322a51fc7e/MarkupSafe-2.0.1.tar.gz", ], strip_prefix = "MarkupSafe-2.0.1", build_file = clean_dep("//third_party:markupsafe.BUILD"), sha256 = "594c67807fb16238b30c44bdf74f36c02cdf22d1c8cda91ef8a0ed8dabf5620a", ) maybe( http_archive, name = "jinja_archive", url = "https://files.pythonhosted.org/packages/39/11/8076571afd97303dfeb6e466f27187ca4970918d4b36d5326725514d3ed3/Jinja2-3.0.1.tar.gz", sha256 = "703f484b47a6af502e743c9122595cc812b0271f661722403114f71a79d0f5a4", build_file = clean_dep("//third_party:jinja.BUILD"), strip_prefix = "Jinja2-3.0.1", )
def find_player(matrix): for r in range(len(matrix)): for c in range(len(matrix)): if matrix[r][c] == 'P': return r, c def check_valid_cell(size, r, c): return 0 <= r < size and 0 <= c < size string = input() size = int(input()) field = [list(input()) for _ in range(size)] m = int(input()) pr, pc = find_player(field) deltas = {'up': (-1, 0), 'down': (1, 0), 'left': (0, -1), 'right': (0, 1)} for _ in range(m): command = input() next_r, next_c = pr + deltas[command][0], pc + deltas[command][1] if check_valid_cell(size, next_r, next_c): if field[next_r][next_c] != '-': string += field[next_r][next_c] field[next_r][next_c] = 'P' field[pr][pc] = '-' pr, pc = next_r, next_c else: if len(string) > 0: string = string[:-1] print(string) for row in field: print(''.join(row))
def weekDay(dayOfTheWeek): d = { 0: 'Sunday', 1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday' } return d[dayOfTheWeek]
def Load_data(filename): with open(filename) as f: content = f.readlines() content = [x.strip() for x in content] Transaction = [] for i in range(0, len(content)): Transaction.append(content[i].split()) return Transaction #To convert initial transaction into frozenset def create_initialset(dataset): retDict = {} for trans in dataset: retDict[frozenset(trans)] = retDict.get(frozenset(trans), 0) + 1 return retDict #class of FP TREE node class TreeNode: def __init__(self, Node_name,counter,parentNode): self.name = Node_name self.count = counter self.nodeLink = None self.parent = parentNode self.children = {} def increment_counter(self, counter): self.count += counter #To create Headertable and ordered itemsets for FP Tree def create_FPTree(dataset, minSupport): HeaderTable = {} for transaction in dataset: for item in transaction: HeaderTable[item] = HeaderTable.get(item,0) + dataset[transaction] for k in list(HeaderTable): if HeaderTable[k] < minSupport: del(HeaderTable[k]) frequent_itemset = set(HeaderTable.keys()) if len(frequent_itemset) == 0: return None, None for k in HeaderTable: HeaderTable[k] = [HeaderTable[k], None] retTree = TreeNode('Null Set',1,None) my_count = 0 for itemset,count in dataset.items(): print(my_count) my_count += 1 frequent_transaction = {} for item in itemset: if item in frequent_itemset: frequent_transaction[item] = HeaderTable[item][0] if len(frequent_transaction) > 0: #to get ordered itemsets form transactions ordered_itemset = [v[0] for v in sorted(frequent_transaction.items(), key=lambda p: p[1], reverse=True)] #to update the FPTree updateTree(ordered_itemset, retTree, HeaderTable, count) return retTree, HeaderTable #To create the FP Tree using ordered itemsets def updateTree(itemset, FPTree, HeaderTable, count): if itemset[0] in FPTree.children: FPTree.children[itemset[0]].increment_counter(count) else: FPTree.children[itemset[0]] = TreeNode(itemset[0], count, FPTree) if HeaderTable[itemset[0]][1] == None: HeaderTable[itemset[0]][1] = FPTree.children[itemset[0]] else: update_NodeLink(HeaderTable[itemset[0]][1], FPTree.children[itemset[0]]) if len(itemset) > 1: updateTree(itemset[1::], FPTree.children[itemset[0]], HeaderTable, count) #To update the link of node in FP Tree def update_NodeLink(Test_Node, Target_Node): while (Test_Node.nodeLink != None): Test_Node = Test_Node.nodeLink Test_Node.nodeLink = Target_Node #To transverse FPTree in upward direction def FPTree_uptransveral(leaf_Node, prefixPath): if leaf_Node.parent != None: prefixPath.append(leaf_Node.name) FPTree_uptransveral(leaf_Node.parent, prefixPath) #To find conditional Pattern Bases def find_prefix_path(basePat, TreeNode): Conditional_patterns_base = {} while TreeNode != None: prefixPath = [] FPTree_uptransveral(TreeNode, prefixPath) if len(prefixPath) > 1: Conditional_patterns_base[frozenset(prefixPath[1:])] = TreeNode.count TreeNode = TreeNode.nodeLink return Conditional_patterns_base #function to mine recursively conditional patterns base and conditional FP tree def Mine_Tree(FPTree, HeaderTable, minSupport, prefix, frequent_itemset): bigL = [v[0] for v in sorted(HeaderTable.items(),key=lambda p: p[1][0])] for basePat in bigL: new_frequentset = prefix.copy() new_frequentset.add(basePat) #print('basetPat', basePat) #print('new set', new_frequentset) #add frequent itemset to final list of frequent itemsets frequent_itemset[tuple(new_frequentset)] = HeaderTable[basePat][0] #get all conditional pattern bases for item or itemsets Conditional_pattern_bases = find_prefix_path(basePat, HeaderTable[basePat][1]) #call FP Tree construction to make conditional FP Tree Conditional_FPTree, Conditional_header = create_FPTree(Conditional_pattern_bases,minSupport) #print(Conditional_pattern_bases) if Conditional_header != None: Mine_Tree(Conditional_FPTree, Conditional_header, minSupport, new_frequentset, frequent_itemset)
L=list(map(int,input().split())) L.insert(0,L.pop()) size=len(L) dp=[[[500000 for r in range(5)] for l in range(5)] for i in range(size)] dp[0][0][0]=0 def cal(a, b): if a==b: return 1 elif a==0: return 2 elif abs(a-b)==2: return 4 else: return 3 # ddr시작 for i in range(1,size): for l in range(5): for r in range(5): # 오른발 왼발 같이 놓을때x if l==r: continue if L[i]!=l and L[i]!=r: continue for z in range(5): # 왼발이 밟을때 if (l==L[i]): dp[i][l][r]=min(dp[i][l][r],dp[i-1][z][r]+cal(z,l)) # 오른발이 밟을때 else: dp[i][l][r]=min(dp[i][l][r],dp[i-1][l][z]+cal(z,r)) print(min([min(dp[size-1][i]) for i in range(5)]))
description = 'The just-bin-it histogrammer.' devices = dict( det_image1=device( 'nicos_ess.devices.datasources.just_bin_it.JustBinItImage', description='A just-bin-it image channel', hist_topic='ymir_visualisation', data_topic='FREIA_detector', brokers=['172.30.242.20:9092'], unit='evts', hist_type='2-D DET', det_width=32, det_height=192, det_range=(1, 6144), ), det_image2=device( 'nicos_ess.devices.datasources.just_bin_it.JustBinItImage', description='A just-bin-it image channel', hist_topic='ymir_visualisation', data_topic='FREIA_detector', brokers=['172.30.242.20:9092'], unit='evts', hist_type='2-D TOF', det_width=32, det_height=192, ), det=device('nicos_ess.devices.datasources.just_bin_it.JustBinItDetector', description='The just-bin-it histogrammer', brokers=['172.30.242.20:9092'], unit='', command_topic='ymir_jbi_commands', response_topic='ymir_jbi_responses', images=['det_image1', 'det_image2'], ), ) startupcode = ''' SetDetectors(det) '''
class Coverage(object): def __init__(self): self.swaggerTypes = { 'Chrom': 'str', 'BucketSize': 'int', 'MeanCoverage': 'list<int>', 'EndPos': 'int', 'StartPos': 'int' } def __str__(self): return 'Chr' + self.Chrom + ": " + str(self.StartPos) + "-" + str(self.EndPos) +\ ": BucketSize=" + str(self.BucketSize) def __repr__(self): return str(self)
DB_TABLES = [] class Table: insertString = "CREATE TABLE {tableName} (" def __init__(self, name, columns): self.name = name self.columns = columns def getQuerry(self): res = self.insertString.format(tableName=self.name) for columns in self.columns: res += columns.getQuerry() + ", " res = res[:-2] res += ")" return res class Column: def __init__(self, name, datatype): self.name = name self.datatype = datatype def getQuerry(self): return "{name} {datatype}".format(name=self.name, datatype=self.datatype) DB_TABLES.append( Table("room", (Column("id", "INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL"), Column("nickname", "TEXT NOT NULL"), Column("temperature", "FLOAT"), Column("humidity", "FLOAT"), Column( "airQuality", "FLOAT"), Column("objectiveSpeed", "INTEGER")))) DB_TABLES.append( Table("sensor_data", ( Column("id", "INTEGER UNIQUE NOT NULL"), Column( "temperature", "FLOAT"), Column( "humidity", "FLOAT"), Column("airQuality", "FLOAT"), Column( "", "FOREIGN KEY ('id') REFERENCES 'room' ('id') ON DELETE CASCADE ON UPDATE CASCADE" )))) DB_TABLES.append( Table("past_sensor_data", ( Column("id", "INTEGER NOT NULL"), Column("temperature", "FLOAT"), Column("humidity", "FLOAT"), Column("airQuality", "FLOAT"), Column("dateTime", "TEXT DEFAULT CURRENT_TIMESTAMP"), Column( "", "FOREIGN KEY ('id') REFERENCES 'room' ('id') ON DELETE CASCADE ON UPDATE CASCADE" )))) DB_TABLES.append( Table("device", ( Column("id", "INTEGER"), Column( "serialNumber", "TEXT NOT NULL UNIQUE"), Column("nickname", "TEXT DEFAULT ''"), Column("curentValue", "FLOAT"), Column( "capabilities", "JSON NOT NULL"), Column("lastUpdate", "datetime"), Column( "", "FOREIGN KEY ('id') REFERENCES 'room' ('id') ON DELETE SET NULL ON UPDATE CASCADE" ))))
''' @jacksontenorio8 Faça um programa que leia cinco valores numéricos e guarde-os em uma lista. No final, mostre qual foi o maior e o menor valor digitando e as suas respectivas posições na lista. ''' lista_num = [] maior = 0 menor = 0 for i in range(0, 5): lista_num.append(int(input(f'Digite um número na posição {i}: '))) if i == 0: maior = menor = lista_num[i] else: if lista_num[i] > maior: maior = lista_num[i] if lista_num[i] < menor: menor = lista_num[i] print('-'*30) print(f'Você digitou os valores {lista_num}.') print(f'O maior valor digitado foi {maior} nas posições',end=' ') for c, valor in enumerate(lista_num): if valor == maior: print(f'{c}...',end=' ') print(f'\nO menor valor digitado {menor} nas posições',end=' ') for c, valor in enumerate(lista_num): if valor == menor: print(f'{c}...',end=' ')
### create list_of_tuples: points = [ (1,2), (3,4), (5,6) ] ### retrieve the first element from the first tuple: print(points[0][0]) # 1 ### retrieve the last element from the first tuple: print(points[0][-1]) # 2 ### retrieve the first element from the last tuple: print(points[-1][0]) # 5 ### retrieve the last element from the last tuple: print(points[-1][-1]) # 6
def reverse(string): """ runtime complexity of this algorithm is O(n) """ # Starting index start_index = 0 # Ending index array = list(string) last_index = len(array) - 1 while last_index > start_index: # Swap items array[start_index], array[last_index] = \ array[last_index], array[start_index] # Increment first index and decrement last index start_index += 1 last_index -= 1 return ''.join(array)
def to_string(val): if val is None: return '' else: return str(val)
x = int(input()) b = bool(input()) int_one_int_op_int_id = x + 0 int_one_int_op_bool_id = x + False int_one_bool_op_int_id = x | 0 int_one_bool_op_bool_id = x | False int_many_int_op_int_id = x + x + 0 int_many_int_op_bool_id = x + x + False int_many_bool_op_int_id = x | x | 0 int_many_bool_op_bool_id = x | x | False bool_one_int_op_int_id = b + 0 bool_one_int_op_bool_id = b + False bool_one_bool_op_int_id = b | 0 bool_one_bool_op_bool_id = b | False bool_many_int_op_int_id = b + b + 0 bool_many_int_op_bool_id = b + b + False bool_many_bool_op_int_id = b | b | 0 bool_many_bool_op_bool_id = b | b | False
attr = [[164, 5, 4, 3, 2, 1, 11, 10, 9, 8, 7, 6, 12, 14, 13, 15, 18, 16, 17, 19, 20, 22, 21, 25, 24, 23, 28, 26, 27, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76], [163, 77, 78, 79, 80, 81], [162, 82, 83, 84], [161, 85, 86], [160, 87, 88], [159, 89], [158, 90], [157, 91], [156, 92], [155, 93], [154, 94], [153, 95], [152, 96], [151, 97], [150, 98], [149, 99], [148, 100], [147, 101], [146, 102], [145, 103], [144, 104], [143, 105], [142, 106], [141, 107], [140, 108], [139, 109], [138, 110], [137, 111], [136, 112], [135, 113], [134, 114], [133, 115], [132, 116], [131, 117], [130, 118], [129, 119], [128, 120], [127, 121], [126, 122], [125, 123]] # print(attr) a,arr= [],[] theta = 1000000 with open('C:\\Users\\91865\\Desktop\\SusyInput') as file:# C:\\Users\\91865\\Desktop\\SusyInput for line in file: line = line.strip() new_line = line.replace('\t', ' ') a = new_line.split(' ') a = [int(i) for i in a] arr.append(a) a = [] # print(arr) # alter the array to store only attributes for i in range(len(arr)): arr[i] = arr[i][1:] # print(arr[i]) su = 0 ans = [] s = set() for i in attr: for k in i: for j in range(len(arr)): if k in arr[j]: s.add(j + 1) # adding objects su += len(s) # print(k,len(s),theta - len(s)) s.clear() print(su,theta - su) su = 0
#!/usr/bin/python3 def safeDivide(x,y): try: a = x/y except: a = 0 finally: return a print(safeDivide(10,0)) # Can also specify a particular exception.. def this_fails(): x = 1/0 try: this_fails() except ZeroDivisionError as errmsg: print('I am handling a run-time error:', errmsg)
# Copyright 2009-2017 Ram Rachum. # This program is distributed under the MIT license. class CuteBaseTimer: '''A base class for timers, allowing easy central stopping.''' __timers = [] # todo: change to weakref list def __init__(self, parent): self.__parent = parent CuteBaseTimer.__timers.append(self) @staticmethod # should be classmethod? def stop_timers_by_frame(frame): '''Stop all the timers that are associated with the given frame.''' for timer in CuteBaseTimer.__timers: ancestor = timer.__parent while ancestor: if ancestor == frame: timer.Stop() break ancestor = ancestor.GetParent()
def sep_str(): inp = input(str("Enter word/words with '*' sign wherever you want: ")).rsplit("*", 1)[0] return inp print(sep_str())
# -*- coding: utf-8 -*- """ Created on Tue Jun 11 20:14:24 2019 @author: Administrator """ class Solution: def majorityElement(self, nums: list) -> list: # x=0 # y=0 # cx=0 # cy=0 # for num in nums: # if (cx==0 or num == x) and num != y: # cx += 1 # x=num # elif cy == 0 or num == y: # cy +=1 # y = num # else: # cx -=1 # cy -=1 # cx = 0 # cy = 0 # for num in nums: # if num == x: # cx +=1 # elif num ==y: # cy +=1 # length = len(nums) # l=[] # if cx>int(length/3): # l.append(x) # if cy>int(length/3): # l.append(y) # return l # a, b, ca, cb, ans = None, None, 0, 0, [] # for n in nums: # if n == a: ca += 1 # elif n == b: cb += 1 # elif ca == 0: a, ca = n, 1 #初始化 # elif cb == 0: b, cb = n, 1 #初始化 # else: ca, cb = ca - 1, cb - 1 # # ca, cb = 0, 0 # for n in nums: # if n == a: ca += 1 # elif n == b: cb += 1 # if ca > len(nums)//3: #最多和次最多的数是不是都多于n/3的向下取整 # ans.append(a) # if cb > len(nums)//3: # ans.append(b) # return ans a, b, ca, cb, ans = None, None, 0, 0, [] for k in nums: if k == a: ca += 1 elif k == b: cb += 1 elif ca == 0: a, ca = k, 1 elif cb == 0: b, cb = k, 1 else: ca -= 1 cb -= 1 ca, cb = 0, 0 for k in nums: if k == a: ca += 1 if k == b: cb += 1 if ca > len(nums) // 3: ans.append(a) if cb > len(nums) // 3: ans.append(b) return ans solu = Solution() #nums = [3,2,3] nums = [1,1,1,3,3,2,2,2] print(solu.majorityElement(nums))
num=int(input("Informe o valor: ")) sucessor= num +1 antecessor= num -1 print("O sucessor é: ", sucessor) print("O antecessor é: ", antecessor)
# global vars g_dataset_dir = "../dataset/" g_train_dir = g_dataset_dir + "/train/" g_test_dir = g_dataset_dir + "/test/" g_image_size = 400 g_grid_row = 8 g_grid_col = 8 g_grid_num = g_grid_row * g_grid_col g_grid_size = int(g_image_size / g_grid_row) g_down_sampled_size = 200 g_down_sampled_grid_size = int(g_grid_size / (g_image_size / g_down_sampled_size)) # global instance of mapping of char vs chess pieces # reference: Forsyth–Edwards Notation, https://en.wikipedia.org/wiki/Forsyth%E2%80%93Edwards_Notation # # pawn = "P", knight = "N", bishop = "B", rook = "R", queen = "Q" and king = "K" # White pieces are designated using upper-case letters ("PNBRQK") while black pieces use lowercase ("pnbrqk") # we use 0 to note an empty grid. # 13 items in total. g_piece_mapping = { "P" : "pawn", "N" : "knight", "B" : "bishop", "R" : "rook", "Q" : "queen", "K" : "king", "p" : "pawn", "n" : "knight", "b" : "bishop", "r" : "rook", "q" : "queen", "k" : "king", "0" : "empty_grid" } g_num_labels = len(g_piece_mapping)
""" This package contains the sphinx extensions used by Astropy. The `automodsumm` and `automodapi` modules contain extensions used by Astropy to generate API documentation - see the docstrings for details. The `numpydoc` module is dervied from the documentation tools numpy and scipy use to parse docstrings in the numpy/scipy format, and are also used by Astropy. The other modules are dependencies for `numpydoc`. """
ONE_DAY_IN_SEC = 86400 SCHEMA_VERSION = "2018-10-08" NOT_APPLICABLE = "N/A" ASFF_TYPE = "Unusual Behaviors/Application/ForcepointCASB" BLANK = "blank" OTHER = "Other" SAAS_SECURITY_GATEWAY = "SaaS Security Gateway" RESOURCES_OTHER_FIELDS_LST = [ "Name", "suid", "suser", "duser", "act", "cat", "cs1", "app", "deviceFacility", "deviceProcessName", "dpriv", "end", "externalId", "fsize", "msg", "proto", "reason", "request", "requestClientApplication", "rt", "sourceServiceName", "cs2", "cs3", "cs5", "cs6", "AD.ThreatRadarCategory", "AD.TORNetworks", "AD.MaliciousIPs", "AD.AnonymousProxies", "AD.IPChain", "AD.IPOrigin", "AD.samAccountName", "dproc", "flexString1", "flexString2", "cn1", "duid", "oldFileId", "oldFileName", "fname", "dhost", "dvc", "dvchost", "destinationProcessName", "record", "cs4", ] BATCH_LOG_FILE_NAME = "casb-siem-aws-missed.log" STREAM_LOG_FILE_NAME = "casb-siem-aws.log" CEF_EXT = ".cef" AWS_SECURITYHUB_BATCH_LIMIT = 100 AWS_LIMIT_TIME_IN_DAYS = 90 DEFAULT_INSIGHTS_FILE = "insights.json" INSIGHTS_ARNS_FILE = "insights_arns.json" CLOUDFORMATION_STACK_NAME = "SecurityHubEnabled" CLOUDFORMATION_STACK_TEMPLATE_FILE = "cloudFormation-stack.json" MAX_RETRIES = 60 # equivalent to 5 minutes (waiting 5 seconds per attempt) CRITICAL = "CRITICAL" HIGH = "HIGH" MEDIUM = "MEDIUM" LOW = "LOW" INFORMATIONAL = "INFORMATIONAL"
input_file = open("input.txt","r") input_lines = input_file.readlines() #print(*input_lines) rules = [] tickets = [] for line in input_lines: if line[0].isalpha() and 'or' in line: #print("Rule") firstLow = line.split(' ')[-3].split('-')[0] firstHigh = line.split(' ')[-3].split('-')[1] secondLow = line.split(' ')[-1].split('-')[0] secondHigh = line.split(' ')[-1].split('-')[1][:-1] rules.append([firstLow, firstHigh, secondLow, secondHigh]) #elif line[0].isalpha(): #print("Your/nearby ticket") elif line[0].isnumeric(): tickets.append(line.strip().split(',')) #print("Ticket") #print(rules) #print(tickets) error_rate = 0 for ticket in tickets[1:]: #loop through each ticket, also skip the first one for field in ticket: #Loop through each field for rule in rules: #Loop through each rule if (int(rule[0]) <= int(field) <= int(rule[1])) or (int(rule[2]) <= int(field) <= int(rule[3])): break if rule == rules[-1]: error_rate += int(field) print("Error rate:", error_rate)
# # PySNMP MIB module PANASAS-BLADESET-MIB-V1 (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PANASAS-BLADESET-MIB-V1 # Produced by pysmi-0.3.4 at Mon Apr 29 20:27:54 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") ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion") panFs, = mibBuilder.importSymbols("PANASAS-PANFS-MIB-V1", "panFs") PanSerialNumber, = mibBuilder.importSymbols("PANASAS-TC-MIB", "PanSerialNumber") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, ObjectIdentity, Integer32, Unsigned32, MibIdentifier, NotificationType, ModuleIdentity, TimeTicks, Counter64, Gauge32, Counter32, iso = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "ObjectIdentity", "Integer32", "Unsigned32", "MibIdentifier", "NotificationType", "ModuleIdentity", "TimeTicks", "Counter64", "Gauge32", "Counter32", "iso") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") panBSet = ModuleIdentity((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3)) panBSet.setRevisions(('2011-04-07 00:00',)) if mibBuilder.loadTexts: panBSet.setLastUpdated('201104070000Z') if mibBuilder.loadTexts: panBSet.setOrganization('Panasas, Inc') panBSetTable = MibTable((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1), ) if mibBuilder.loadTexts: panBSetTable.setStatus('current') panBSetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1), ).setIndexNames((0, "PANASAS-BLADESET-MIB-V1", "panBSetName")) if mibBuilder.loadTexts: panBSetEntry.setStatus('current') panBSetName = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetName.setStatus('current') panBSetNumBlades = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetNumBlades.setStatus('current') panBSetAvailSpares = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetAvailSpares.setStatus('current') panBSetRequestedSpares = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetRequestedSpares.setStatus('current') panBSetTotalCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetTotalCapacity.setStatus('current') panBSetReservedCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 6), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetReservedCapacity.setStatus('current') panBSetUsedCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 7), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetUsedCapacity.setStatus('current') panBSetAvailableCapacity = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 8), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetAvailableCapacity.setStatus('current') panBSetInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 1, 1, 9), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetInfo.setStatus('current') panBSetBladesTable = MibTable((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 2), ) if mibBuilder.loadTexts: panBSetBladesTable.setStatus('obsolete') panBSetBladesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 2, 1), ).setIndexNames((0, "PANASAS-BLADESET-MIB-V1", "panBSetName"), (0, "PANASAS-BLADESET-MIB-V1", "panBSetBladeIndex")) if mibBuilder.loadTexts: panBSetBladesEntry.setStatus('obsolete') panBSetBladeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 2, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetBladeIndex.setStatus('obsolete') panBSetBladeHwSn = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 3, 2, 1, 2), PanSerialNumber()).setMaxAccess("readonly") if mibBuilder.loadTexts: panBSetBladeHwSn.setStatus('obsolete') mibBuilder.exportSymbols("PANASAS-BLADESET-MIB-V1", panBSetTotalCapacity=panBSetTotalCapacity, panBSetInfo=panBSetInfo, panBSetRequestedSpares=panBSetRequestedSpares, panBSetBladesTable=panBSetBladesTable, panBSetNumBlades=panBSetNumBlades, panBSetBladesEntry=panBSetBladesEntry, PYSNMP_MODULE_ID=panBSet, panBSetUsedCapacity=panBSetUsedCapacity, panBSetAvailableCapacity=panBSetAvailableCapacity, panBSetTable=panBSetTable, panBSetName=panBSetName, panBSetReservedCapacity=panBSetReservedCapacity, panBSetEntry=panBSetEntry, panBSetBladeIndex=panBSetBladeIndex, panBSetAvailSpares=panBSetAvailSpares, panBSet=panBSet, panBSetBladeHwSn=panBSetBladeHwSn)
#!/usr/bin/env python3 def step(n): if n%2==0: return n/2 else: return 3*n + 1 def to_one(n): count = 0 while n != 1: n = step(n) count += 1 return count def all_chains(highest): for i in range(1, highest): yield (i, to_one(i)) print(max( all_chains(1000000), key=(lambda x: x[1]) ))
#program to check whether every even index contains an even number # and every odd index contains odd number of a given list. def odd_even_position(nums): return all(nums[i]%2==i%2 for i in range(len(nums))) print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 3])) print(odd_even_position([2, 1, 4, 3, 6, 7, 6, 4])) print(odd_even_position([4, 1, 2]))
love = 'I would love to be in ' places = [ 'zion', 'bryce', 'moab', 'arches', 'candyland', 'sedona'] for x in places: print(x)
# This Python file uses the following encoding: utf-8 """This file contains functions for the formatting of the the test results files.""" def line(char: str = "_", newline: bool = False) -> None: """Prints a character 70 times, with an optional preceding newline.""" if newline is True: print () if len(char) == 1: print (char * 70) else: raise ValueError(f"The parameter 'char' must be a string that is one character long, not {len(char)} characters long!") def header(text: str) -> None: """Prints a centered, all-uppercase header for the unittest log files. Tries to center the 'headertext' for a 70-character column width. """ if not str.isupper(text): text = str.upper(text) num_spaces = int ((70 - len (text)) / 2) print (" " * num_spaces, text, " " * num_spaces, sep="")
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. load("//antlir/bzl:constants.bzl", "REPO_CFG") def check_flavor_exists(flavor): if flavor not in REPO_CFG.flavor_to_config: fail( "{} must be in {}" .format(flavor, list(REPO_CFG.flavor_to_config)), "flavor", )
# ====================================================================== # Subterranean Sustainability # Advent of Code 2018 Day 12 -- Eric Wastl -- https://adventofcode.com # # Python implementation by Dr. Dean Earl Wright III # ====================================================================== # ====================================================================== # p o t s . p y # ====================================================================== "A solver for the Advent of Code 2018 Day 12 puzzle" # ---------------------------------------------------------------------- # import # ---------------------------------------------------------------------- # ---------------------------------------------------------------------- # constants # ---------------------------------------------------------------------- GENERATIONS = 20 P2_GENERATIONS = 50000000000 P2_100 = 2675 P2_DELTA = 22 # ====================================================================== # Pots # ====================================================================== class Pots(object): # pylint: disable=R0902, R0205 "Object for Subterranean Sustainability" def __init__(self, generations=GENERATIONS, text=None, part2=False): # 1. Set the initial values self.part2 = part2 self.text = text self.pots = '' self.rules = {} self.left = 0 self.generations = generations # 2. Process text (if any) if text is not None and len(text) > 3: self.processText(text) def processText(self, text): self.pots = '.' * self.generations self.left = -self.generations self.processInitialState(text[0]) self.processRules(text[1:]) def processInitialState(self, line): parts = line.split(' ') if parts[0] != 'initial' or parts[1] != 'state:': print("*** Expected 'initial state' but found '%s %s'" % (parts[0], parts[1])) return self.pots = self.pots + parts[2] + self.pots def processRules(self, text): for line in text: parts = line.split(' ') if parts[1] != '=>': print("*** Expected '=>' but found '%s'" % parts[1]) return self.rules[parts[0]] = parts[2] def next(self, index): current = self.pots[index-2:index+3] if current in self.rules: return self.rules[current] return '.' def next_generation(self): result = ['.','.'] for index in range(2, len(self.pots)-2): result.append(self.next(index)) return ''.join(result) + '..' def sum_pots(self): result = 0 value = self.left for pot in self.pots: if pot == '#': result += value value += 1 return result def run(self, verbose=False): for gen in range(1, self.generations+1): next_gen = self.next_generation() self.pots = next_gen if verbose: print("%2d: %5d %s" % (gen, self.sum_pots(), next_gen)) def part_one(self, verbose=False, limit=0): "Returns the solution for part one" # 1. Return the solution for part one self.run(verbose=verbose) return self.sum_pots() def part_two(self, verbose=False, limit=0): "Returns the solution for part two" # 1. Return the solution for part two return P2_100 + P2_DELTA * (P2_GENERATIONS - 100) # ---------------------------------------------------------------------- # module initialization # ---------------------------------------------------------------------- if __name__ == '__main__': pass # ====================================================================== # end p o t s . p y end # ======================================================================
""" 51 / 51 test cases passed. Runtime: 108 ms Memory Usage: 19.3 MB """ class Solution: def gardenNoAdj(self, n: int, paths: List[List[int]]) -> List[int]: graph = [[] for _ in range(n)] ans = [0] * n for x, y in paths: graph[x - 1].append(y - 1) graph[y - 1].append(x - 1) for i in range(n): ans[i] = ({1, 2, 3, 4} - {ans[adj] for adj in graph[i]}).pop() return ans
#Python program to remove the n'th # index character from a nonempty string. inputStr = "akfjljfldksgnlfskgjlsjf" n = 5 def abc(inputStr, n): if n > len(inputStr): print("invalid 'n'.") return 0 return inputStr[0:n-1] + inputStr[n:] newStr = abc(inputStr,n) print(newStr)
class SetCommands(): def __init__(self, command): self.command = command def speed(self, x: int): """ description: set speed to x cm/s x: 10-100 response: ok, error """ return self.command(f'speed {x}') def rc_control(self, a, b, c, d): """ description: Send RC control via four channels. a: left/right (-100~100) b: forward/backward (-100~100) c: up/down (-100~100) d: yaw (-100~100) response: ok, error """ return self.command(f'rc {a} {b} {c} {d}') def wifi(self, ssid: str, psw: str): """ description: Set Wi-Fi with SSID password response: ok, error """ return self.command(f'wifi {ssid} {psw}')
## Copyright 2002-2003 Andrew Loewenstern, All Rights Reserved # see LICENSE.txt for license information def bucket_stats(l): """given a list of khashmir instances, finds min, max, and average number of nodes in tables""" max = avg = 0 min = None def count(buckets): c = 0 for bucket in buckets: c = c + len(bucket.l) return c for node in l: c = count(node.table.buckets) if min == None: min = c elif c < min: min = c if c > max: max = c avg = avg + c avg = avg / len(l) return {'min':min, 'max':max, 'avg':avg}
DEFAULT_MEROSS_HTTP_API = "https://iot.meross.com" DEFAULT_MQTT_HOST = "mqtt.meross.com" DEFAULT_MQTT_PORT = 443 DEFAULT_COMMAND_TIMEOUT = 10.0
# Desenvolva um programa em Python que receba a matricula, o nome, o teste, a prova dos alunos de uma turma, até que seja digitado 0 para a matricula do aluno. # O programa deverá calcular e exibir, para cada aluno, a matricula, o nome, a média e se o aluno está aprovado(media>=7), Final(media >=5 e <7) ou reprovado(média<5). matricula = input("Digite a matricula: ") while matricula != "0": nome = input("Digite o nome: ") teste = float(input("Digite o teste: ")) prova = float(input("Digite a prova: ")) media = (teste + prova) / 2 if media >= 7: status = "Aprovado" elif media < 5: status = "Reprovado" else: status = "Final" print("Matricula: " + matricula) print("Nome: " + nome) print("Média: " + str(media)) print("Status: " + status) matricula = input("Digite a matricula: ")
t = int(input()) while t > 0: s = input() new = '' c=1 for i in range(len(s)): if i == 0: new+=s[i] elif i!=0 and s[i] != s[i-1]: new+=str(c) c=1 new+=s[i] elif s[i] == s[i-1] and new[-1] == s[i]: c+=1 print(new) t-=1
class RelinquishOptions(object,IDisposable): """ Options to control behavior of relinquishing ownership of elements and worksets. RelinquishOptions(relinquishEverything: bool) """ def Dispose(self): """ Dispose(self: RelinquishOptions) """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: RelinquishOptions,disposing: bool) """ 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,relinquishEverything): """ __new__(cls: type,relinquishEverything: bool) """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass CheckedOutElements=property(lambda self: object(),lambda self,v: None,lambda self: None) """True means all elements checked out by the current user should be relinquished. False means none of these are relinquished. Get: CheckedOutElements(self: RelinquishOptions) -> bool Set: CheckedOutElements(self: RelinquishOptions)=value """ FamilyWorksets=property(lambda self: object(),lambda self,v: None,lambda self: None) """True means all family worksets owned by the current user should be relinquished. False means none of these are relinquished. Get: FamilyWorksets(self: RelinquishOptions) -> bool Set: FamilyWorksets(self: RelinquishOptions)=value """ 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: RelinquishOptions) -> bool """ StandardWorksets=property(lambda self: object(),lambda self,v: None,lambda self: None) """True means all project standards worksets owned by the current user should be relinquished. False means none of these are relinquished. Get: StandardWorksets(self: RelinquishOptions) -> bool Set: StandardWorksets(self: RelinquishOptions)=value """ UserWorksets=property(lambda self: object(),lambda self,v: None,lambda self: None) """True means all user-created worksets owned by the current user should be relinquished. False means none of these are relinquished. Get: UserWorksets(self: RelinquishOptions) -> bool Set: UserWorksets(self: RelinquishOptions)=value """ ViewWorksets=property(lambda self: object(),lambda self,v: None,lambda self: None) """True means all view worksets owned by the current user should be relinquished. False means none of these are relinquished. Get: ViewWorksets(self: RelinquishOptions) -> bool Set: ViewWorksets(self: RelinquishOptions)=value """
# Vim has the best keybindings ever class Vim: @property def __best__(self): return True
#!/usr/bin/env python # -*- coding: utf-8 -*- def all_messages(): return \ { "0": "Nettacker-motor begon ...\n\n", "1": "python nettacker.py [opties]", "2": "Toon Nettacker Help Menu", "3": "Gelieve de licentie en afspraken te lezen https://github.com/viraintel/OWASP-Nettacker\n", "4": "Motor", "5": "Motorinvoeropties", "6": "selecteer een taal {0}", "7": "scan alle IP's in het bereik", "8": "subdomeinen zoeken en scannen", "9": "draadnummers voor verbindingen met een host", "10": "draadnummers voor scan hosts", "11": "Sla alle logboeken op in het bestand (results.txt, results.html, results.json)", "12": "Doel", "13": "Target input opties", "14": "doel (en) lijst, apart met \",\"", "15": "lees doel (en) van het bestand", "16": "Opties voor scanmethode", "17": "kies scanmethode {0}", "18": "kies scanmethode om {0} uit te sluiten", "19": "gebruikersnaam (en) lijst, apart met \",\"", "20": "lees gebruikersnaam (s) van het bestand", "21": "wachtwoord (en) lijst, apart met \",\"", "22": "lees wachtwoord (en) van het bestand", "23": "poort (en) lijst, apart met \",\"", "24": "lees wachtwoorden van het bestand", "25": "tijd om te slapen tussen elk verzoek", "26": "Kan de doelstelling (en) niet opgeven", "27": "Kan de doelstelling (en) niet specificeren, bestand niet openen: {0}", "28": "het is beter om draadnummer lager dan 100 te gebruiken, BTW gaan we door ...", "29": "stel time-out in {0} seconden, het is te groot, is het niet? door de manier waarop we doorgaan ...", "30": "deze scanmodule [{0}] niet gevonden!", "31": "deze scanmodule [{0}] niet gevonden!", "32": "U kunt alle scanmethodes niet uitsluiten", "33": "U kunt alle scanmethodes niet uitsluiten", "34": "de {0} module die u heeft geselecteerd om te sluiten niet gevonden!", "35": "enter methods inputs, example: \"ftp_brute_users=test,admin&ftp_brute_passwds=" "read_from_file:/tmp/pass.txt&ftp_brute_port=21\"", "36": "kan het bestand niet lezen {0}", "37": "Kan de gebruikersnaam (en) niet opgeven, kan het bestand niet openen: {0}", "38": "", "39": "Kan het wachtwoord (en) niet specificeren, bestand niet openen: {0}", "40": "bestand \"{0}\" is niet te schrijven!", "41": "kies alstublieft uw scanmethode!", "42": "Temp-bestanden verwijderen!", "43": "sorteren resultaten!", "44": "gedaan!", "45": "begin met {0}, {1} van {2} aanval", "46": "deze module \"{0}\" is niet beschikbaar", "47": "helaas kan deze versie van de software gewoon op linux /osx/windows worden uitgevoerd.", "48": "Uw Python-versie wordt niet ondersteund!", "49": "overslaan duplicaat doel (sommige subdomeinen / domeinen kunnen hetzelfde IP en bereik hebben)", "50": "onbekend type doelwit [{0}]", "51": "controleer {0} bereik ...", "52": "controleert {0} ...", "53": "HOST", "54": "USERNAME", "55": "WACHTWOORD", "56": "HAVEN", "57": "TYPE", "58": "BESCHRIJVING", "59": "verbose modus niveau (0-5) (standaard 0)", "60": "toon software versie", "61": "controleer op updates", "62": "", "63": "", "64": "Wordt opnieuw geprobeerd als de verbindings time-out (standaard 3)", "65": "ftp verbinding met {0}: {1} time-out, overslaan {2}: {3}", "66": "INGESLOTEN!", "67": "INGESLOTEN INGESLOTEN, TOEGESTAAN VOOR LIJST COMMAND!", "68": "ftp verbinding met {0}: {1} mislukt, de hele stap overslaan [proces {2} van {3}]!" " Naar de volgende stap gaan", "69": "invoer doel voor {0} module moet DOMAIN, HTTP of SINGLE_IPv4 zijn, om {1}", "70": "gebruiker: {0} pass: {1} host: {2} port: {3} found!", "71": "(GEEN TOESTEMMING VOOR LIJSTFILES)", "72": "proberen {0} van {1} in behandeling {2} van {3} {4}: {5}", "73": "smtp verbinding met {0}: {1} time-out, overslaan {2}: {3}", "74": "smtp verbinding met {0}: {1} is mislukt, de hele stap overschrijdt [proces {2} van {3}]!" " Naar de volgende stap gaan", "75": "invoer doel voor {0} module moet HTTP, overslaan {1}", "76": "ssh verbinding met {0}: {1} time-out, overslaan {2}: {3}", "77": "ssh verbinding met {0}: {1} is mislukt, de hele stap overschrijdt [proces {2} van {3}]!" " Naar de volgende stap gaan", "78": "ssh verbinding met% s:% s is mislukt, de hele stap overslaan [proces% s van% s]! Naar " "de volgende stap gaan", "79": "OPEN PORT", "80": "host: {0} poort: {1} gevonden!", "81": "doel {0} ingediend!", "82": "kan geen proxy-lijstbestand openen: {0}", "83": "kan geen proxy-lijstbestand vinden: {0}", "84": "U gebruikt OWASP Nettacker versie {0} {1} {2} {6} met code naam {3} {4} {5}", "85": "deze functie is nog niet beschikbaar! voer alsjeblieft \"git clone https://github.com/viraintel/" "OWASP-Nettacker.git\" of \"pip install -U OWASP-Nettacker\" om de laatste versie te krijgen.", "86": "bouw een grafiek van alle activiteiten en informatie, u moet HTML-uitvoer gebruiken. " "beschikbare grafieken: {0}", "87": "om grafiekfunctie te gebruiken, moet uw uitvoerbestandnaam eindigen met \".html\" of \".htm\"!", "88": "bouwgrafiek ...", "89": "voltooi bouw grafiek!", "90": "Penetratie Testen Grafieken", "91": "Deze grafiek is gemaakt door OWASP Nettacker. Grafiek bevat alle modules activiteiten, " "netwerk kaart en gevoelige informatie, Deel dit bestand niet met iemand als het niet betrouwbaar is.", "92": "OWASP Nettacker Report", "93": "Software Details: OWASP Nettacker versie {0} [{1}] in {2}", "94": "geen open poorten gevonden!", "95": "geen gebruiker / wachtwoord gevonden!", "96": "{0} modules geladen ...", "97": "deze grafiekmodule niet gevonden: {0}", "98": "deze grafische module \"{0}\" is niet beschikbaar", "99": "ping voor het scannen van de host", "100": "het overslaan van het hele doel {0} en het scannen methode {1} doordat -ping-before-scan " "is waar en het antwoordde niet!", "101": "U gebruikt de laatste versie van OWASP Nettacker niet, alsjeblieft bijwerken.", "102": "Kijk niet naar updates, controleer alstublieft uw internetverbinding.", "103": "U gebruikt de laatste versie van OWASP Nettacker ...", "104": "directory listing found in {0}", "105": "Voer alsjeblieft de poort in via de -g of --methods-args-schakelaar in plaats van url", "106": "http verbinding {0} time-out!", "107": "", "108": "no directory or file found for {0} in port {1}", "109": "unable to open {0}", "110": "dir_scan_http_method waarde moet GET of HEAD zijn, stel standaard in op GET.", "111": "lijst alle methoden args", "112": "kan {0} module args niet krijgen", "113": "", "114": "", "115": "", "116": "", "117": "" }