content
stringlengths
7
1.05M
""" The RequestSupplement object that will get injected on marketplace requests """ class RequestSupplement(object): # adding some duplicate fields keyed to more consistent python naming and # more understandable naming in some cases. You're free to use whichever # you want. EXTRAS = { 'portal_id': 'hub_id', 'app_pageUrl': 'local_url', 'app_callbackUrl': 'local_base_url', 'app_canvasUrl': 'base_url', } def __init__(self, request): super(RequestSupplement,self).__init__() self.process(request) def process(self, request): for k in request.REQUEST: if k.startswith('hubspot.marketplace.'): attr = '_'.join(k.split('.')[2:]) val = request.REQUEST.get(k) if attr.endswith('_id'): val = long(val) elif attr.startswith('is_'): val = val.lower()=='true' setattr(self, attr, val) for k in self.__class__.EXTRAS: if getattr(self,k,None): # they're not all necessarily here (uninstall hook only gives secret and portal_id) setattr(self,self.__class__.EXTRAS[k],getattr(self,k))
# import matplotlib.pyplot as plt # Menge an Werten zahlen = "1203456708948673516874354531568764645" # Initialisieren der Histogramm Variable histogramm = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0] for index in range(len(zahlen)): histogramm[int(zahlen[index])] += 1 # plt.hist(histogramm, bins = 9) # plt.show() for i in range(0,10): print("Die Zahl", i, "kommt", histogramm[i], "Mal vor.")
#!/usr/bin/env pytho codigo = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', '.': '.-.-.-', ',': '--..--', ':': '---...', ';': '-.-.-.', '?': '..--..', '!': '-.-.--', '"': '.-..-.', "'": '.----.', '+': '.-.-.', '-': '-....-', '/': '-..-.', '=': '-...-', '_': '..--.-', '$': '...-..-', '@': '.--.-.', '&': '.-...', '(': '-.--.', ')': '-.--.-' } palabra = input("Palabra:") lista_codigos = [] for caracter in palabra: if caracter.islower(): caracter=caracter.upper() lista_codigos.append(codigo[caracter]) print (" ".join(lista_codigos)) morse=input("Morse:") lista_morse=morse.split(" ") palabra = "" for cod in lista_morse: #letra=[key for key,valor in codigo.items() if valor==cod][0] for key,valor in codigo.items(): if valor == cod: letra = key palabra=palabra+letra print (palabra)
class Cloth: def __init__(self, name, shop_url, available, brand_logo, price, img_url): self.name = name self.shop_url = shop_url self.available = available self.brand_logo = brand_logo self.price = price self.img_url = img_url def __str__(self): print('Name: {0}\nBrand: {1}\nPrice: {2}\nAvailable: {3}, Link to the shop: {4}'.format(self.name, self.brand, self.price, self.available, self.shop_url))
#!/usr/bin/env python3 """ The marketing team is spending way too much time typing in hashtags. Let's help them with our own Hashtag Generator! Here's the deal: It must start with a hashtag (#). All words must have their first letter capitalized. If the final result is longer than 140 chars it must return false. If the input or the result is an empty string it must return false. Examples " Hello there thanks for trying my Kata" => "#HelloThereThanksForTryingMyKata" " Hello World " => "#HelloWorld" "" => false """ def execute(s): s = s.rstrip() r = False if 0 == len(s) or 140 < len(s): return r r = "#%s" % s.title().replace(' ','') return r
def pickingNumbers(a): solution = 0 for num1 in a: if a.count(num1) + a.count(num1 + 1) > solution: solution = a.count(num1) + a.count(num1 + 1) return solution
# while loops def nearest_square(limit): number = 0 while (number+1) ** 2 < limit: number += 1 return number ** 2 test1 = nearest_square(40) print("expected result: 36, actual result: {}".format(test1)) # black jack card_deck = [4, 11, 8, 5, 13, 2, 8, 10] hand = [] while sum(hand) <= 21: hand.append(card_deck.pop()) #removes from deck print(hand) # headline ticker for news, up to 140 chars headlines = ["Local Bear Eaten by Man", "Legislature Announces New Laws", "Peasant Discovers Violence Inherent in System", "Cat Rescues Fireman Stuck in Tree", "Brave Knight Runs Away", "Papperbok Review: Totally Triffic"] news_ticker = "" for headline in headlines: if len(news_ticker) + len(headline) <= 140: news_ticker += headline + " " else: for letter in headline: if len(news_ticker) < 140: news_ticker += letter else: break; print(news_ticker) # alternative for above, shorter news_ticker = "" for headline in headlines: news_ticker += headline + " " if len(news_ticker) >= 140: # just take first 140 after creating full news_ticker = news_ticker[:140] break; print(news_ticker)
A_1,B_1 = input().split(" ") a = int(A_1) b = int(B_1) if a > b: horas = (24-a) + b print("O JOGO DUROU %i HORA(S)"%(horas)) elif a == b: print("O JOGO DUROU 24 HORA(S)") else: horas = b - a print("O JOGO DUROU %i HORA(S)"%(horas))
"""Example of comments within the Hello World package This is a further elaboration of the docstring. Here, you can define the details and steps appropriate for the situation. Code tells you how. Comments tell you why. args: name (int): a description of the parameter name (str): a description of the parameter returns: type: a description of what is being returned of type """ # Comment preceding a simple print statement to show how the hash works print("Hello, World!")
# https://app.codesignal.com/arcade/code-arcade/well-of-integration/QmK8kHTyKqh8xDoZk def threeSplit(numbers): # From a list of numbers, cut into three pieces such that each # piece contains an integer, and the sum of integers in each # piece is the same. # We know that the total sum of elements in the array is divisible by 3. # So any 3 segments it can be divided into must have sum total/3. total = sum(numbers) third = total / 3 # The count of starts, this is, places where it adds to a third. start_count = 0 # Acum so far of values in the array. acum_sum = 0 # Result which will hold the amount of ways the array can be split into 3 equally. result = 0 for idx in range(len(numbers) - 1): # Keep accumulating values. acum_sum += numbers[idx] # A second splitting point is if up to this point it adds to two thirds. # Checked before the start point for the case in which a third of the total # is equal to two thirds, because the total added up to 0. Also for a second # splitting point to be valid, there has to be at least one starting point. if acum_sum == 2 * third and start_count > 0: # Any "second splitting point" found will work with any of the previously # found "starting splitting points", so add up the amount of such points # found until the current one. result += start_count # A starting splitting point is if up to this point it adds up to a third. if acum_sum == third: start_count += 1 return result
def comparator(predicate): """Makes a comparator function out of a function that reports whether the first element is less than the second""" return lambda a, b: predicate(a, b) * -1 + predicate(b, a) * 1
# https://stackoverflow.com/questions/14485255/vertical-sum-in-a-given-binary-tree # https://codereview.stackexchange.com/questions/151208/vertical-sum-in-a-given-binary-tree d = {} def traverse(node, hd): if not node: return if not hd in d: d[hd] = 0 d[hd] = d[hd] + node.value traverse(node.left, hd - 1) traverse(node.right, hd + 1) class Node: def __init__(self, value, left=None, right=None): self.value = value self.left = left self.right = right """ 1 / \ 2 3 / \ / \ 4 5 6 7 """ node7 = Node(70) node6 = Node(60) node5 = Node(50) node4 = Node(40) node3 = Node(3) node2 = Node(2) root = Node(1) root.left = node2 root.right = node3 node2.left = node4 node2.right = node5 node3.left = node6 node3.right = node7 traverse(root, 0) print(sorted(d.items()))
class BaseError(Exception): def __init__(self, error_code): super().__init__(self) self.error_dic = { '1001': 'Get params failed. ', '1002': 'Type of input error. ', '1003': 'File does not exists. ', '1004': 'File receiving. ', '1005': 'Permission error. ', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = self.error_code def __str__(self): return self.error_msg class AuthError(Exception): def __init__(self, error_code): super().__init__(self) self.error_dic = { '1001': 'user exists', '1002': "User does not exists", '1003': 'register failed', '1004': 'password failed', '1005': 'Password format failed', '1006': 'verify code does not exists or already expired or already used.', '1007': 'The verify code sent failed. ', '1008': 'Get phone number failed', '1009': 'phone number format failed. ', '1010': '已领取会员', "1011": '会员已过期 ', "1012": "Membership has expired", "1013": "创建内部测试用户失败", "1014": "已指定相同权限, 请勿重复设置", "1015": "仅允许【内部定制用户】绑定【内部定制商品】", "1016": "仅允许【定制用户】绑定【定制商品】", "1017": 'Please Check Email Format.', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = self.error_code def __str__(self): return self.error_msg class PayError(Exception): def __init__(self, error_code, error_message=None): super().__init__(self) self.error_dic = { '3001': 'Product does not exist', '3002': 'Trade number does not exists', '3003': 'Recharge does not exists.', '3004': 'Payment Failed', '3005': 'Price failed', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = error_message def __str__(self): return self.error_msg class DBError(Exception): def __init__(self, error_code, error_message=None): super().__init__(self) self.error_dic = { '4001': 'Get recharge list failed. ', '4002': 'Add new item failed. ', '4003': 'Item has already exists. ', '4004': 'Item does not exists. ', '4005': 'Get object failed', '4006': 'The currently deleted item is being referenced. ', '4007': 'Statistics of all data error. ', '4008': 'Statistical classification data error', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = error_message def __str__(self): return self.error_msg class TokenError(Exception): def __init__(self, error_code, error_message=None): super().__init__(self) self.error_dic = { '5000': 'Get token failed. ', '5001': 'Token has already expired. ', '5002': 'Illegal Ip. ', '5003': 'Token does not exist. ', '5005': 'token does not match the user. ', "5006": 'Current user is not member. ', "5007": 'Member has expired. ', "5008": 'Current user is not admin.', "5009": 'Token format error.', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = error_message def __str__(self): return self.error_msg class BackstageError(Exception): def __init__(self, error_code, error_message=None): super().__init__(self) self.error_dic = { '6000': 'Permission denied. ', '6001': 'Token has already expired. ', '6002': 'Illegal Ip. ', '6003': 'Token does not exist. ', '6004': 'token does not match the user', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = error_message def __str__(self): return self.error_msg class ShopError(Exception): def __init__(self, error_code, error_message=None): super().__init__(self) self.error_dic = { '7000': '第三方订单号不存在. ', '7001': '订单号不存在. ', '7002': 'Current page does not exists. ', '7003': 'Secondary menu does not exists. ', '7004': 'Main menu does not exists.', '7005': 'Character does not exists.', '7006': 'The current product has been favorited. ', '7007': 'Item not collected. ', '7008': 'Statistics data error.', '7009': 'Data classification or sorting error.', '7010': 'Generate product data error.', '7011': 'Statistical product type error.', '7012': '找不到对应订单', '7013': '商城更新资源失败', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = error_message def __str__(self): return self.error_msg class PersonalItemError(Exception): def __init__(self, error_code, error_message=None): super().__init__(self) self.error_dic = { '8000': 'User did not purchase this product. ', '8001': 'Product type does not support download. ', } self.error_code = error_code if self.error_code in self.error_dic: self.error_msg = self.error_dic.get(self.error_code) else: self.error_msg = error_message def __str__(self): return self.error_msg
conf_my_cnf_xenial = """[mysqld] bind-address = 0.0.0.0 default-storage-engine = innodb innodb_file_per_table max_connections = 4096 collation-server = utf8_general_ci character-set-server = utf8 innodb_autoinc_lock_mode=2 innodb_flush_log_at_trx_commit=0 innodb_buffer_pool_size=122M # MariaDB Galera Cluster in Xenial wsrep_cluster_name="galera_cluster" wsrep_cluster_address="{{ wsrep_cluster_address }}" wsrep_node_name="{{ wsrep_node_name }}" wsrep_node_address="{{ wsrep_node_address }}" wsrep_provider=/usr/lib/libgalera_smm.so wsrep_provider_options="pc.recovery=TRUE;gcache.size=300M" wsrep_sst_method=rsync binlog_format=ROW """
def elevadorLotado(paradas, capacidade): energiaGasta = 0 while paradas: ultimo = paradas[-1] energiaGasta += 2*ultimo paradas = paradas[:-capacidade] return energiaGasta testes = int(input()) for x in range(testes): NCM = input().split() capacidade = int(NCM[1]) destinhos = list(map(int,input().split())) destinhos.sort() s = elevadorLotado(destinhos, capacidade) print(s)
with open('EN_op_1_57X32A15_31.csv','r') as csvfile: reader = csv.reader(csvfile) for row in reader: print(row[1])
class Blosum62: """Score matrix BLOSUM62""" def __init__(self): self.blosum62 = { 'A': {'A': 4, 'R':-1, 'N':-2, 'D':-2, 'C': 0, 'Q':-1, 'E':-1, 'G': 0, 'H':-2, 'I':-1, 'L':-1, 'K':-1, 'M':-1, 'F':-2, 'P':-1, 'S': 1, 'T': 0, 'W':-3, 'Y':-2, 'V': 0, 'B':-2, 'Z':-1, 'X': 0, '-':-4}, 'R': {'A':-1, 'R': 5, 'N': 0, 'D':-2, 'C':-3, 'Q': 1, 'E': 0, 'G':-2, 'H': 0, 'I':-3, 'L':-2, 'K': 2, 'M':-1, 'F':-3, 'P':-2, 'S':-1, 'T':-1, 'W':-3, 'Y':-2, 'V':-3, 'B':-1, 'Z': 0, 'X':-1, '-':-4}, 'N': {'A':-2, 'R': 0, 'N': 6, 'D': 1, 'C':-3, 'Q': 0, 'E': 0, 'G': 0, 'H': 1, 'I':-3, 'L':-3, 'K': 0, 'M':-2, 'F':-3, 'P':-2, 'S': 1, 'T': 0, 'W':-4, 'Y':-2, 'V':-3, 'B': 3, 'Z': 0, 'X':-1, '-':-4}, 'D': {'A':-2, 'R':-2, 'N': 1, 'D': 6, 'C':-3, 'Q': 0, 'E': 2, 'G':-1, 'H':-1, 'I':-3, 'L':-4, 'K':-1, 'M':-3, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-4, 'Y':-3, 'V':-3, 'B': 4, 'Z': 1, 'X':-1, '-':-4}, 'C': {'A': 0, 'R':-3, 'N':-3, 'D':-3, 'C': 9, 'Q':-3, 'E':-4, 'G':-3, 'H':-3, 'I':-1, 'L':-1, 'K':-3, 'M':-1, 'F':-2, 'P':-3, 'S':-1, 'T':-1, 'W':-2, 'Y':-2, 'V':-1, 'B':-3, 'Z':-3, 'X':-2, '-':-4}, 'Q': {'A':-1, 'R': 1, 'N': 0, 'D': 0, 'C':-3, 'Q': 5, 'E': 2, 'G':-2, 'H': 0, 'I':-3, 'L':-2, 'K': 1, 'M': 0, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-2, 'Y':-1, 'V':-2, 'B': 0, 'Z': 3, 'X':-1, '-':-4}, 'E': {'A':-1, 'R': 0, 'N': 0, 'D': 2, 'C':-4, 'Q': 2, 'E': 5, 'G':-2, 'H': 0, 'I':-3, 'L':-3, 'K': 1, 'M':-2, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-3, 'Y':-2, 'V':-2, 'B': 1, 'Z': 4, 'X':-1, '-':-4}, 'G': {'A': 0, 'R':-2, 'N': 0, 'D':-1, 'C':-3, 'Q':-2, 'E':-2, 'G': 6, 'H':-2, 'I':-4, 'L':-4, 'K':-2, 'M':-3, 'F':-3, 'P':-2, 'S': 0, 'T':-2, 'W':-2, 'Y':-3, 'V':-3, 'B':-1, 'Z':-2, 'X':-1, '-':-4}, 'H': {'A':-2, 'R': 0, 'N': 1, 'D':-1, 'C':-3, 'Q': 0, 'E': 0, 'G':-2, 'H': 8, 'I':-3, 'L':-3, 'K':-1, 'M':-2, 'F':-1, 'P':-2, 'S':-1, 'T':-2, 'W':-2, 'Y': 2, 'V':-3, 'B': 0, 'Z': 0, 'X':-1, '-':-4}, 'I': {'A':-1, 'R':-3, 'N':-3, 'D':-3, 'C':-1, 'Q':-3, 'E':-3, 'G':-4, 'H':-3, 'I': 4, 'L': 2, 'K':-3, 'M': 1, 'F': 0, 'P':-3, 'S':-2, 'T':-1, 'W':-3, 'Y':-1, 'V': 3, 'B':-3, 'Z':-3, 'X':-1, '-':-4}, 'L': {'A':-1, 'R':-2, 'N':-3, 'D':-4, 'C':-1, 'Q':-2, 'E':-3, 'G':-4, 'H':-3, 'I': 2, 'L': 4, 'K':-2, 'M': 2, 'F': 0, 'P':-3, 'S':-2, 'T':-1, 'W':-2, 'Y':-1, 'V': 1, 'B':-4, 'Z':-3, 'X':-1, '-':-4}, 'K': {'A':-1, 'R': 2, 'N': 0, 'D':-1, 'C':-3, 'Q': 1, 'E': 1, 'G':-2, 'H':-1, 'I':-3, 'L':-2, 'K': 5, 'M':-1, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-3, 'Y':-2, 'V':-2, 'B': 0, 'Z': 1, 'X':-1, '-':-4}, 'M': {'A':-1, 'R':-1, 'N':-2, 'D':-3, 'C':-1, 'Q': 0, 'E':-2, 'G':-3, 'H':-2, 'I': 1, 'L': 2, 'K':-1, 'M': 5, 'F': 0, 'P':-2, 'S':-1, 'T':-1, 'W':-1, 'Y':-1, 'V': 1, 'B':-3, 'Z':-1, 'X':-1, '-':-4}, 'F': {'A':-2, 'R':-3, 'N':-3, 'D':-3, 'C':-2, 'Q':-3, 'E':-3, 'G':-3, 'H':-1, 'I': 0, 'L': 0, 'K':-3, 'M': 0, 'F': 6, 'P':-4, 'S':-2, 'T':-2, 'W': 1, 'Y': 3, 'V':-1, 'B':-3, 'Z':-3, 'X':-1, '-':-4}, 'P': {'A':-1, 'R':-2, 'N':-2, 'D':-1, 'C':-3, 'Q':-1, 'E':-1, 'G':-2, 'H':-2, 'I':-3, 'L':-3, 'K':-1, 'M':-2, 'F':-4, 'P': 7, 'S':-1, 'T':-1, 'W':-4, 'Y':-3, 'V':-2, 'B':-2, 'Z':-1, 'X':-2, '-':-4}, 'S': {'A': 1, 'R':-1, 'N': 1, 'D': 0, 'C':-1, 'Q': 0, 'E': 0, 'G': 0, 'H':-1, 'I':-2, 'L':-2, 'K': 0, 'M':-1, 'F':-2, 'P':-1, 'S': 4, 'T': 1, 'W':-3, 'Y':-2, 'V':-2, 'B': 0, 'Z': 0, 'X': 0, '-':-4}, 'T': {'A': 0, 'R':-1, 'N': 0, 'D':-1, 'C':-1, 'Q':-1, 'E':-1, 'G':-2, 'H':-2, 'I':-1, 'L':-1, 'K':-1, 'M':-1, 'F':-2, 'P':-1, 'S': 1, 'T': 5, 'W':-2, 'Y':-2, 'V': 0, 'B':-1, 'Z':-1, 'X': 0, '-':-4}, 'W': {'A':-3, 'R':-3, 'N':-4, 'D':-4, 'C':-2, 'Q':-2, 'E':-3, 'G':-2, 'H':-2, 'I':-3, 'L':-2, 'K':-3, 'M':-1, 'F': 1, 'P':-4, 'S':-3, 'T':-2, 'W':11, 'Y': 2, 'V':-3, 'B':-4, 'Z':-3, 'X':-2, '-':-4}, 'Y': {'A':-2, 'R':-2, 'N':-2, 'D':-3, 'C':-2, 'Q':-1, 'E':-2, 'G':-3, 'H': 2, 'I':-1, 'L':-1, 'K':-2, 'M':-1, 'F': 3, 'P':-3, 'S':-2, 'T':-2, 'W': 2, 'Y': 7, 'V':-1, 'B':-3, 'Z':-2, 'X':-1, '-':-4}, 'V': {'A': 0, 'R':-3, 'N':-3, 'D':-3, 'C':-1, 'Q':-2, 'E':-2, 'G':-3, 'H':-3, 'I': 3, 'L': 1, 'K':-2, 'M': 1, 'F':-1, 'P':-2, 'S':-2, 'T': 0, 'W':-3, 'Y':-1, 'V': 4, 'B':-3, 'Z':-2, 'X':-1, '-':-4}, 'B': {'A':-2, 'R':-1, 'N': 3, 'D': 4, 'C':-3, 'Q': 0, 'E': 1, 'G':-1, 'H': 0, 'I':-3, 'L':-4, 'K': 0, 'M':-3, 'F':-3, 'P':-2, 'S': 0, 'T':-1, 'W':-4, 'Y':-3, 'V':-3, 'B': 4, 'Z': 1, 'X':-1, '-':-4}, 'Z': {'A':-1, 'R': 0, 'N': 0, 'D': 1, 'C':-3, 'Q': 3, 'E': 4, 'G':-2, 'H': 0, 'I':-3, 'L':-3, 'K': 1, 'M':-1, 'F':-3, 'P':-1, 'S': 0, 'T':-1, 'W':-3, 'Y':-2, 'V':-2, 'B': 1, 'Z': 4, 'X':-1, '-':-4}, 'X': {'A': 0, 'R':-1, 'N':-1, 'D':-1, 'C':-2, 'Q':-1, 'E':-1, 'G':-1, 'H':-1, 'I':-1, 'L':-1, 'K':-1, 'M':-1, 'F':-1, 'P':-2, 'S': 0, 'T': 0, 'W':-2, 'Y':-1, 'V':-1, 'B':-1, 'Z':-1, 'X':-1, '-':-4}, '-': {'A':-4, 'R':-4, 'N':-4, 'D':-4, 'C':-4, 'Q':-4, 'E':-4, 'G':-4, 'H':-4, 'I':-4, 'L':-4, 'K':-4, 'M':-4, 'F':-4, 'P':-4, 'S':-4, 'T':-4, 'W':-4, 'Y':-4, 'V':-4, 'B':-4, 'Z':-4, 'X':-4, '-': 1} } def score(self, c1, c2): return(self.blosum62[c1][c2]) def calc_score(self, s1, s2): if len(s1) != len(s2): return(-1) score = 0 for i in range(len(s1)): score += self.blosum62[s1[i]][s2[i]] return(score) class SM_Nucleotide: """Score matrix Nucleotide""" def __init__(self): self.sm = { 'A': {'A': 2, 'T':-1, 'G':-1, 'C':-1, '*':-2}, 'T': {'A':-1, 'T': 2, 'G':-1, 'C':-1, '*':-2}, 'G': {'A':-1, 'T':-1, 'G': 2, 'C':-1, '*':-2}, 'C': {'A':-1, 'T':-1, 'G':-1, 'C': 2, '*':-2}, '*': {'A':-2, 'T':-2, 'G':-2, 'C':-2, '*':-1} } def score(self, c1, c2): return(self.sm[c1][c2]) def calc_score(self, s1, s2): if len(s1) != len(s2): return(-1) score = 0 for i in range(len(s1)): score += self.sm[s1[i]][s2[i]] return(score)
chars = { 'A': ['010', '101', '111', '101', '101'], 'B': ['110', '101', '111', '101', '110'], 'C': ['011', '100', '100', '100', '011'], 'D': ['110', '101', '101', '101', '110'], 'E': ['111', '100', '111', '100', '111'], 'F': ['111', '100', '111', '100', '100'], 'G': ['0111', '1000', '1011', '1001', '0110'], 'H': ['101', '101', '111', '101', '101'], 'I': ['111', '010', '010', '010', '111'], 'J': ['111', '010', '010', '010', '110'], 'K': ['1001', '1010', '1100', '1010', '1001'], 'L': ['100', '100', '100', '100', '111'], 'M': ['10001', '11011', '10101', '10001', '10001'], 'N': ['1001', '1101', '1111', '1011', '1001'], 'O': ['010', '101', '101', '101', '010'], 'P': ['110', '101', '110', '100', '100'], 'Q': ['0110', '1001', '1001', '1011', '0111'], 'R': ['110', '101', '110', '101', '101'], 'S': ['011', '100', '011', '001', '110'], 'T': ['111', '010', '010', '010', '010'], 'U': ['101', '101', '101', '101', '010'], 'V': ['10001', '10001', '10001', '01010', '00100'], 'W': ['10001', '10001', '10101', '11011', '10001'], 'X': ['1001', '0110', '0110', '0110', '1001'], 'Y': ['101', '101', '010', '010', '010'], 'Z': ['1111', '0010', '0100', '1000', '1111'], '.': ['0', '0', '0', '0', '1'], ':': ['0', '1', '0', '1', '0'], '!': ['1', '1', '1', '0', '1'], '?': ['01110', '10001', '00110', '00000', '00100'], '\'': ['11', '11', '00', '00', '00'], '\"': ['11', '00', '00', '00', '00'], ' ': ['0', '0', '0', '0', '0'], ',': ['00', '00', '00', '01', '11'], '/': ['001', '011', '010', '110', '100'], '\\': ['100', '110', '010', '011', '001'], '0': ['010', '101', '101', '101', '010'], '1': ['010', '110', '010', '010', '111'], '2': ['011', '101', '010', '100', '111'], '3': ['111', '001', '111', '001', '111'], '4': ['011', '101', '111', '001', '001'], '5': ['111', '100', '111', '001', '111'], '6': ['111', '100', '111', '101', '111'], '7': ['111', '001', '010', '100', '100'], '8': ['111', '101', '111', '101', '111'], '9': ['111', '101', '111', '001', '111'] } def get_mapping(string): global chars mapping = ['','','','',''] string = string.upper() for char in string: if char in chars: char_mapping = chars[char] else: char_mapping = ['0','0','0','0','0'] mapping = [ mapping[0] + char_mapping[0] + '0', mapping[1] + char_mapping[1] + '0', mapping[2] + char_mapping[2] + '0', mapping[3] + char_mapping[3] + '0', mapping[4] + char_mapping[4] + '0' ] return mapping
SAGA_ENABLED = 1 MIN_DETECTED_FACE_WIDTH = 20 MIN_DETECTED_FACE_HEIGHT = 20 PICKLE_FILES_DIR = "/app/facenet/resources/output" MODEL_FILES_DIR = "/app/facenet/resources/model" UPLOAD_DIR = "/app/resources/images/" # PICKLE_FILES_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/output' # MODEL_FILES_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/model' # UPLOAD_DIR = '/Users/ashishgupta/git/uPresent/face-recognition/resources/images/' # DATASET_PATH = '/Users/anchitseth/Desktop/facenet-data-vol/dataset' # PICKLE_FILES_DIR = '/Users/anchitseth/Desktop/facenet-data-vol/output' # MODEL_FILES_DIR = '/Users/anchitseth/Desktop/facenet-data-vol/model'
# -*- coding: utf-8 -*- """ Created on Mon Jul 22 21:48:29 2019 @author: zejiran. """ def fecha_a_dias(anio: int, mes: int, dia: int) -> int: """ Convierte una fecha a días, ingresada comop año, mes y día. Se supone que todos los meses tienen 30 días. Parámetros: anio (int) Año de la fecha. Número entero positivo. mes (int) Mes de la fecha. Número entero positivo. dia (int) Día de la fecha. Número entero positivo. Retorno: int: La fecha ingresada convertida a días. """ dias = (anio * 360) + (mes * 30) + dia return dias def diferencia_fechas(anio_fecha2: int, mes_fecha2: int, dia_fecha2: int, anio_fecha1: int, mes_fecha1: int, dia_fecha1: int) -> int: """ Calcula la diferencia en días entre dos fechas cualesquiera fecha1 y fecha2 (expresadas en año, mes y día). Se supone que la fecha2 siempre es superior a la fecha1. Parámetros: anio_fecha2 (int) Año de la fecha2. Número entero positivo. mes_fecha2 (int) Mes de la fecha2. Número entero positivo. dia_fecha2 (int) Día de la fecha2. Número entero positivo. anio_fecha1 (int) Año de la fecha1. Número entero positivo. mes_fecha1 (int) Mes de la fecha1. Número entero positivo. dia_fecha1 (int) Día de la fecha1. Número entero positivo. Retorno: int: Diferencia en días entre las dos fechas. """ dias_fecha1 = fecha_a_dias(anio_fecha1, mes_fecha1, dia_fecha1) dias_fecha2 = fecha_a_dias(anio_fecha2, mes_fecha2, dia_fecha2) return dias_fecha2 - dias_fecha1 def calcular_edad(anio_actual: int, mes_actual: int, dia_actual: int, anio_nacimiento: int, mes_nacimiento: int, dia_nacimiento: int) -> str: """ Calcula la edad de un persona dada su fecha de nacimiento y la fecha actual. Parámetros: anio_actual (int) Año actual. Número entero positivo. mes_actual (int) Mes actual. Número entero positivo. dia_actual (int) Día actual. Número entero positivo. anio_nacimiento (int) Año de nacimiento. Número entero positivo. mes_nacimiento (int) Mes de nacimiento. Número entero positivo. dia_nacimiento (int) Día de nacimiento. Número entero positivo. Retorno: str: Mensaje informando la edad de la persona. El mensaje debe tener el siguiente formato: "La persona tiene X años, Y meses y Z días" """ edad_en_dias_totales = diferencia_fechas(anio_actual, mes_actual, dia_actual, anio_nacimiento, mes_nacimiento, dia_nacimiento) anios_cumplidos = edad_en_dias_totales // 360 sobrante_de_los_anios = edad_en_dias_totales % 360 meses_cumplidos = sobrante_de_los_anios // 30 dias_cumplidos = sobrante_de_los_anios % 30 return "La persona tiene " + str(anios_cumplidos) + " años, " + str(meses_cumplidos) + " meses y " + str( dias_cumplidos) + " días"
""" VIS_LR Visualization tools for learning rate stuff Stefan Wong 2019 """ def plot_lr_vs_acc(ax, lr_data, acc_data, **kwargs): title = kwargs.pop('title', 'Learning Rate vs. Accuracy') if len(lr_data) != len(acc_data): plot_len = min([len(lr_data), len(acc_data)]) else: plot_len = len(lr_data) ax.plot(lr_data[:plot_len], acc_data[:plot_len]) #ax.set_xlim([lr_data[0], lr_data[plot_len]]) #ax.set_ylim([acc_data[0], acc_data[plot_len]]) ax.set_xlabel('Accuracy') ax.set_ylabel('Learning Rate') ax.set_title(title)
class Contact: def __init__(self, first_name: str, second_name: str, phone_number: str): self._first_name = first_name self._second_name = second_name self._phone_number = phone_number @property def first_name(self): return self._first_name @property def second_name(self): return self._second_name @property def phone_number(self): return self._phone_number @first_name.setter def first_name(self, name: str): self._first_name = name @second_name.setter def second_name(self, surname: str): self._second_name = surname @phone_number.setter def phone_number(self, number: str): self._phone_number = number
'''A fórmula para calcular a área de uma circunferência é: area = π . raio2. Considerando para este problema que π = 3.14159: - Efetue o cálculo da área, elevando o valor de raio ao quadrado e multiplicando por π.''' R = float(input()) A = 3.14159 * (R ** 2) print('A={:.4f}'.format(A))
def answer(l): res = 0 length = len(l) for x in xrange(length): left = 0 right = 0 for i in xrange(x): if not (l[x] % l[i]): left = left + 1 for i in xrange(x + 1, length): if not (l[i] % l[x]): right = right + 1 res = res + left * right return res # Provided test cases. assert(answer([1, 1, 1]) == 1) assert(answer([1, 2, 3, 4, 5, 6]) == 3) # Custom test cases. assert(answer([1]) == 0) assert(answer([1, 2]) == 0) assert(answer([2, 4]) == 0) assert(answer([1, 1, 1, 1]) == 4) assert(answer([1, 1, 1, 1, 1]) == 10) assert(answer([1, 1, 1, 1, 1, 1]) == 20) assert(answer([1, 1, 1, 1, 1, 1, 1]) == 35) assert(answer([1, 1, 2]) == 1) assert(answer([1, 1, 2, 2]) == 4) assert(answer([1, 1, 2, 2, 2]) == 10) assert(answer([1, 1, 2, 2, 2, 3]) == 11) assert(answer([1, 2, 4, 8, 16]) == 10) assert(answer([2, 4, 5, 9, 12, 34, 45]) == 1) assert(answer([2, 2, 2, 2, 4, 4, 5, 6, 8, 8, 8]) == 90) assert(answer([2, 4, 8]) == 1) assert(answer([2, 4, 8, 16]) == 4) assert(answer([3, 4, 2, 7]) == 0) assert(answer([6, 5, 4, 3, 2, 1]) == 0) assert(answer([4, 7, 14]) == 0) assert(answer([4, 21, 7, 14, 8, 56, 56, 42]) == 9) assert(answer([4, 21, 7, 14, 56, 8, 56, 4, 42]) == 7) assert(answer([4, 7, 14, 8, 21, 56, 42]) == 4) assert(answer([4, 8, 4, 16]) == 2)
# NOTE: The sitename and dataname corresponding to the observation are 'y' by default # Any latents that are not population level model_constants = { 'arm.anova_radon_nopred': { 'population_effects':{'mu_a', 'sigma_a', 'sigma_y'}, 'ylims':(1000, 5000), 'ylims_zoomed':(1000, 1200) }, 'arm.anova_radon_nopred_chr': { 'population_effects':{'sigma_a', 'sigma_y', 'mu_a'}, 'ylims':(1000, 5000), 'ylims_zoomed':(1000, 1200) }, 'arm.congress': { 'population_effects':{'beta', 'sigma'}, 'sitename':'vote_88', 'dataname':'vote_88', 'ylims':(1000, 5000), # CHANGE! 'ylims_zoomed':(1000, 1200) # CHANGE! }, 'arm.earnings_latin_square': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_b1", "sigma_b2", "sigma_c", "sigma_d", "sigma_y", 'mu_a1', 'mu_a2', 'mu_b1', 'mu_b2', 'mu_c', 'mu_d'}, 'ylims':(800, 5000), 'ylims_zoomed':(800, 5000) }, 'arm.earnings_latin_square_chr': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_b1", "sigma_b2", "sigma_c", "sigma_d", "sigma_y", 'mu_a1', 'mu_a2', 'mu_b1', 'mu_b2', 'mu_c', 'mu_d'}, 'ylims':(800, 5000), 'ylims_zoomed':(800, 5000) }, 'arm.earnings_vary_si': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_y", "mu_a1", "mu_a2"}, 'sitename':'log_earn', 'dataname':'log_earn', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.earnings_vary_si_chr': { 'population_effects':{"sigma_a1", "sigma_a2", "sigma_y", "mu_a1", "mu_a2"}, 'sitename':'log_earn', 'dataname':'log_earn', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.earnings1': { 'population_effects':{"sigma", "beta"}, 'sitename':'earn_pos', 'dataname':'earn_pos', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.earnings2': { 'population_effects':{"sigma", "beta"}, 'sitename':'log_earnings', 'dataname':'log_earnings', 'ylims':(800, 5000), # CHANGE! 'ylims_zoomed':(800, 5000) # CHANGE! }, 'arm.election88_ch14': { 'population_effects':{'mu_a', 'sigma_a', 'b'}, 'ylims':(1200, 2000), 'ylims_zoomed':(1200, 1400) }, 'arm.election88_ch19': { 'population_effects':{'beta', 'mu_age', 'sigma_age', 'mu_edu', 'sigma_edu', 'mu_age_edu', 'sigma_age_edu', 'mu_region', 'sigma_region', 'b_v_prev'}, 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.electric': { 'population_effects':{'beta', 'mu_a', 'sigma_a', 'sigma_y'}, 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.electric_1a': { 'population_effects':set(), 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.hiv': { 'population_effects':{'mu_a1', 'sigma_a1', 'mu_a2', 'sigma_a2', 'sigma_y'}, 'ylims':(1200, 2000), # CHANGE! 'ylims_zoomed':(1200, 1400) # CHANGE! }, 'arm.wells_dist': { 'population_effects':{'beta'}, 'sitename':'switched', 'dataname':'switched', 'ylims':(2000, 7500), 'ylims_zoomed':(2000, 2500) }, 'arm.wells_dae_inter_c': { 'population_effects':{'beta'}, 'sitename':'switched', 'dataname':'switched', 'ylims':(1800, 4000), 'ylims_zoomed':(1800, 2200) }, 'arm.radon_complete_pool': { 'population_effects':{'beta', 'sigma'}, 'ylims':(1000, 4000), 'ylims_zoomed':(1000, 1400) }, 'arm.radon_group': { 'population_effects':{'beta', 'sigma', 'mu_alpha', 'sigma_alpha', 'mu_beta', 'sigma_beta'}, 'ylims':(1000, 4000), 'ylims_zoomed':(1000, 1200), }, 'arm.radon_inter_vary': { 'population_effects':{'beta', 'sigma_y', 'sigma_a', 'sigma_b', 'sigma_beta', 'mu_a', 'mu_b', 'mu_beta'}, 'ylims':(1000, 5000), 'ylims_zoomed':(1000, 1300) }, }
def addStrings(num1: str, num2: str) -> str: i, j = len(num1) - 1, len(num2) - 1 tmp = 0 result = "" while i >= 0 or j >= 0: if i >= 0: tmp += int(num1[i]) i -= 1 if j >= 0: tmp += int(num2[j]) j -= 1 result = str(tmp % 10) + result tmp //= 10 if tmp != 0: result = str(tmp) + result return result if __name__ == "__main__": num1 = "999999" num2 = "99" result = addStrings(num1, num2) print(result)
""" Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param A: a list of integer @return: a tree node """ def sortedArrayToBST(self, A): # write your code here if len(A) == 0: return None mid = len(A) / 2 node = TreeNode(A[mid]) node.left = self.sortedArrayToBST(A[:mid]) node.right = self.sortedArrayToBST(A[(mid+1):]) return node
intin = int(input()) if intin == 2: print("NO") elif intin%2==0: if intin%4==0: print("YES") elif (intin-2)%4==0: print("YES") else: print("NO") else: print("NO")
def rgb(r, g, b): s="" if r>255: r=255 elif g>255: g=255 elif b>255: b=255 if r<0: r=0 elif g<0: g=0 elif b<0: b=0 r='{0:x}'.format(r) g='{0:x}'.format(g) b='{0:x}'.format(b) if int(r,16)<=15 and int(r,16)>=0: r='0'+r if int(g,16)<=15 and int(g,16)>=0: g='0'+g if int(b,16)<=15 and int(b,16)>=0: b='0'+b s+=r+g+b return s.upper()
# https://www.reddit.com/r/dailyprogrammer/comments/1ystvb/022414_challenge_149_easy_disemvoweler/ def disem(str): result = '' rem_vowels = '' vowels = 'aeiou' for c in str: if c not in vowels and not c.isspace(): result += c elif not c.isspace(): rem_vowels += c print(result + '\n' + rem_vowels) def main(): phrase = input('\nPlease enter a line: ') disem(phrase) choice = input('\nAgain? ') if choice != 'n': main() quit() main() # Need to actually call the main() method!
''' @description 2019/09/22 20:53 '''
def setup(): size (500,500) background (100) smooth() noLoop() strokeWeight(15) str(100) def draw (): fill (250) rect (100,100, 100,100) fill (50) rect (200,200, 50,100)
#Write a function that accepts a 2D list of integers and returns the maximum EVEN value for the entire list. #You can assume that the number of columns in each row is the same. #Your function should return None if the list is empty or all the numbers in the 2D list are odd. #Do NOT use python's built in max() function. def even_empty_odd(list2d): len_list = 0 even_numbers = [] odd_numbers = [] count = 0 #if the list is empty for list_number in list2d: len_list += len(list_number) if len_list == 0: return None #if the list is gretaer than zero else: for list_number in list2d: for number in list_number: #find the even numbers if number % 2 == 0: even_numbers.append(number) #append all the even numbers in the even_numbers list else: #find the odd numbers odd_numbers.append(number) #append all the odd numbers in the odd_numbers list count += 1 #Compare if the len of the odd_numbers list is equal to count #if True that means that all the numbers are odds if len(odd_numbers) == count: return "All the numbers in the list are odds" #if not it means that at least there is onw even number else: even_numbers.sort() return even_numbers[len(even_numbers)-1] print(even_empty_odd([[1,8],[3,2]]))
class PolicyOwner(basestring): """ cluster-admin|vserver-admin Possible values: <ul> <li> "cluster_admin" , <li> "vserver_admin" </ul> """ @staticmethod def get_api_name(): return "policy-owner"
""" HealthDES - A python library to support discrete event simulation in health and social care """ class ResourceBase: # TODO: Build out the do and query functions for person, activity and resource objects. # Need to create dictionary of actions and parameters. # Subclassing allows dictionary of actions/ activities to be extended. # Need to provide error checking if actions/ parameters not in dictionary. def do(self, action, **kwargs): """ Perform an action on the person """ pass def query(self, param): """ Get a parameter from the person.""" pass
### assuming you have Google Chrome installed... ## remember `pip3 install -r setup.py` before trying any scrapers in this dir # have a nice day selenium chromedriver requests
class Power: def __init__(self, power_id, name, amount): self.power_id = power_id self.power_name = name self.amount = amount @classmethod def from_json(cls, json_object): return cls(json_object["id"], json_object["name"], json_object["amount"]) def __eq__(self, other): return self.power_id == other.power_id and self.amount == other.amount
DB_PORT=5432 DB_USERNAME="postgres" DB_PASSWORD="password" DB_HOST="127.0.0.1" DB_DATABASE="eventtriggertest"
# -*- coding: utf-8 -*- """ Created on Wed Mar 14 20:07:55 2018 @author: vegetto """ # Local versus Global def local(): # m doesn't belong to the scope defined by the local function so Python will keep looking into the next enclosing scope. m is finally found in the global scope print(m, 'printing from the local scope') m = 5 print(m, 'printing from the global scope') local()
class WindowNeighbor: """The window class for finding the neighbor pixels around the center""" def __init__(self, width, center, image): # center is a list of [row, col, Y_intensity] self.center = [center[0], center[1], image[center][0]] self.width = width self.neighbors = None self.find_neighbors(image) self.mean = None self.var = None def find_neighbors(self, image): self.neighbors = [] ix_r_min = max(0, self.center[0] - self.width) ix_r_max = min(image.shape[0], self.center[0] + self.width + 1) ix_c_min = max(0, self.center[1] - self.width) ix_c_max = min(image.shape[1], self.center[1] + self.width + 1) for r in range(ix_r_min, ix_r_max): for c in range(ix_c_min, ix_c_max): if r == self.center[0] and c == self.center[1]: continue self.neighbors.append([r, c, image[r, c, 0]]) def __str__(self): return 'windows c=(%d, %d, %f) size: %d' % ( self.center[0], self.center[1], self.center[2], len(self.neighbors) )
class Solution(object): def findLengthOfLCIS(self, nums): """ :type nums: List[int] :rtype: int """ start = 0 prev = None m = 0 for i, n in enumerate(nums): if prev is not None: if n <= prev: start = i m = max(m, i - start + 1) prev = n return m
setting = { 'file': './data/crime2010_2018.csv', 'limit': 10000, 'source': [0,1,2,3,7,8,10,11,14,16,23,5,25], 'vars': { 0 : 'num', 1 : 'date_reported', 2:'date_occured', 3:'time_occured', 7:'crime_code', 8:'crime_desc', 10:'victim_age', 11:'victim_sex', 14:'premise_desc', 16:'weapon', 23:'address', 5:'area',25:'location' } }
'''from axju.core.tools import SmartCLI from axju.worker.git import GitWorker def main(): cli = SmartCLI(GitWorker) cli.run() if __name__ == '__main__': main() '''
# -*- coding: utf-8 -*- class PaytabsApiError(Exception): """Exception raised when an a RequestHandler indicates the request failed. Attributes: code -- the error code returned from the API msg_english -- explanation of the error """ def __init__(self, code, message): self.code = code self.massage = message super(PaytabsApiError, self).__init__(message, )
#!/usr/bin/python # -*- coding: utf-8 -*- # (c) 2017, Michael Eaton <[email protected]> # # This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # this is a windows documentation stub. actual code lives in the .ps1 # file of the same name ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = r''' --- module: win_firewall version_added: '2.4' short_description: Enable or disable the Windows Firewall description: - Enable or Disable Windows Firewall profiles. options: profiles: description: - Specify one or more profiles to change. choices: - Domain - Private - Public default: [Domain, Private, Public] state: description: - Set state of firewall for given profile. choices: - enabled - disabled requirements: - This module requires Windows Management Framework 5 or later. author: Michael Eaton (@MichaelEaton83) ''' EXAMPLES = r''' - name: Enable firewall for Domain, Public and Private profiles win_firewall: state: enabled profiles: - Domain - Private - Public tags: enable_firewall - name: Disable Domain firewall win_firewall: state: disabled profiles: - Domain tags: disable_firewall ''' RETURN = r''' enabled: description: current firewall status for chosen profile (after any potential change) returned: always type: bool sample: true profiles: description: chosen profile returned: always type: string sample: Domain state: description: desired state of the given firewall profile(s) returned: always type: list sample: enabled '''
"""Top-level package for siphr.""" __author__ = """Shamindra Shrotriya""" __email__ = "[email protected]" __version__ = "0.1.0"
class ActivityBar: """ Content settings for the activity bar. """ def __init__(self, id: str, title: str, icon: str) -> None: self.id = id self.title = title self.icon = icon class StaticWebview: """ Content settings for a Static Webview. """ def __init__(self, id: str, html: str, title: str = None) -> None: self.id = id self.html = html self.title = title class InputBoxOptions: """ Options to configure the behavior of the input box UI. """ def __init__( self, title: str = None, password: bool = None, ignore_focus_out: bool = None, prompt: str = None, place_holder: str = None, value: str = None, ) -> None: self.title = title self.password = password self.ignoreFocusOut = ignore_focus_out self.prompt = prompt self.placeHolder = place_holder self.value = value class QuickPickOptions: """ Options to configure the behavior of the quick pick UI. """ def __init__( self, title: str = None, can_pick_many: bool = None, ignore_focus_out: bool = None, match_on_description: bool = None, place_holder: str = None, match_on_detail: bool = None, ) -> None: self.title = title self.canPickMany = can_pick_many self.ignoreFocusOut = ignore_focus_out self.matchOnDescription = match_on_description self.placeHolder = place_holder self.matchOnDetail = match_on_detail class QuickPickItem: """ Content settings for a Quick Pick Item. """ def __init__(self, label: str = None, detail: str = None, description: str = None, **options) -> None: self.label = label self.detail = detail self.description = description self.__dict__.update(options) class Undefined: """ An instance of this class is returned everytime javascript returns undefined. """ def __str__(self): return "undefined" def __bool__(self): return False def __eq__(self, other): return isinstance(other, self.__class__) undefined = Undefined() class Disposable: """ Represents a type which can release resources, such as event listening or a timer. """ def __init__(self, id): self.id = id def dispose(self): print(f'DI: {self.id}', flush=True, end='')
load("//webgen:webgen.bzl", "erb_file", "js_file", "scss_file", "website") def page(name, file, out=None, data=False, math=False, plot=False): extra_templates = [] if data: extra_templates.append("template/data.html") if math: extra_templates.append("template/mathjax.html") if plot: extra_templates.append("template/plot.html") if plot == "tape": extra_templates.append("template/plot_tape.html") erb_file( name = name, srcs = [file, "template/default.html"] + extra_templates, out = out if out else file, bootstrap = True, ) def script(name, file=None, files=[], out=None, plot=False): extra_sources = [] if plot: extra_sources.append("vis/js/plot.js") if plot == "prog" or plot == "tape": extra_sources.append("vis/js/plot_prog.js") if plot == "tape": extra_sources.append("vis/js/plot_tape.js") js_file( name = name, srcs = extra_sources + ([file] if file else []) + files, out = out if out else file, )
num1 = int(input('Digite o primeiro número: ')) num2 = int(input('Digite o segundo número: ')) if num1 == num2: print('Os números {} e {} são equivalentes.'.format(num1, num2)) elif num1 > num2: print('O número {} é maior que o número {}.'.format(num1, num2)) elif num2 > num1: print('O número {} é maior que o número {}.'.format(num2, num1))
class Solution: def uniquePaths(self, m, n): """ :type m: int :type n: int :rtype: int """ return int(math.factorial(m+n-2)/ (math.factorial(m-1)* math.factorial(n-1)))
def two_finger_sort(arr, brr): """ The two_finger_sort() is a function that takes two sorted lists as input parameters and returns a single sorted list. Its time complexity is O(n), but it also needs extra space to store the new sorted list. Explanation : arr = [1, 2, 34, 56], brr = [3, 5], crr = [] ^ ^ 1. Compare the elements that are at the beginning i.e. arr[0] and brr[0]. 2. Choose the smaller element and copy it to a new list i.e. arr[0] in this case. 3. Move the pointer to the next element i.e. arr[1] in this case. 4. Compare again and then move to step 2. 5. Complete the comparison till one of the lists is exhausted with the elements and then copy the rest of the elements in the other list to the list crr. 6. Return the crr list. crr = [1, 2, 3, 5, 34, 56] """ if arr == sorted(arr) and brr == sorted(brr): i = 0 j = 0 crr = [] while i < len(arr) and j < len(brr): if arr[i] > brr[j]: crr.append(brr[j]) j = j + 1 elif arr[i] == brr[j]: crr.append(arr[i]) crr.append(brr[j]) i = i + 1 j = j + 1 else : crr.append(arr[i]) i = i + 1 if i == len(arr): while j < len(brr): crr.append(brr[j]) j = j + 1 else : while i < len(arr): crr.append(arr[i]) i = i + 1 return crr else : return "Error : The input lists should be sorted." #For Debugging #print(two_finger_sort([1, 2, 3, 4, 56], [3, 5])) """ INPUT arr = [1, 2, 34, 56] brr = [3, 5] OUTPUT [1, 2, 3, 5, 34, 56] INPUT arr = [1, 2, 4, 3, 56] brr = [3, 5] OUTPUT Error : The input lists should be sorted. """
# A return statement in a Python function serves two purposes: # It immediately terminates the function and passes execution control back to the caller. # It provides a mechanism by which the function can pass data back to the caller. def f(): print('foo') print('bar') return f() # In this example, the return statement is actually superfluous. A function will # return to the caller when it falls off the end—that is, after the last # statement of the function body is executed. So, this function would behave # identically without the return statement def f1(x): if x < 0: return if x > 100: return print(x) print() f1(101) f1(-1) f1(50) # The first two calls to f() don’t cause any output, because a return statement # is executed and the function exits prematurely, before the print() statement # This sort of paradigm can be useful for error checking in a function # def f(): # if error_cond1: # return # if error_cond2: # return # if error_cond3: # return # <normal processing> def f2(): return 'foo' print(f2()) # A function can return any type of object # If multiple comma-separated expressions are specified in a return statement, # then they’re packed and returned as a tuple: def f3(): return 'foo', 'bar', 'baz', 'qux' print(type(f3())) # When no return value is given, a Python function returns the special Python # value None. The same thing happens if the function body doesn’t contain a # return statement at all and the function falls off the end def f4(): return print(f4()) # Revisiting the side-effects def double1(x): x *= 2 print(f'In double1(x), x = {x}') print() x = 10 print(f'Before calling double1(x), x = {x}') double1(x) print(f'After calling double1(x), x = {x}') # To update the value of x at caller end def double2(x): x *= 2 print(f'In double2(x), x = {x}') return x print() print(f'Before calling double2(x), x = {x}') x = double2(x) print(f'After calling double2(x), x = {x}') # using the side effect def double_list_while(x): i = 0 while i < len(x): x[i] *= 2 i += 1 # without using the side effect def double_list_for(x): r = [] for i in x: r.append(i * 2) return r a = [1, 2, 3, 4, 5] print() print(a) print(double_list_while(a), a) print(double_list_for(a), a)
#data kualitatif a = "the dogis hungry. The cat is bored. the snack is awake." s = a.split(".") print(s) print(s[0]) print(s[1]) print(s[2])
''' Completion sample module ''' def func_module_level(i, a='foo'): 'some docu' return i * a class ModClass: ''' some inner namespace class''' @classmethod def class_level_func(cls, boolean=True): return boolean class NestedClass: ''' some inner namespace class''' @classmethod def class_level_func(cls, a_str='foo', boolean=True): return boolean or a_str @classmethod def a_really_really_loooo_path_to_func(i=23, j='str'): '''## Some documentation over `multiple` lines - list1 - list2 ''' return i
N = int(input()) A = int(input()) for a in range(A+1): for j in range(21): if a + 500 * j == N: print("Yes") exit() print("No")
# ---------------------------------------------------------------- # Copyright 2016 Cisco Systems # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ------------------------------------------------------------------ """ service.py The base Service class. """ class Service(object): """ Base service class which can be extended for different ways of communicating to remote server """ def operate_on_object_or_dictionary(self, entity, function, args): result=None if isinstance(entity, dict): result = {} for module, child in entity.items(): result[module] = function(child, *args) else: result = function(entity, *args) return result def execute_payload(self, provider, payload, operation): reply = provider.execute(payload, operation) return reply
# Scrapy settings for uefispider project # # For simplicity, this file contains only the most important settings by # default. All the other settings are documented here: # # http://doc.scrapy.org/en/latest/topics/settings.html # BOT_NAME = 'uefispider' SPIDER_MODULES = ['uefispider.spiders'] NEWSPIDER_MODULE = 'uefispider.spiders' # Crawl responsibly by identifying yourself (and your website) on the user-agent USER_AGENT = 'uefispider (+https://github.com/theopolis/uefi-spider)' ITEM_PIPELINES = { 'uefispider.pipelines.UefispiderPipeline': 1 } COOKIES_DEBUG = True
class Solution: def baseNeg2(self, N: int) -> str: if N == 0: return "0" nums = [] while N != 0: r = N % (-2) N //= (-2) if r < 0: r += 2 N += 1 nums.append(r) return ''.join(map(str, nums[::-1]))
# 🚨 Don't change the code below 👇 print("Welcome to the Love Calculator!") name1 = input("What is your name? \n") name2 = input("What is their name? \n") # 🚨 Don't change the code above 👆 lower_name1 = name1.lower() lower_name2 = name2.lower() names_together = lower_name1 + lower_name2 #print(names_together) True_T = names_together.count("t") True_R = names_together.count("r") True_U = names_together.count("U") True_E = names_together.count("e") total_in_true = True_T + True_R + True_U + True_E Love_L = names_together.count("l") Love_O = names_together.count("o") Love_v = names_together.count("v") Love_e = names_together.count("e") total_in_love = Love_L + Love_O + Love_v + Love_e final_result = int(f"{total_in_true}{total_in_love}") print(final_result) #Write your code below this line 👇
# This file contains the different states of the api class Config(object): DEBUG = False SQLALCHEMY_DATABASE_URI = 'sqlite:///database.db' SQLALCHEMY_TRACK_MODIFICATIONS = False class Production(Config): DEBUG = False class DevelopmentConfig(Config): DEBUG = True
class Node(object): def __init__(self, item): self.data = item self.left = None self.right = None def BTToDLLUtil(root): if root is None: return root if root.left: left = BTToDLLUtil(root.left) while left.right: left = left.right left.right = root root.left = left if root.right: right = BTToDLLUtil(root.right) while right.left: right = right.left right.left = root root.right = right return root def BTToDLL(root): if root is None: return root root = BTToDLLUtil(root) while root.left: root = root.left return root def method1(head): if head is None: return while head: print(head.data, end=" ") head = head.right if __name__ == "__main__": """ from timeit import timeit root = Node(10) root.left = Node(12) root.right = Node(15) root.left.left = Node(25) root.left.right = Node(30) root.right.left = Node(36) head = BTToDLL(root) print(timeit(lambda: method1(head), number=10000)) # 0.05323586200393038 """
#!/usr/bin/env python print('nihao')
def friend_find(line): check=[i for i,j in enumerate(line) if j=="red"] total=0 for i in check: if i>=2 and line[i-1]=="blue" and line[i-2]=="blue": total+=1 elif (i>=1 and i<=len(line)-2) and line[i-1]=="blue" and line[i+1]=="blue": total+=1 elif (i<=len(line)-3) and line[i+1]=="blue" and line[i+2]=="blue": total+=1 return total
# _*_ coding: utf-8 _*_ # # Package: bookstore.src.core.validator __all__ = ["validators"]
sanitizedLines = [] with open("diff.txt") as f: for line in f: sanitizedLines.append("https://interclip.app/" + line.strip()) print(str(sanitizedLines))
# # chmod this file securely and be sure to remove the default users # users = { "frodo" : "1ring", "yossarian" : "catch22", "ayla" : "jondalar", }
def calcMul(items): mulTotal = 1 for i in items: mulTotal *= i return mulTotal print("The multiple is: ",calcMul([10,20,30]))
def validate_contract_create(request, **kwargs): if request.validated['auction'].status not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', 'Can\'t add contract in current ({}) auction status'.format(request.validated['auction'].status)) request.errors.status = 403 return def validate_contract_update(request, **kwargs): if request.validated['auction_status'] not in ['active.qualification', 'active.awarded']: request.errors.add('body', 'data', 'Can\'t update contract in current ({}) auction status'.format( request.validated['auction_status'])) request.errors.status = 403 return if any([i.status != 'active' for i in request.validated['auction'].lots if i.id in [a.lotID for a in request.validated['auction'].awards if a.id == request.context.awardID]]): request.errors.add('body', 'data', 'Can update contract only in active lot status') request.errors.status = 403 return
# -*- coding: utf-8 -*- """ enquanto não maça passo pega """ """ while not maça: passo pega while not maça: if bloco: passo if buraco: pula if moeda: pega pega """ ''' for c in range(1,10): print(c) print('fIMM')''' c = 1 while c < 10: print(c) c = c + 1 print('fIMM!') for c in range(1, 5): n = int(input('Digite um valor: ')) print('fiMM') while n != 0: n = int(input('Digite um valor: ')) print('fIMMMM!!!') r = 'S' while r == 'S': n = int(input('Digite um valor: ')) r = str(input('Quer continuar? [S/N] ')).upper() print('!!!fim') par = 0 impar = 0 n = 1 while n != 0: n = int(input('--Digite um valor: ')) if n % 2 == 0: par += 1 else: impar += 1 print('Voce digitou {} pares e {} impares'.format(par, impar))
# flask-login 用クラス class FlaskUser(object): def __init__(self, user_hash, username=None): self.user_hash = user_hash if username is not None: self.username = username def is_authenticated(self): return True def is_active(self): return True def is_anonymous(self): return False def get_id(self): return self.user_hash def get_username(self): if self.username is None: return "名無し" else: return self.username
"""Constants for Skoda Connect library.""" BASE_SESSION = 'https://msg.volkswagen.de' BASE_AUTH = 'https://identity.vwgroup.io' BRAND = 'VW' COUNTRY = 'DE' # Data used in communication CLIENT = { 'Legacy': { 'CLIENT_ID': '9496332b-ea03-4091-a224-8c746b885068%40apps_vw-dilab_com', # client id for VWG API, legacy Skoda Connect/MySkoda 'SCOPE': 'openid mbb profile cars address email birthdate nickname phone', # 'SCOPE': 'openid mbb profile cars address email birthdate badge phone driversLicense dealers profession vin', 'TOKEN_TYPES': 'code id_token token' }, 'New': { 'CLIENT_ID': 'f9a2359a-b776-46d9-bd0c-db1904343117@apps_vw-dilab_com', # Provides access to new API? tokentype=IDK_TECHNICAL.. 'SCOPE': 'openid mbb profile', 'TOKEN_TYPES': 'code id_token' }, 'Unknown': { 'CLIENT_ID': '72f9d29d-aa2b-40c1-bebe-4c7683681d4c@apps_vw-dilab_com', # gives tokentype=IDK_SMARTLINK ? 'SCOPE': 'openid dealers profile email cars address', 'TOKEN_TYPES': 'code id_token' }, } XCLIENT_ID = '85fa2187-5b5c-4c35-adba-1471d0c4ea60' XAPPVERSION = '5.3.2' XAPPNAME = 'We Connect' USER_AGENT = 'okhttp/3.14.7' APP_URI = 'carnet://identity-kit/login' # Used when fetching data HEADERS_SESSION = { 'Connection': 'keep-alive', 'Content-Type': 'application/json', 'Accept-charset': 'UTF-8', 'Accept': 'application/json', 'X-Client-Id': XCLIENT_ID, 'X-App-Version': XAPPVERSION, 'X-App-Name': XAPPNAME, 'User-Agent': USER_AGENT, 'tokentype': 'IDK_TECHNICAL' } # Used for authentication HEADERS_AUTH = { 'Connection': 'keep-alive', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9', 'Accept-Encoding': 'gzip, deflate', 'Content-Type': 'application/x-www-form-urlencoded', 'x-requested-with': XAPPNAME, 'User-Agent': USER_AGENT, 'X-App-Name': XAPPNAME }
class User: def __init__(self, userName, firstName, lastName, passportNumber, address1, address2, zipCode): self.userName = userName self.firstName = firstName self.lastName = lastName self.passportNumber = passportNumber self.address1 = address1 self.address2 = address2 self.zipCode = zipCode def toString(self): return "[userName: " + self.userName + ", firstName: " + self.firstName + ", lastName: " + self.lastName + ", passportNumber: " + self.passportNumber +\ ", address1: " + self.address1 + ", address2: " + self.address2 + ", zipCode: " + self.zipCode + "]"
# pylint: skip-file # pylint: disable=too-many-instance-attributes class VMInstance(GCPResource): '''Object to represent a gcp instance''' resource_type = "compute.v1.instance" # pylint: disable=too-many-arguments def __init__(self, rname, project, zone, machine_type, metadata, tags, disks, network_interfaces, service_accounts=None, ): '''constructor for gcp resource''' super(VMInstance, self).__init__(rname, VMInstance.resource_type, project, zone) self._machine_type = machine_type self._service_accounts = service_accounts self._machine_type_url = None self._tags = tags self._metadata = [] if metadata and isinstance(metadata, dict): self._metadata = {'items': [{'key': key, 'value': value} for key, value in metadata.items()]} elif metadata and isinstance(metadata, list): self._metadata = [{'key': label['key'], 'value': label['value']} for label in metadata] self._disks = disks self._network_interfaces = network_interfaces self._properties = None @property def service_accounts(self): '''property for resource service accounts ''' return self._service_accounts @property def network_interfaces(self): '''property for resource machine network_interfaces ''' return self._network_interfaces @property def machine_type(self): '''property for resource machine type ''' return self._machine_type @property def machine_type_url(self): '''property for resource machine type url''' if self._machine_type_url == None: self._machine_type_url = Utils.zonal_compute_url(self.project, self.zone, 'machineTypes', self.machine_type) return self._machine_type_url @property def tags(self): '''property for resource tags ''' return self._tags @property def metadata(self): '''property for resource metadata''' return self._metadata @property def disks(self): '''property for resource disks''' return self._disks @property def properties(self): '''property for holding the properties''' if self._properties == None: self._properties = {'zone': self.zone, 'machineType': self.machine_type_url, 'metadata': self.metadata, 'tags': self.tags, 'disks': self.disks, 'networkInterfaces': self.network_interfaces, } if self.service_accounts: self._properties['serviceAccounts'] = self.service_accounts return self._properties def to_resource(self): '''return the resource representation''' return {'name': self.name, 'type': VMInstance.resource_type, 'properties': self.properties, }
#create veriable........ cr_pass=0##insert veriables defer=0##insert veriables fail=0##insert veriables choice=0#staff choice. count1=0#$$$counting "Progress" count2=0#$$$counting "Trailing" count3=0#$$$counting "Excluded" count4=0#$$$counting "Retriever" total=0#@@@@all counting values total #start the programme.......... print("--------------------------------------------------------") print("Staff Version with Histogram\n") while True: #insert from user cr_pass=int(input("Enter your total PASS credits:")) defer=int(input("Enter your total DEFER credits:")) fail=int(input("Enter your total FAIL credits:")) #programme.......... if cr_pass==120: print("Progress\n") count1=count1+1 elif cr_pass==100: print("Progress (module trailer)\n") count2=count2+1 elif fail>=80: print("Exclude\n") count3=count3+1 else: print("Do not progress – module retriever\n") count4=count4+1 print("Would you like to enter another set of data?") choice=str(input("Enter 'y' for yes or 'q' to quit and view results:")) if choice=="Y" or choice=="y": print("\n") continue if choice=="Q" or choice=="q": print("--------------------------------------------------------") print("Horizontal Histogram") print("Progress",count1,":",("*"*count1)) print("Trailer",count2,":",("*"*count2)) print("Retriever",count4,":",("*"*count4)) print("Excluded",count3,":",("*"*count3)) print("\n") total=count1+count2+count3+count4 print(total,"outcomes in total.") print("--------------------------------------------------------") break
''' Item : Python 100Dsays Time : 20200521 變量 ''' # 設變數 a, b 進行計算 a = 123 b = 456 c = "hello world" d = 1 + 5j e = True #-計算 -------------------------------------------- print(a + b) # 579 print(a - b) # -333 print(a * b) # 560888 print(a / b) # 0.269... # 檢索變量的類型的函數 type ----------------------- print(type(a+b)) # int print(type(a-b)) # int print(type(a*b)) # int print(type(a/b)) # float print(type(c)) # str print(type(d)) # complex print(type(e)) # bool # 變數類型轉換函數-------------------------------- print(" int 轉成 str ") print(type(str(a+b))) # 將指定的對象轉換成字符串形式,可以指定編碼。 print(type(chr(a+b))) # 將整數轉換成該編碼對應的字符串(一個字符) print(" 字符串轉換成對應的整數") # print(type(ord (c))) 無法轉換 # print(type(float(c))) 無法轉換 #-輸入輸出函數--------------------------------------------- # input() # 可輸入字符串 # int() # 轉成整數 # print() # 輸出 # ----------------------------------------------------- # 輸入值轉成整數 x = int(input('a = ')) y = int(input('b = ')) # 佔位符, %d 是整數的佔位符,%f 是小數的佔位符,%% 表示百分號 print('%d + %d = %d' % (a, b, a+b)) print('%d - %d = %d' % (a, b, a-b)) # 運算符 ''' [] [:] : 下標? ,切片 ** : 指數 ~ + - : 取反位 >> 右移 ? , <<左移 & 按位與? ^| 按位異或 按位或 !== 不等於 is, is not 身份運算符 in, not in 成員運算符 not or and 邏輯運算符 ''' # -練習1-華氏溫度轉為攝氏溫度---------------------------------------------- # %1f 浮點佔位符 # {f : 1.f}, {c:1.f}, :1.f 為浮點數 f = float(input(" 請輸入華氏溫度 ")) c = (f-32) / 1.8 print( '%.1f 華氏度 = %1f 攝氏度' % (f,c)) #-練習2-圓半徑計算周長和面積, .2f 2位數浮點值 radius = float(input("請輸入圓的半徑")) perimeter = 2 * 3.1416 * radius area = 3.1416 * radius * radius print('周長: %.2f' % perimeter) print('面積: %.2f' % area) #-練習3 判斷是否閏年--------------------------------------- year = int(input(" 請輸入年份 ")) is_leap = year % 4 == 0 and year % 100 != 0 or \ year % 400 == 0 print(is_leap)
# # Variables: # - Surname: String # - SurnameLength, NextCodeNumber, CustomerID, i: Integer # - NextChar: Char # Surname = input("Enter your surname: ") SurnameLength = len(Surname) CustomerID = 0 for i in range(0, SurnameLength): NextChar = Surname[i] NextCodeNumber = ord(NextChar) CustomerID = CustomerID + NextCodeNumber print("Customer ID is ", CustomerID)
class EmptyType(object): """A sentinel value when nothing is returned from the database""" def __new__(cls): return Empty def __reduce__(self): return EmptyType, () def __bool__(self): return False def __repr__(self): return 'Empty' Empty = object.__new__(EmptyType)
class classproperty(object): '''Implements both @property and @classmethod behavior.''' def __init__(self, getter): self.getter = getter def __get__(self, instance, owner): return self.getter(instance) if instance else self.getter(owner)
''' Exercicio 004 Faça um Programa que peça as 4 notas bimestrais e mostre a média. ''' n1 = float(input('Digite a nota do primeiro bimestre: ')) n2 = float(input('Digite a nota do segundo bimestre: ')) n3 = float(input('Digite a nota do terceiro bimestre: ')) n4 = float(input('Digite a nota do quarto bimestre: ')) media = (n1 + n2 + n3 + n4 ) / 4 print(f'A média das notas é igual a {media:.2f}')
class Game(object): def initialize(self, ): pass def start(self, ): pass def end(self, ): pass def play(self): self.initialize() self.start() # 开始游戏 self.end() # 结束游戏 class Cricket(Game): def initialize(self, ): print("Cricket Game Finished!") def start(self, ): print("Cricket Game Initialized! Start playing.") def end(self, ): print("Cricket Game Started. Enjoy the game!") class Football(Game): def initialize(self, ): print("Football Game Finished!") def start(self, ): print("Football Game Initialized! Start playing.") def end(self, ): print("Football Game Started. Enjoy the game!") if __name__ == "__main__": game = Cricket() game.play() print() game = Football() game.play()
def is_empty(text): if text in [None,'']: return True return False
''' 013 Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salária, com 15% de aumento''' sal = float(input('Digite o seu salário: R$ ')) print(f'O seu salário com aumento de 15% é {sal + (sal * 15)/100:.2f}')
mysql_config = { 'user': 'USER', 'password': 'PASSWORD', 'host': 'HOST', 'port': 3306, 'charset': 'utf8mb4', 'database': 'DATABASE', 'raise_on_warnings': False, 'use_pure': False, }
class Preprocess_Data: """this class converts the integer date time values to the python datetime string format""" def __init__(self, data_dict): self.data_dict = data_dict def preprocess(self): from_year = self.data_dict["fromYr"] from_month = self.data_dict["fromMth"] to_year = self.data_dict["toYr"] to_month = self.data_dict["toMth"] from_date = str(from_year) + "-" + str(from_month) to_date = str(to_year) + "-" + str(to_month) return from_date, to_date
class Solution: def XXX(self, root: TreeNode) -> int: if not root: return 0 res = 1 q = [root] while q: n = len(q) for i in range(n): node = q.pop(0) if node.left and node.right: # 有两个子节点 q.append(node.left) q.append(node.right) elif node.left: # 有左子节点 q.append(node.left) elif node.right: # 有右子节点 q.append(node.right) else: return res res += 1
#CORES r = str('\33[31m') #red g = str('\33[32m') #green y = str('\33[33m') #yellow b = str('\33[34m') #blue m = str('\33[35m') #magenta c = str('\33[36m') #cian x = str('\33[m') #fechamento #PROGRAMA print('=~'*12) print('Minha casa minha vida') print('=~'*12) casa = float(input('Qual o valor da casa que você pretende comprar? R$')) sal = float(input('Qual é o seu salário? R$')) anos = int(input('Pretende comprar em quantos anos? ')) prestações = anos * 12 parcela = casa/prestações print('O valor total da casa é {}R${:.2f}{}, dividido em {}{}{} vezes de {}R${:.2f}{}.' .format(g, casa, x, c, prestações, x, g, parcela, x)) if parcela >= sal*0.7: print('Empréstimo {}não liberado{}.'.format(r,x)) else: print('Parabéns, empréstimo {}liberado{}!'.format(b,x))
user_name = "huyankai" user_age = 24 print(user_name, "今年", str(user_age), sep=">>>>",end="") print(user_name, "今年", str(user_age), sep=">>>>")
#!/usr/bin/env python3 """Global color definitions. """ BLUE_BACKGROUND: int = 20 GREEN_BACKGROUND: int = 30 RED_BACKGROUND: int = 5 WHITE: int = 0 YELLOW_BACKGROUND: int = 186
# TIme problem # 00:00:00 - n:59:59 # 해당 문제는 완전 탐색 유형(Brute Forcing)으로도 풀 수 있다. # 완전 탐색 알고리즘은 가능한 경우의 수를 모두 검사해보는 탐색 방법이다. # 시간 복잡도로 인해서 일반적으로 알고리즘 문제를 풀 때 확인(탐색)해야 하는 전체 데이터의 개수가 100만개 이하 일 때 완전 탐색을 사용하면 적절하다. # 내가 푼 방법은 완전 탐색보다는 시간 복잡도를 O(N)으로 감소하여 처리하는 알고리즘이다. 이는 일정한 데이터 제한 안에서 휴리스틱을 적용했다. # Heuristic # 01. 시간에 3이 포함되면 분과 초의 경우의 수 모두가 참이다 # 02. 분에 3이 포함되면 모든 초의 경우의 수가 참이다 # 03. 데이터는 0~59, 0~23의 범위를 가진다. n = int(input()) solution = 0 hour_three_case = 0 minute_three_case = 0 second_three_case = 0 for number in range(0, n + 1): if "3" in str(number): hour_three_case += 1 for number in range(0, 60): if "3" in str(number): minute_three_case += 1 for number in range(0, 60): if "3" in str(number): second_three_case += 1 print(hour_three_case, minute_three_case, second_three_case) solution += hour_three_case * 60 * 60 solution += (n - hour_three_case + 1) * (minute_three_case * 60) solution += (n - hour_three_case + 1) * \ (60-(minute_three_case)) * second_three_case print(solution)
movie = {"title": "padmavati", "director": "Bhansali","year": "2018", "rating": "4.5"} print(movie) print(movie['year']) movie['year'] = 2019 #update data. print(movie['year']) print('-' * 20) for x in movie: print(x) #this print key. print(movie[x]) #this print value at key. print('-' * 20) movie = {} movie['title'] = 'Manikarnika' movie['Director'] = 'kangana Ranut' movie['year'] = '2015' print(movie) movie['actor'] = ['kangana Ranut', 'Khilge','Pelge'] #defining a list within dictionary. movie['other_detail'] = {'language': 'Hindi', 'runtime': '180min'} #defining a dictinary witnin dictionay. print(movie) print('\n...........new example........') orders = {'apple': 2, 'banana': 5 , 'orange': 10} print(orders.values()) print(list(orders)) print(list(orders.values())) for tuple in list(orders.items()): #iterate in dictionary , converting in tuple by using items() method. print(tuple)
espanhol = {"um": "uno", "dois": "dos"} ingles = {"um": "one", "dois": "two"} idioma = input("Escolha o idioma: ") if (idioma=="espanhol"): print(idioma+["um"]) elif (idioma=="ingles"): print(ingles["um"]) else: print("inválido")
def comb(m, s): if m == 1: return [[x] for x in s] if m == len(s): return [s] return [s[:1] + a for a in comb(m-1, s[1:])] + comb(m, s[1:])
n, x = map(int, input().split()) mark_sheet = [] for _ in range(x): mark_sheet.append( map(float, input().split()) ) for i in zip(*mark_sheet): print( sum(i)/len(i) )
__name__ = "lbry" __version__ = "0.42.1" version = tuple(__version__.split('.'))
def main(): # input N = int(input()) As = [*map(int, input().split())] # compute ## 1-9の各数字がそれぞれ何回登場するかを数える counts = [0] * 9 for A in As: counts[A-1] += 1 ## 各数字の登場回数の最大値を求める target = counts[0] ans = 0 for i, count in enumerate(counts): if target < count: ans = i + 1 target = count # output print(ans) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- class Base(RuntimeError): """An extendible class for responding to exceptions caused within your application. Usage: .. code-block: python class MyRestError(errors.Base): pass # somewhere in your code... raise MyRestError(code=01, message='You broke it', developer_message='Invalid index supplied') # {'code': '01406', message='You broke it', 'developer_message': 'Invalid index supplied'} """ class Meta(object): attributes = ( 'code', 'status', 'message', 'developer_message') def __init__( self, code, message='Unknown Error', status_code=406, developer_message=None): """Initialize the error. Args: code (int/string): A unique exception code for the error, gets combined with the status_code status_code (int): The HTTP status code associated with the response (see https://httpstatuses.com/) message (string): A human friendly exception message developer_message (string): A more complex exception message aimed at deveopers """ super(Base, self).__init__(message) self.status_code = status_code self.code = '{}{}'.format(status_code, code) self.message = message self.developer_message = '{}: {}'.format( self.__class__.__name__, developer_message or message)
# initialize/define the blockchain list blockchain = [] open_txs = [] def get_last_blockchain_val(): """ Returns the last element of the blockchain list. """ if len(blockchain) < 1: return None return blockchain[-1] def add_tx(tx_amt, last_tx=[1]): """ Adds the last transaction amount and current transaction amount to the blockchain list. Parameters: <tx_amt> current transaction amount. <last_tx> last transaction (default: [1]). """ if last_tx is None: last_tx = [1] return blockchain.append([last_tx, tx_amt]) def get_tx_amt(): """ Gets and returns user input (transaction amount) from the user as a float. """ return float(input("Please enter transaction amount: ")) def get_user_choice(): """ Gets and returns user input (user choice) from the user. """ return input("Please enter choice: ").upper() def mine_block(): pass def print_out_blockchain(blockchain): """ Prints out the blockchain. """ print("The entire blockchain:") print(blockchain) print("Printing out the blocks...") i = 0 for block in blockchain: print(f" Block[{i}]: {block}") i += 1 else: print("-" * 20) def validate_blockchain(blockchain): """ Validates the blockchain. """ is_valid = True print("Validating the blockchain...") for i in range(len(blockchain)): if i == 0: continue else: print( f" Comparing block[{i}] ({blockchain[i]})", f"first element ({blockchain[i][0]})", ) print(f" and previous block[{i-1}]", f"({blockchain[i-1]})... ", end="") if blockchain[i][0] == blockchain[i - 1]: print("match") is_valid = True else: print("mis-match") is_valid = False break # # --- original attempt --- # if len(blockchain) > 1: # for i in range(1, len(blockchain)): # print( # f" Comparing block[{i - 1}] ({blockchain[i - 1]})", # f"and block[{i}][0] ({blockchain[i]})... ", # end="", # ) # if blockchain[i - 1] == blockchain[i][0]: # print("match") # else: # print("mis-match") # # --- original attempt --- # # --- second attempt --- # i = 0 # for block in blockchain: # if i == 0: # i += 1 # continue # else: # print(f" Comparing block[{i}] ({block})", f"first element ({block[0]})") # print( # f" and previous block[{i-1}] ({blockchain[(i-1)]})... ", end="", # ) # if block[0] == blockchain[(i - 1)]: # print("match") # is_valid = True # else: # print("mis-match") # is_valid = False # break # i += 1 # # --- second attempt --- return is_valid more_input = True while more_input: print("Please choose") print(" a: Add a transaction value") print(" p: Print the blockchain blocks") print(" m: Manipulate the blockchain") print(" v: Validate the blockchain") print(" q: Quit") usr_choice = get_user_choice() if usr_choice == "A": tx_amt = get_tx_amt() add_tx(tx_amt, get_last_blockchain_val()) elif usr_choice == "P": print_out_blockchain(blockchain) elif usr_choice == "M": if len(blockchain) > 0: blockchain[0] = [2] elif usr_choice == "V": validate_blockchain(blockchain) elif usr_choice == "Q": more_input = False else: print(f"Not a valid choice: '{usr_choice}'") # add_tx(last_tx=get_last_blockchain_val(), tx_amt=tx_amt) if not validate_blockchain(blockchain): print(f"Not a valid blockchain! Exiting...") break else: print("No more input") print("Done!")
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. py:currentmodule:: leepstools.file.angle .. moduleauthor:: Hendrix Demers <[email protected]> Read angle distribution result from LEEPS simulation. """ ############################################################################### # Copyright 2017 Hendrix Demers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ############################################################################### # Standard library modules. # Third party modules. # Local modules. # Project modules. # Globals and constants variables. class Angle(): def __init__(self): self.theta_deg = [] self.probability_1_sr = [] self.stu_1_sr = [] def read(self, file_path): lines = [] with open(file_path) as input_file: lines = input_file.readlines() for line in lines: line = line .strip() if not line.startswith('#'): items = line.split() try: theta_deg = float(items[0]) probability_1_sr = float(items[1]) stu_1_sr = float(items[2]) self.theta_deg.append(theta_deg) self.probability_1_sr.append(probability_1_sr) self.stu_1_sr.append(stu_1_sr) except IndexError: pass
# coding=utf-8 class AutumnInvokeException(Exception): pass class InvocationTargetException(Exception): pass if __name__ == '__main__': pass
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: ''' T: O(n log n + n^3) S: O(1) ''' n = len(nums) if n < 4: return [] nums.sort() results = set() for x in range(n): for y in range(x+1, n): i, j = y + 1, n-1 while i < j: summ = nums[x] + nums[y] + nums[i] + nums[j] if summ == target: results.add((nums[x],nums[y], nums[i], nums[j])) i += 1 elif summ < target: i += 1 else: j -= 1 return results