content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def read_input(): return [l.strip().split(',') for l in open('input_day03.txt')] def trace(d, start, end, ports, steps): while start != end: if start not in ports: ports[start] = steps steps += 1 start += d def parse_direction(instruction): deltas = { 'L': -1 + 0j, 'R':...
def read_input(): return [l.strip().split(',') for l in open('input_day03.txt')] def trace(d, start, end, ports, steps): while start != end: if start not in ports: ports[start] = steps steps += 1 start += d def parse_direction(instruction): deltas = {'L': -1 + 0j, 'R': ...
veta = input('Zadaj vetu:') veta_upravena = "" for i in veta: if i.isalpha() or i == " ": veta_upravena += i print(veta_upravena)
veta = input('Zadaj vetu:') veta_upravena = '' for i in veta: if i.isalpha() or i == ' ': veta_upravena += i print(veta_upravena)
def russian(a,b): x = a; y = b z = 0 while x > 0: if (x % 2 == 1): z = z + y y = y << 1 x = x >> 1 return z print(russian(10,6)) def rec_russian(a,b): if a==0: return 0 if a%2 == 0: return 2*rec_russian(a/2,b) return b + ...
def russian(a, b): x = a y = b z = 0 while x > 0: if x % 2 == 1: z = z + y y = y << 1 x = x >> 1 return z print(russian(10, 6)) def rec_russian(a, b): if a == 0: return 0 if a % 2 == 0: return 2 * rec_russian(a / 2, b) return b + 2 * r...
def if_weird(value): if value % 2 != 0: # Odd number return "Weird" else: # Even number if value in range(2, 5+1): return "Not Weird" elif value in range(6, 20+1): return "Weird" elif value > 20: return "Not Weird" if __name__ == "__main__": # Read an integer number from stdin (standard input...
def if_weird(value): if value % 2 != 0: return 'Weird' elif value in range(2, 5 + 1): return 'Not Weird' elif value in range(6, 20 + 1): return 'Weird' elif value > 20: return 'Not Weird' if __name__ == '__main__': n = int(input().strip()) print(if_weird(N))
with tf.name_scope('forward'): W1 = tf.get_variable("W1", [3,3,1,5], initializer=tf.contrib.layers.xavier_initializer(seed=0)) Z1 = tf.nn.conv2d(x, W1, [1,1,1,1], 'SAME') # RELU A1 = tf.nn.relu(Z1) # MAXPOOL: window 5x5, sride 5, padding 'SAME' P1 = tf.nn.max_pool(A1, [1,5,5,1], [1,5,5,1], 'SAME...
with tf.name_scope('forward'): w1 = tf.get_variable('W1', [3, 3, 1, 5], initializer=tf.contrib.layers.xavier_initializer(seed=0)) z1 = tf.nn.conv2d(x, W1, [1, 1, 1, 1], 'SAME') a1 = tf.nn.relu(Z1) p1 = tf.nn.max_pool(A1, [1, 5, 5, 1], [1, 5, 5, 1], 'SAME') w2 = tf.get_variable('W2', [3, 3, 5, 10], i...
classmates = ['1', '2', '3'] length = len(classmates) item0 = classmates[0] classmates.append('4') classmates.insert(length - 2, '12') classmates.pop(3) classmates[1] = '121' itemLast = classmates[-1] print (length, item0, itemLast, classmates)
classmates = ['1', '2', '3'] length = len(classmates) item0 = classmates[0] classmates.append('4') classmates.insert(length - 2, '12') classmates.pop(3) classmates[1] = '121' item_last = classmates[-1] print(length, item0, itemLast, classmates)
print("Python as Calculator") print(2*3) #Multiplication print(5/4) #float division print(5//4) # integer division print(12/4) #float division print(12//4) # integer division print(2**5) #exponent print(109%5) #Modulo print(83+23-4) # Addition and subtraction print(2+5/10-6*(23**7)/35)
print('Python as Calculator') print(2 * 3) print(5 / 4) print(5 // 4) print(12 / 4) print(12 // 4) print(2 ** 5) print(109 % 5) print(83 + 23 - 4) print(2 + 5 / 10 - 6 * 23 ** 7 / 35)
db_column = ['ID_Source_IP', 'ID_Dest_IP', 'ID_Source_PORT', 'ID_Dest_PORT', 'Protocol','ID_Source_MAC', 'ID_Dest_MAC'] # El nombre de las tags, segun el orden de la # columnas en db_column, las extraigo del fichero # de configuracion a traves del registro info_config_file label...
db_column = ['ID_Source_IP', 'ID_Dest_IP', 'ID_Source_PORT', 'ID_Dest_PORT', 'Protocol', 'ID_Source_MAC', 'ID_Dest_MAC'] labels = [self.info_config_file['Source_Ip'], self.info_config_file['Dest_Ip'], self.info_config_file['Source_Port'], self.info_config_file['Dest_Port'], self.info_config_file['Protocol']] for it in ...
# # PySNMP MIB module CAPWAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CAPWAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:46:56 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:...
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint) ...
ordered_params = [ 'k_deg', 'k_synt' ] n_vars = 1 def model(y, t, yout, p): #---------------------------------------------------------# #Parameters# #---------------------------------------------------------# k_deg = p[0] k_synt = p[1] #-----------------------------------------------------...
ordered_params = ['k_deg', 'k_synt'] n_vars = 1 def model(y, t, yout, p): k_deg = p[0] k_synt = p[1] _y = y[0] yout[0] = -_y * k_deg + k_synt
#!/usr/bin/env python #/*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=* # * Copyright (c) 1995-2002 UCAR # * University Corporation for Atmospheric Research(UCAR) # * National Center for Atmospheric Research(NCAR) # * Research Applications Program(RAP) # * P.O.Box 3000, Boulder, Colorado, 80307-3000, USA # * ...
sig_list = ['HUP', 'INT', 'QUIT', 'ILL', 'TRAP', 'ABRT', 'IOT', 'BUS', 'FPE', 'KILL', 'USR1', 'SEGV', 'USR2', 'PIPE', 'ALRM', 'TERM', 'STKFLT', 'CLD', 'CHLD', 'CONT', 'STOP', 'TSTP', 'TTIN', 'TTOU', 'SIGURG', 'XCPU', 'XFSZ', 'VTALRM', 'PROF', 'WINCH', 'POLL', 'IO', 'PWR', 'UNUSED']
class Number: def __init__(self, val): self.value = val def __sub__(self, other): return self.value - other class NewNumber(Number): def __repr__(self): return f'{self.value}' if __name__ == "__main__": number = Number(10) print(number) newNumber = NewNumber(15) p...
class Number: def __init__(self, val): self.value = val def __sub__(self, other): return self.value - other class Newnumber(Number): def __repr__(self): return f'{self.value}' if __name__ == '__main__': number = number(10) print(number) new_number = new_number(15) ...
def save_result_rmse(model_name, rmse, rsqu): filepath = 'Results/' filepath += model_name.replace(' ','') filepath += '.txt' with open(filepath, 'w') as f: f.write('### ') f.write(model_name) f.write(' ###\n') f.write(f'R-squared:{rsqu:,.4f}\n') f.write(f'RMSE:{rmse:,.2f}') f.close()
def save_result_rmse(model_name, rmse, rsqu): filepath = 'Results/' filepath += model_name.replace(' ', '') filepath += '.txt' with open(filepath, 'w') as f: f.write('### ') f.write(model_name) f.write(' ###\n') f.write(f'R-squared:{rsqu:,.4f}\n') f.write(f'RMSE:{...
i = int(input()) for _ in range(i): N = int(input()) if N % 10 == 0 and N % 8 == 0: print('ikisugi') elif N % 10 == 0: print('sugi') elif N % 8 == 0: print('iki') elif N % 3 == 0: print(N // 3)
i = int(input()) for _ in range(i): n = int(input()) if N % 10 == 0 and N % 8 == 0: print('ikisugi') elif N % 10 == 0: print('sugi') elif N % 8 == 0: print('iki') elif N % 3 == 0: print(N // 3)
def start() : shadows = True; driverType = irr.driverChoiceConsole(); if driverType == irr.EDT_COUNT : return 1; device = irr.createDevice(driverType, irr.dimension2d_u32(640, 480), 16, False, shadows); if device == None : return 1; driver = device.getVideoDriver(); smgr = device.getSceneMan...
def start(): shadows = True driver_type = irr.driverChoiceConsole() if driverType == irr.EDT_COUNT: return 1 device = irr.createDevice(driverType, irr.dimension2d_u32(640, 480), 16, False, shadows) if device == None: return 1 driver = device.getVideoDriver() smgr = device.get...
# # PySNMP MIB module PRIVAT-MultiLAN-Switch-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PRIVAT-MultiLAN-Switch-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:33:15 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version ...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, single_value_constraint, value_size_constraint, value_range_constraint) ...
#Q4: What is the time complexity of for i in range(3): for j in range(2): print(i , j) #La complejidad es O(n^2)
for i in range(3): for j in range(2): print(i, j)
PRESTAMOS_JSON_0 = { "loan": 1000, "num_of_years": 1, "rate": 9, "freq": 12, "extra_pmt": 150, "extra_pmt_start": 6, "extra_pmt_f": 1, "pmt_when": 0, } PRESTAMOS_JSON_1 = { "loan": 1000, "num_of_years": 1, "rate": 9, "freq": 12, "extra_pmt": 150, ...
prestamos_json_0 = {'loan': 1000, 'num_of_years': 1, 'rate': 9, 'freq': 12, 'extra_pmt': 150, 'extra_pmt_start': 6, 'extra_pmt_f': 1, 'pmt_when': 0} prestamos_json_1 = {'loan': 1000, 'num_of_years': 1, 'rate': 9, 'freq': 12, 'extra_pmt': 150, 'extra_pmt_start': 6, 'extra_pmt_f': 1, 'pmt_when': 1} prestamos_result_0 = {...
class Config(object): def __init__(self): # model params self.model = "AR_reg" self.nsteps = 7 # equivalent to x_len self.hidden_size = 8 self.num_heads = 8 self.gru_size = 8 self.attention_size = 8 self.l2_lambda = 1e-3 self.ar_lambda = ...
class Config(object): def __init__(self): self.model = 'AR_reg' self.nsteps = 7 self.hidden_size = 8 self.num_heads = 8 self.gru_size = 8 self.attention_size = 8 self.l2_lambda = 0.001 self.ar_lambda = 0.1 self.ar_g = 0.0 self.data_pat...
N, M = map(int, input().split()) ks = [list(map(int, input().split())) for i in range(M)] p = list(map(int, input().split())) k = [] s = [] for i in range(M): k.append(ks[i][0]) s.append(ks[i][1:]) A = [i for i in range(1, 11)] count = 0 for i in range(1 << N): B = [] flag = True for j in range(10):...
(n, m) = map(int, input().split()) ks = [list(map(int, input().split())) for i in range(M)] p = list(map(int, input().split())) k = [] s = [] for i in range(M): k.append(ks[i][0]) s.append(ks[i][1:]) a = [i for i in range(1, 11)] count = 0 for i in range(1 << N): b = [] flag = True for j in range(10...
#import os #import app class Config: ''' General configuration parent class ''' UPLOADED_PHOTOS_DEST ='app/static/photos' SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://k:qwerty1234@localhost/watchlist' SECRET_KEY ='qwerty1234' # email configurations #app.config['MAIL_SERVER'] = 'smtp.gma...
class Config: """ General configuration parent class """ uploaded_photos_dest = 'app/static/photos' sqlalchemy_database_uri = 'postgresql+psycopg2://k:qwerty1234@localhost/watchlist' secret_key = 'qwerty1234' class Prodconfig(Config): """ Production configuration child class Args:...
datasets = [ 'abalone-3_vs_11', # 'kddcup-land_vs_portsweep', # 'dataset_31_credit-g', # 'dresses-sales', # 'dermatology', # 'thyroid-hypothyroid', # 'credit-approval', # 'horse-colic-surgical', # 'heart', # 'hepatitis', # ] dict_categorical_cols = {'abalone-3_vs_11': [0], ...
datasets = ['abalone-3_vs_11', 'kddcup-land_vs_portsweep', 'dataset_31_credit-g', 'dresses-sales', 'dermatology', 'thyroid-hypothyroid', 'credit-approval', 'horse-colic-surgical', 'heart', 'hepatitis'] dict_categorical_cols = {'abalone-3_vs_11': [0], 'kddcup-land_vs_portsweep': [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12...
cache = {} def newName(seed): if "name" not in cache: cache["name"] = open("dict.txt").read().split("\n") pass def newItem(seed): pass def newEquip(seed): pass def newMob(seed): pass
cache = {} def new_name(seed): if 'name' not in cache: cache['name'] = open('dict.txt').read().split('\n') pass def new_item(seed): pass def new_equip(seed): pass def new_mob(seed): pass
__author__ = 'ahnevskiy' class Date: def __init__(self, day, month, year): self.day = str(day) self.month = convert_mount(month=month) self.year = str(year) def convert_mount(month): # converts the month number to a word if month == 1: return "January" elif month == 2...
__author__ = 'ahnevskiy' class Date: def __init__(self, day, month, year): self.day = str(day) self.month = convert_mount(month=month) self.year = str(year) def convert_mount(month): if month == 1: return 'January' elif month == 2: return 'February' elif month ...
class NewsSentenceInfo: TITLE_SENT_IND = -1 def __init__(self, news_id, sent_id): self.__news_id = news_id self.__sent_id = sent_id @property def IsTitle(self): return self.__sent_id == -1 @property def NewsIndex(self): return self.__news_id @property ...
class Newssentenceinfo: title_sent_ind = -1 def __init__(self, news_id, sent_id): self.__news_id = news_id self.__sent_id = sent_id @property def is_title(self): return self.__sent_id == -1 @property def news_index(self): return self.__news_id @property ...
def read_file(fpath, word_idx = 0, tag_idx = -1, filter_words = ['-DOCSTART-']): words = [] tags = [] with fpath.open() as f: for l in f: fields = l.strip().split() if fields: word = fields[word_idx] tag = fields[tag_idx] else: word = '' tag = None if wo...
def read_file(fpath, word_idx=0, tag_idx=-1, filter_words=['-DOCSTART-']): words = [] tags = [] with fpath.open() as f: for l in f: fields = l.strip().split() if fields: word = fields[word_idx] tag = fields[tag_idx] else: ...
''' This scriptwill contain a ros node which will subscribe to the position topic for each leg and calculate as well as execute the most optimised path to be followed - using an RL system. Subscribers /leg/position < quadruped_interfaces.msg.LegPosition > # could be changed as one for each leg Publishers # ad...
""" This scriptwill contain a ros node which will subscribe to the position topic for each leg and calculate as well as execute the most optimised path to be followed - using an RL system. Subscribers /leg/position < quadruped_interfaces.msg.LegPosition > # could be changed as one for each leg Publishers # ad...
w = input("Please enter the string:") if w == w[::-1] : print(f"{w} is a palindrome.") else: print(f"{w} is not a palindrome.")
w = input('Please enter the string:') if w == w[::-1]: print(f'{w} is a palindrome.') else: print(f'{w} is not a palindrome.')
def do_mutation(chrom, prob = 10): # Code mutates chromesome that formed with dictionary # Mutation Probabily adjusted to %10 chrom_keys = [list(chrom.keys())[i] for i in range(len(chrom))] chrom_values = [list(chrom.values())[i] for i in range(len(chrom))] mut_prob = np.random.randin...
def do_mutation(chrom, prob=10): chrom_keys = [list(chrom.keys())[i] for i in range(len(chrom))] chrom_values = [list(chrom.values())[i] for i in range(len(chrom))] mut_prob = np.random.randint(0, 100) mut_prob = 5 if mut_prob < prob: np.random.shuffle(chrom_values) return {chrom_keys[i]...
#!/usr/bin/env python # https://stackoverflow.com/questions/1052589/how-can-i-parse-the-output-of-proc-net-dev-into-keyvalue-pairs-per-interface-u def GetWirelessStats() : dev = open("/proc/net/wireless", "r").readlines() # was using /proc/net/dev header_line = dev[1].replace("tus","status") header_nam...
def get_wireless_stats(): dev = open('/proc/net/wireless', 'r').readlines() header_line = dev[1].replace('tus', 'status') header_names = header_line[header_line.index('|') + 1:].replace('|', ' ').replace('22', ' ').split() raw_values = {} for line in dev[2:]: intf = line[:line.index(':')].st...
# -*- coding: utf-8 -*- #Author:LTW ''' This is a simple templating engine.It is based on str.format. This is rudimentary and is not suitable for too complex use. The HTML escape support is now removed because it's useless. ''' class Templating: def __init__(self,filename): file=open(filename,'r',encoding...
""" This is a simple templating engine.It is based on str.format. This is rudimentary and is not suitable for too complex use. The HTML escape support is now removed because it's useless. """ class Templating: def __init__(self, filename): file = open(filename, 'r', encoding='utf8') self.__templa...
# # PySNMP MIB module HP-STACK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HP-STACK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:24:12 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,...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) ...
class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state #This class shares all its attributes among its various instances class Singelton(Borg): def __init__(self, **kwargs): Borg.__init__(self) self._shared_state.update(kwargs) def __str__(self): return str(self._shared_st...
class Borg: _shared_state = {} def __init__(self): self.__dict__ = self._shared_state class Singelton(Borg): def __init__(self, **kwargs): Borg.__init__(self) self._shared_state.update(kwargs) def __str__(self): return str(self._shared_state) if __name__ == '__main__'...
precision_dummy_dict = { 'US': {'lost_job_1mo': 0.10, 'is_hired_1mo': 0.33, 'is_unemployed': 0.15, 'job_search': 0.38, 'job_offer': 0.17}, 'MX': {'lost_job_1mo': 0.18,...
precision_dummy_dict = {'US': {'lost_job_1mo': 0.1, 'is_hired_1mo': 0.33, 'is_unemployed': 0.15, 'job_search': 0.38, 'job_offer': 0.17}, 'MX': {'lost_job_1mo': 0.18, 'is_hired_1mo': 0.6, 'is_unemployed': 0.15, 'job_search': 0.42, 'job_offer': 0.24}, 'BR': {'lost_job_1mo': 0.45, 'is_hired_1mo': 0.31, 'is_unemployed': 0....
integers = list(map(int, input().split())) while True: line = input() if line == 'end': break tokens = line.split() command = tokens[0] if command == 'swap': i_one = int(tokens[1]) i_two = int(tokens[2]) integers[i_one], integers[i_two] = integers[i_two], integers...
integers = list(map(int, input().split())) while True: line = input() if line == 'end': break tokens = line.split() command = tokens[0] if command == 'swap': i_one = int(tokens[1]) i_two = int(tokens[2]) (integers[i_one], integers[i_two]) = (integers[i_two], integers[...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def smallestFromLeaf(self, root): def dfs(node, path): if not node: return path.append(chr(or...
class Solution: def smallest_from_leaf(self, root): def dfs(node, path): if not node: return path.append(chr(ord('a') + node.val)) if not node.left and (not node.right): res[0] = min(res[0], ''.join(path)[::-1]) else: ...
#Each new term in the Fibonacci sequence #is generated by adding the previous two terms. #By starting with 1 and 2, the first 10 terms will be: #1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... #By considering the terms in the Fibonacci sequence #whose values do not exceed four million, find the sum of the even-valued terms....
sum_even_fib = 0 anteprevious = 1 previous = 2 fib = previous fibs_even = [] while fib < 4000000: if fib % 2 == 0: sum_even_fib += fib fibs_even.append(fib) fib = previous + anteprevious anteprevious = previous previous = fib print('sum even: ', sum_even_fib) print('#' * 40) print('fibs ...
def main(): # input N = input() As = list(map(int,input().split())) # compute # output if __name__ == '__main__': main()
def main(): n = input() as = list(map(int, input().split())) if __name__ == '__main__': main()
# This sample tests the reportImplicitStringConcatenation diagnostic check. def func1(val: str): pass func1("first argument" "second argument") func1( "This is the first argument, which contains " "especially long text that could not fit into " "one single line thus should be spread." ) func1( ...
def func1(val: str): pass func1('first argumentsecond argument') func1('This is the first argument, which contains especially long text that could not fit into one single line thus should be spread.') func1('This is the first argument, which contains especially long text that could not fit into one single line thus...
_SHOWN_ATTR = "_dbnd_shown" def set_shown(ex): setattr(ex, _SHOWN_ATTR, True) def is_shown(ex): if not ex: return False return getattr(ex, _SHOWN_ATTR, False) def log_error(logger, ex, msg, *msg_args): if is_shown(ex): logger.error(msg, *msg_args) else: logger.exception...
_shown_attr = '_dbnd_shown' def set_shown(ex): setattr(ex, _SHOWN_ATTR, True) def is_shown(ex): if not ex: return False return getattr(ex, _SHOWN_ATTR, False) def log_error(logger, ex, msg, *msg_args): if is_shown(ex): logger.error(msg, *msg_args) else: logger.exception(ms...
class Solution: def searchRange(self, nums: List[int], target: int) -> List[int]: res = [-1, -1] if nums is None or len(nums) == 0: return res size = len(nums) l, r = 0, size - 1 while l < r: m = (l + r)//2 if nums[m] < target: ...
class Solution: def search_range(self, nums: List[int], target: int) -> List[int]: res = [-1, -1] if nums is None or len(nums) == 0: return res size = len(nums) (l, r) = (0, size - 1) while l < r: m = (l + r) // 2 if nums[m] < target: ...
def indexEqualsValue(array): left, right = 0, len(array) - 1 while left <= right: mid = left + (right - left) // 2 if array[mid] < mid: left = mid + 1 elif array[mid] == mid and mid == 0: return mid elif array[mid] == mid and array[mid - 1] < mid - 1: ...
def index_equals_value(array): (left, right) = (0, len(array) - 1) while left <= right: mid = left + (right - left) // 2 if array[mid] < mid: left = mid + 1 elif array[mid] == mid and mid == 0: return mid elif array[mid] == mid and array[mid - 1] < mid - 1...
# Power of 2 # https://www.interviewbit.com/problems/power-of-2/ # # Find if Given number is power of 2 or not. # More specifically, find if given number can be expressed as 2^k where k >= 1. # # Input: # # number length can be more than 64, which mean number can be greater than 2 ^ 64 (out of long long range) # # Outp...
class Solution: class Bignum(str): def __eq__(self, other): if len(self) == len(other): for (a, b) in zip(self, other): if a != b: return False return True return False def __mod__(self, other): ...
class Transformer: def support(self, obj) -> bool: pass def transform(self, obj): pass
class Transformer: def support(self, obj) -> bool: pass def transform(self, obj): pass
# # @lc app=leetcode id=150 lang=python3 # # [150] Evaluate Reverse Polish Notation # # https://leetcode.com/problems/evaluate-reverse-polish-notation/description/ # # algorithms # Medium (39.74%) # Likes: 2446 # Dislikes: 585 # Total Accepted: 356.4K # Total Submissions: 864.6K # Testcase Example: '["2","1","+"...
class Solution: def eval_rpn(self, tokens: List[str]) -> int: operators = ['+', '-', '*', '/'] stack = [] for token in tokens: stack.append(token) if token in operators: op = stack.pop() num2 = int(stack.pop()) num1 = i...
def subset(nums: list) -> None: result: list = [] def helper(idx: int, slate: list): if idx >= len(nums): result.append(list(slate)) else: slate.append(nums[idx]) helper(idx + 1, slate) slate.pop() helper(idx + 1, slate) helper(0,...
def subset(nums: list) -> None: result: list = [] def helper(idx: int, slate: list): if idx >= len(nums): result.append(list(slate)) else: slate.append(nums[idx]) helper(idx + 1, slate) slate.pop() helper(idx + 1, slate) helper(0, ...
MODEL_RUN_COLUMNS = list(['f1', 'f2', 'f3', 'm1', 'm2', 'm3', 'f1_1d', 'f2_1d', 'f3_1d', ...
model_run_columns = list(['f1', 'f2', 'f3', 'm1', 'm2', 'm3', 'f1_1d', 'f2_1d', 'f3_1d', 'm1_1d', 'm2_1d', 'm3_1d', 'fattr1', 'fattr2', 'fattr3', 'mattr1', 'mattr2', 'mattr3', 'attr1', 'attr2', 'attr3', 'attr', 'fattr', 'mattr', 'unfild', 'deptn', 'deptn_1d', 'lev1', 'lev2', 'lev3', 'f', 'm', 'fpct', 'fpct1', 'fpct2', ...
def get_model_path(relativePath): model_prepend = "models/" return model_prepend + relativePath squeezePath = get_model_path("squeezenet_weights_tf_dim_ordering_tf_kernels.h5") resPath = get_model_path("resnet50_weights_tf_dim_ordering_tf_kernels.h5") inceptionPath = get_model_path("inception_v3_weights_tf_...
def get_model_path(relativePath): model_prepend = 'models/' return model_prepend + relativePath squeeze_path = get_model_path('squeezenet_weights_tf_dim_ordering_tf_kernels.h5') res_path = get_model_path('resnet50_weights_tf_dim_ordering_tf_kernels.h5') inception_path = get_model_path('inception_v3_weights_tf_d...
def test_get_friend_data(coub_api_auth, requests_mock, snapshot_factory): requests_mock.get( f"/api/v2/friends", json=snapshot_factory(f"api/v2/friends/get_data.json") ) assert coub_api_auth.friends.get_data() def test_get_friend_data_from_provider(coub_api_auth, requests_mock, snapshot_factory):...
def test_get_friend_data(coub_api_auth, requests_mock, snapshot_factory): requests_mock.get(f'/api/v2/friends', json=snapshot_factory(f'api/v2/friends/get_data.json')) assert coub_api_auth.friends.get_data() def test_get_friend_data_from_provider(coub_api_auth, requests_mock, snapshot_factory): requests_mo...
def creat_matrix_playfair(key): # 5X5 matrix key = key.lower() array = [[] for i in range(5)] row = 0 col = 0 # assign key to the matrix for i in key: if (i == 'j'): # Convert j into i i = 'i' if not any(i in array[k] for k in range(5)): array[row].a...
def creat_matrix_playfair(key): key = key.lower() array = [[] for i in range(5)] row = 0 col = 0 for i in key: if i == 'j': i = 'i' if not any((i in array[k] for k in range(5))): array[row].append(i) col += 1 if col == 5: row +=...
def tuple_sum(u, v): if len(u) == len(v): sum = () i = 0 while i < len(u): sum += (u[i] + v[i],) i += 1 return sum def tuple_ask(): size = int(input("Entrez une taille de tuple:")) tuple = () while size != 0: tuple += (float(input("Valeur:...
def tuple_sum(u, v): if len(u) == len(v): sum = () i = 0 while i < len(u): sum += (u[i] + v[i],) i += 1 return sum def tuple_ask(): size = int(input('Entrez une taille de tuple:')) tuple = () while size != 0: tuple += (float(input('Valeur:...
#!/usr/bin/python # coding=utf-8 class MyProperty(object): def __init__(self): self._width = 0 def set_width(self, value): self._width = value def get_width(self): return self._width w_width = property(get_width, set_width) def __str__(self): return str(self._wid...
class Myproperty(object): def __init__(self): self._width = 0 def set_width(self, value): self._width = value def get_width(self): return self._width w_width = property(get_width, set_width) def __str__(self): return str(self._width) if __name__ == '__main__': ...
# A robot is located at the top-left corner of a m x n grid # (marked 'Start' in the diagram below). # # The robot can only move either down or right at any point in time. # The robot is trying to reach the bottom-right corner of the grid # (marked 'Finish' in the diagram below). # # How many possible unique paths are ...
class Solution: def unique_paths(self, m, n): matrix = [] for i in range(m): matrix.append([0] * n) for i in range(n): matrix[0][i] = 1 for i in range(m): matrix[i][0] = 1 for i in range(1, m): for j in range(1, n): ...
# Author: Lukas Alatalo #this program is a simulation of an escape room. The description of the room is displayed to the user and the user must find a #way to escape based on different hints. AUTHOR = "Lukas Alatalo" ROOM_NAME = "Piano Man" def escape_room(): print( '''You find yourself in a room with a...
author = 'Lukas Alatalo' room_name = 'Piano Man' def escape_room(): print('You find yourself in a room with a piano, a matress, and a bulletproof window.\nThere is a door that is locked and cannot be openned with a key. You can examine the window,\nthe mattress and the piano. There is also a Keymaster called Lukas...
print("Hello NET2008, 2020") print("Hello NET2008, 2019") print("I need to print a second line")
print('Hello NET2008, 2020') print('Hello NET2008, 2019') print('I need to print a second line')
A,K=map(int,input().split()) t=A ans=0 z=2*(10**12) if K==0:ans=z-A else: while t<z: t=t+1+K*t ans+=1 print(ans)
(a, k) = map(int, input().split()) t = A ans = 0 z = 2 * 10 ** 12 if K == 0: ans = z - A else: while t < z: t = t + 1 + K * t ans += 1 print(ans)
#single inheritance class My(object): y = 5988 class Mat(My): x = 54 p1 = Mat() print(p1.x) print(p1.y)
class My(object): y = 5988 class Mat(My): x = 54 p1 = mat() print(p1.x) print(p1.y)
def symbol_to_number(symbol): symbols_list = { 'A' : 0, 'C' : 1, 'G' : 2, 'T' : 3, } return symbols_list[symbol] def pattern_to_number(pattern): if len(pattern) == 0: return 0 symbol = pattern[-1] prefix = pattern[:-1] return 4*pattern_to_number(prefix)+symbol_to_number(symbol) '''def results(patt...
def symbol_to_number(symbol): symbols_list = {'A': 0, 'C': 1, 'G': 2, 'T': 3} return symbols_list[symbol] def pattern_to_number(pattern): if len(pattern) == 0: return 0 symbol = pattern[-1] prefix = pattern[:-1] return 4 * pattern_to_number(prefix) + symbol_to_number(symbol) "def result...
__metaclass__ = type class Servant: def __init__(self): self.order = [] self.count = []
__metaclass__ = type class Servant: def __init__(self): self.order = [] self.count = []
class ResponseBody: data = None code = 200 message = "success" def __init__(self, data=None, code=200, message='success', **kwargs): self.data = data self.code = code self.message = message self.size = (len(data) if isinstance(data, (list, set)) else 1) for key i...
class Responsebody: data = None code = 200 message = 'success' def __init__(self, data=None, code=200, message='success', **kwargs): self.data = data self.code = code self.message = message self.size = len(data) if isinstance(data, (list, set)) else 1 for key in ...
class MockClass(object): '''A class that allows you to call any method in it or its attributes (recursively), resulting in printing the exact call to stdout. ''' def __init__(self, name): self._name = name def __repr__(self): return "MockClass({0})".format(self._name) def __cal...
class Mockclass(object): """A class that allows you to call any method in it or its attributes (recursively), resulting in printing the exact call to stdout. """ def __init__(self, name): self._name = name def __repr__(self): return 'MockClass({0})'.format(self._name) def __ca...
USER="" PASSWORD="" URI="onyourbikemysql.cquggrydnjcx.eu-west-1.rds.amazonaws.com" PORT="3306" # DB=""
user = '' password = '' uri = 'onyourbikemysql.cquggrydnjcx.eu-west-1.rds.amazonaws.com' port = '3306'
def AND(a,b): return a*b def OR(a,b): return 1-(1-a)*(1-b) def NOT(a): return 1-a def XOR3 (a, b, c): w1 = AND(a,b) w2 = NOT(w1) w3 = OR(a,b) w4 = AND(w2,w3) w5 = AND(w4,c) w6 = NOT(w5) w7 = OR(w4,c) return AND(w6,w7) def update_lfsr(lfsr_equation): # calculate lfsr new value ...
def and(a, b): return a * b def or(a, b): return 1 - (1 - a) * (1 - b) def not(a): return 1 - a def xor3(a, b, c): w1 = and(a, b) w2 = not(w1) w3 = or(a, b) w4 = and(w2, w3) w5 = and(w4, c) w6 = not(w5) w7 = or(w4, c) return and(w6, w7) def update_lfsr(lfsr_equation): ...
# 10.2 Write a program to read through the mbox-short.txt and figure out the # distribution by hour of the day for each of the messages. You can pull the # hour out from the 'From ' line by finding the time and then splitting the # string a second time using a colon. # From stephen.marquard@uct.ac.za Sat Jan 5 09:14:1...
name = input('Enter file:') if len(name) < 1: name = 'mbox-short.txt' handle = open(name) hours = [] for line in handle: if not line.startswith('From '): continue line = line.split() time = line[5] hour = time[:2] hours.append(hour) distr = dict() for hour in hours: distr[hour] = dis...
i = [0] N = int(input()) estado = ["A"] * N print(i[0], estado) def hanoi(X, Y, Z, N): if(N <= 0): return hanoi(X, Z, Y, N-1) estado[N-1] = Y i[0] += 1 print(i[0], estado) hanoi(Z, Y, X, N-1) hanoi("A", "B", "C", N)
i = [0] n = int(input()) estado = ['A'] * N print(i[0], estado) def hanoi(X, Y, Z, N): if N <= 0: return hanoi(X, Z, Y, N - 1) estado[N - 1] = Y i[0] += 1 print(i[0], estado) hanoi(Z, Y, X, N - 1) hanoi('A', 'B', 'C', N)
# aa=open("log_sign.txt","w+") # dic={} # print("1. sign\n 2. login") # opti= input("chose the option ") # if opti=="1" or "sign": # a=input("Enter the name") # if "@gmail.com" in a: # pas = input("Enter the password") # ss,dd,ff,gg,hh=0,0,0,0,0 # if len(pas)>=8: # for i in...
a = open('/home/ng/Desktop/anurag/mangal_file.py', 'r') print(a.read())
# Time: (nd) | Space O(n) def minNumberOfCoinsForChange(n, denums): numOfCoins = [float("inf") for amount in range(n+1)] numOfCoins[0] = 0 for denom in denums: for amount in range(len(numOfCoins)): if denom <= amount: numOfCoins[amount] = min(numOfCoins[amount], 1 + numOf...
def min_number_of_coins_for_change(n, denums): num_of_coins = [float('inf') for amount in range(n + 1)] numOfCoins[0] = 0 for denom in denums: for amount in range(len(numOfCoins)): if denom <= amount: numOfCoins[amount] = min(numOfCoins[amount], 1 + numOfCoins[amount - de...
varinfo={} varinfo['PFT_FIRE_CLOSS']={'RepUnits': 'PgC/y', 'sets': [1, 2, 3, 5, 6], 'NatUnits': 'gC/m^2/s', 'desc': 'total pft-level fire C loss'} varinfo['SNOWDP']={'RepUnits': 'm', 'sets': [2, 3, 5, 6], 'NatUnits': 'm', 'desc': 'snow height'} varinfo['LITHR']={'RepUnits': 'PgC/y', 'sets': [1, 2, 5], 'NatUnits': 'gC/m...
varinfo = {} varinfo['PFT_FIRE_CLOSS'] = {'RepUnits': 'PgC/y', 'sets': [1, 2, 3, 5, 6], 'NatUnits': 'gC/m^2/s', 'desc': 'total pft-level fire C loss'} varinfo['SNOWDP'] = {'RepUnits': 'm', 'sets': [2, 3, 5, 6], 'NatUnits': 'm', 'desc': 'snow height'} varinfo['LITHR'] = {'RepUnits': 'PgC/y', 'sets': [1, 2, 5], 'NatUnits...
def title(string, icon='-'): print(string.center(100,icon))
def title(string, icon='-'): print(string.center(100, icon))
def renderStreet(map, street_id=0): graph = [] street = map.streets[street_id] # graph.append([-2 for _ in range(street.height)]) for lane in range(street.width): row = [] for cell in range(street.height): val = street.get((lane, cell)) row.append(-1 if val =...
def render_street(map, street_id=0): graph = [] street = map.streets[street_id] for lane in range(street.width): row = [] for cell in range(street.height): val = street.get((lane, cell)) row.append(-1 if val == 0 else val.speed) graph.append(row) return gr...
ORDWAY_APP_DOMAIN = "app.ordwaylabs.com" ORDWAY_APP_URL = f"https://{ORDWAY_APP_DOMAIN}" ORDWAY_STAGING_DOMAIN = "staging.ordwaylabs.com" ORDWAY_STAGING_URL = f"https://{ORDWAY_STAGING_DOMAIN}" API_ENDPOINT_BASE = f"{ORDWAY_APP_URL}/api" STAGING_ENDPOINT_BASE = f"{ORDWAY_STAGING_URL}/api" SUPPORTED_API_VERSIONS = ("...
ordway_app_domain = 'app.ordwaylabs.com' ordway_app_url = f'https://{ORDWAY_APP_DOMAIN}' ordway_staging_domain = 'staging.ordwaylabs.com' ordway_staging_url = f'https://{ORDWAY_STAGING_DOMAIN}' api_endpoint_base = f'{ORDWAY_APP_URL}/api' staging_endpoint_base = f'{ORDWAY_STAGING_URL}/api' supported_api_versions = ('1',...
# all hook will be in here # this file will hook the commands with funcations class Hooklist: def Hookslist(self): return { "@sendmsg": "msg", "@deletemsg": "del" } def hookkey(self): return self.Hookslist().keys()
class Hooklist: def hookslist(self): return {'@sendmsg': 'msg', '@deletemsg': 'del'} def hookkey(self): return self.Hookslist().keys()
# Copyright (C) 2021 Clinton Garwood # MIT Open Source Initiative Approved License # sum_total_clinton.py # CIS-135 Python # Assignment #14 Sum Total Calculations # Rubric: 1 Point # Create a function named askAgain that contains a while loop that asks a user # to enter any number, or 0 (the number zero) to ex...
def ask_again(): sub_total = 0 loop_counter = 0 get_input = int(input('\tPlease enter a number, or enter 0 (zero) to exit: ')) while get_input != 0: sub_total += get_input loop_counter += 1 print('\tLoop count:', loop_counter, 'Running grand total so far: ', sub_total) ge...
class CsvReader(): def __init__(self, sep=',', header=False, skip_top=0, skip_bottom=0): self.sep = sep self.header = header self.skip_top = skip_top self.skip_bottom = skip_bottom def __enter__(self): pass def __exit__(self,exc_type, exc_val, exc_tb): ...
class Csvreader: def __init__(self, sep=',', header=False, skip_top=0, skip_bottom=0): self.sep = sep self.header = header self.skip_top = skip_top self.skip_bottom = skip_bottom def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass
# Make a copy of this as IBM_API_KEYS.py and fill in your API keys #### IBM ################## ## STT STT_API_ENDPOINT = "https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/d01dba71-c104-4035-beb2-979315bfc91f" STT_API_KEY = "luSLdQ7tvPb0K9EdAfwA37OYRW8L-KvvRaZ2l4r2XA2G" # TA TA_API_ENDPOINT = "https:...
stt_api_endpoint = 'https://api.us-south.speech-to-text.watson.cloud.ibm.com/instances/d01dba71-c104-4035-beb2-979315bfc91f' stt_api_key = 'luSLdQ7tvPb0K9EdAfwA37OYRW8L-KvvRaZ2l4r2XA2G' ta_api_endpoint = 'https://api.us-south.tone-analyzer.watson.cloud.ibm.com/instances/ac0ebb12-0c6a-49bf-9726-0ece18c5fb13' ta_api_key ...
def determine_status(name, current, warn, critical, trigger=None): if not warn and not critical: return 'ok' if trigger: if trigger == 'ignore': return 'ok' if trigger == 'lt': if warn and current > warn: return 'ok' if warn and cri...
def determine_status(name, current, warn, critical, trigger=None): if not warn and (not critical): return 'ok' if trigger: if trigger == 'ignore': return 'ok' if trigger == 'lt': if warn and current > warn: return 'ok' if warn and criti...
route_types = { 0: 'Light Rail', 1: 'Heavy Rail', 2: 'Commuter Rail', 3: 'Bus', 4: 'Ferry' }
route_types = {0: 'Light Rail', 1: 'Heavy Rail', 2: 'Commuter Rail', 3: 'Bus', 4: 'Ferry'}
load("//:import_external.bzl", import_external = "safe_wix_scala_maven_import_external") def dependencies(): import_external( name = "com_typesafe_akka_akka_actor_2_12", artifact = "com.typesafe.akka:akka-actor_2.12:2.5.15", artifact_sha256 = "7e5157e3709fae72fbab8388cb04a654320146cf99cc0c90848a42...
load('//:import_external.bzl', import_external='safe_wix_scala_maven_import_external') def dependencies(): import_external(name='com_typesafe_akka_akka_actor_2_12', artifact='com.typesafe.akka:akka-actor_2.12:2.5.15', artifact_sha256='7e5157e3709fae72fbab8388cb04a654320146cf99cc0c90848a421db6953d2b', srcjar_sha256...
def merge_sort(arr): if (len(arr)>1): mid = len(arr) // 2 lefthalf, righthalf = arr[:mid] , arr[mid:] merge_sort(lefthalf) merge_sort(righthalf) merge(lefthalf, righthalf, arr) def merge(lh, rh, arr): il = 0 ir = 0 k = 0 while il < len(lh) and ir < len(rh):...
def merge_sort(arr): if len(arr) > 1: mid = len(arr) // 2 (lefthalf, righthalf) = (arr[:mid], arr[mid:]) merge_sort(lefthalf) merge_sort(righthalf) merge(lefthalf, righthalf, arr) def merge(lh, rh, arr): il = 0 ir = 0 k = 0 while il < len(lh) and ir < len(rh)...
# Configuration variables for the backup # Location to store temporary tar.gz and gpg objects (preferably somewhere with large amounts of storage) TMP_STORE_DIR = '/mnt/lvm/temp' # Place mysqldump user and password in ~/.my.cnf (with permission 600) BACKUP_MYSQL = True # Backup root directories ROOT_BACKUP_DIRS = [ ...
tmp_store_dir = '/mnt/lvm/temp' backup_mysql = True root_backup_dirs = ['/bin', '/boot', '/etc', '/lib32', '/lib64', '/opt', '/root', '/usr', '/var'] media_backup_dirs = ['/mnt/lvm/appz', '/mnt/lvm/audiobooks', '/mnt/lvm/ebooks', '/mnt/lvm/games', '/mnt/lvm/movies/Documentaries', '/mnt/lvm/music', '/mnt/lvm/other movie...
''' Kattis - chocolates Pre-computable complete search problem. Since the input space is small (16), we can compute all the values first. Notice that there are 2 check to check if a placing of chocolates forms a polygon: first we check if the chocolates are a single connected component in terms of 4 directional flood ...
""" Kattis - chocolates Pre-computable complete search problem. Since the input space is small (16), we can compute all the values first. Notice that there are 2 check to check if a placing of chocolates forms a polygon: first we check if the chocolates are a single connected component in terms of 4 directional flood ...
class RegexError(Exception): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class TomlError(Exception): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class AuthenticationError(Exception): def __init__(self, *args, **kwargs): super()....
class Regexerror(Exception): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Tomlerror(Exception): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Authenticationerror(Exception): def __init__(self, *args, **kwargs): super...
# Time Complexity: O(N), Space Complexity: O(1) def isMonotonic(array): if len(array) <= 2: return True isNonDecreasing = True isNonIncreasing = True for i in range(1, len(array)): if array[i] > array[i - 1]: isNonIncreasing = False if array[i] < array[i - 1]: ...
def is_monotonic(array): if len(array) <= 2: return True is_non_decreasing = True is_non_increasing = True for i in range(1, len(array)): if array[i] > array[i - 1]: is_non_increasing = False if array[i] < array[i - 1]: is_non_decreasing = False return...
# Copyright 2017 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Recipe for uploading skiaserve to gs://skia-public-binaries. DEPS = [ 'flavor', 'gsutil', 'recipe_engine/context', 'recipe_engine/file', 'reci...
deps = ['flavor', 'gsutil', 'recipe_engine/context', 'recipe_engine/file', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/step', 'recipe_engine/time', 'vars'] def run_steps(api): api.vars.setup() if api.properties.get('patch_issue') or api.properties.get('patch_set'): return src =...
with open ("customers.csv") as customer_data: line_counter = 0 customer_list = [] data_header = [] while 1: data = customer_data.readline() if not data: break if line_counter == 0: data_header = data.split(",") else: customer_list.append(data.split...
with open('customers.csv') as customer_data: line_counter = 0 customer_list = [] data_header = [] while 1: data = customer_data.readline() if not data: break if line_counter == 0: data_header = data.split(',') else: customer_list.append...
''' source: https://codeforces.com/contest/1665/problem/A AC ''' n = int(input()) for i in range(n): in_num = int(input()) print(f'{1} {in_num-3} {1} {1}')
""" source: https://codeforces.com/contest/1665/problem/A AC """ n = int(input()) for i in range(n): in_num = int(input()) print(f'{1} {in_num - 3} {1} {1}')
class Node: def __init__(self, data, parent): self.data = data self.parent = parent self.left_child = None self.right_child = None self.height = 0 class AVLTree: def __init__(self): self.root = None def insert(self, data): if not self.root: ...
class Node: def __init__(self, data, parent): self.data = data self.parent = parent self.left_child = None self.right_child = None self.height = 0 class Avltree: def __init__(self): self.root = None def insert(self, data): if not self.root: ...
BASIC_CHARACTER_SET = { 0x00: 'COMMERCIAL AT', 0x01: 'POUND SIGN', 0x02: 'DOLLAR SIGN', 0x03: 'YEN SIGN', 0x04: 'LATIN SMALL LETTER E WITH GRAVE', 0x05: 'LATIN SMALL LETTER E WITH ACUTE', 0x06: 'LATIN SMALL LETTER U WITH GRAVE', 0x07: 'LATIN SMALL LETTER I WITH GRAVE', 0x08: 'LATIN S...
basic_character_set = {0: 'COMMERCIAL AT', 1: 'POUND SIGN', 2: 'DOLLAR SIGN', 3: 'YEN SIGN', 4: 'LATIN SMALL LETTER E WITH GRAVE', 5: 'LATIN SMALL LETTER E WITH ACUTE', 6: 'LATIN SMALL LETTER U WITH GRAVE', 7: 'LATIN SMALL LETTER I WITH GRAVE', 8: 'LATIN SMALL LETTER O WITH GRAVE', 9: 'LATIN CAPITAL LETTER C WITH CEDIL...
# SQLess Main Library file #A class fo using tables class table(object): path = '' # the location of a CSV file form = [] # the format of the CSV file (eg. ID, name, DoB,) content = [] # a 2d array, will be filled with sub arrays, each ub array is a row def read_table(self, p): # read in a d...
class Table(object): path = '' form = [] content = [] def read_table(self, p): try: with open(p, 'r') as f: stream = f.read() except FileNotFoundError as E: raise file_not_found_error('No such path: {}'.format(p)) stream = stream.strip('\n...
snippet_normalize (cr, width, height) cr.select_font_face ("Sans", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) cr.set_font_size (0.35) cr.move_to (0.04, 0.53) cr.show_text ("Hello") cr.move_to (0.27, 0.65) cr.text_path ("void") cr.set_source_rgb (0.5,0.5,1) cr.fill_preserve () cr.set_source_...
snippet_normalize(cr, width, height) cr.select_font_face('Sans', cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_BOLD) cr.set_font_size(0.35) cr.move_to(0.04, 0.53) cr.show_text('Hello') cr.move_to(0.27, 0.65) cr.text_path('void') cr.set_source_rgb(0.5, 0.5, 1) cr.fill_preserve() cr.set_source_rgb(0, 0, 0) cr.set_line_width...
# pytools/recursion/json_parse.py # # Author: Daniel Clark, 2016 ''' This module contains a function to parse a json object to find and replace string values ''' def json_parse(json, key_str, old_str, new_str): ''' Recursively parse a json object to replace old string with the new string based on a dot-s...
""" This module contains a function to parse a json object to find and replace string values """ def json_parse(json, key_str, old_str, new_str): """ Recursively parse a json object to replace old string with the new string based on a dot-separated key string path :param json: a dict, list, string, or...
class MyClass: variable1 = 1 variable2 = 2 def foo(self): # We'll explain self parameter later return "Hello from function foo" my_object = MyClass() another_object = MyClass() my_object.variable2 = 3 # Assign a new value to variable2 in my_object print(my_object.variable2) print(anothe...
class Myclass: variable1 = 1 variable2 = 2 def foo(self): return 'Hello from function foo' my_object = my_class() another_object = my_class() my_object.variable2 = 3 print(my_object.variable2) print(another_object.variable2) print(my_object.variable1) print(my_object.foo())
class AR: def __init__(self, raw): self.raw = raw self.APIs = [] self.parse() def parse(self): start, end = 0x8, 0x8 while True: end = start + 60 fileHeader = self.raw[ start : end ] if fileHeader == b'': break fileN...
class Ar: def __init__(self, raw): self.raw = raw self.APIs = [] self.parse() def parse(self): (start, end) = (8, 8) while True: end = start + 60 file_header = self.raw[start:end] if fileHeader == b'': break ...
with open('input.txt', 'r') as reader: layout = [[c for c in line.strip()] for line in reader.readlines()] x_max = len(layout[0]) y_max = len(layout) def next_state(state, x, y, seat_count_func, max_seat): if state[y][x] == '.': return '.' count = seat_count_func(state, x, y) if state[y][x] == ...
with open('input.txt', 'r') as reader: layout = [[c for c in line.strip()] for line in reader.readlines()] x_max = len(layout[0]) y_max = len(layout) def next_state(state, x, y, seat_count_func, max_seat): if state[y][x] == '.': return '.' count = seat_count_func(state, x, y) if state[y...
# -*- coding: utf-8 -*- # Coded By Kuduxaaa DB_PORT = 3306 DB_HOST = 'localhost' DB_USER = 'root' DB_PASS = '' DB_NAME = '' class Config(object): DEBUG = False TESTING = False CSRF_ENABLED = True SITE_NAME = 'Wavetech TTS' SECRET_KEY = 'c219d4e3-3ea8-4dbb-8641-8bbfc644aa18' SQLALCHEMY_DATABASE...
db_port = 3306 db_host = 'localhost' db_user = 'root' db_pass = '' db_name = '' class Config(object): debug = False testing = False csrf_enabled = True site_name = 'Wavetech TTS' secret_key = 'c219d4e3-3ea8-4dbb-8641-8bbfc644aa18' sqlalchemy_database_uri = f'mysql://{DB_USER}:{DB_PASS}@{DB_HOST...
class Point(): def __init__(self, input1, input2): self.x= input1 self.y= input2 p = Point(2,8) print(p.x) print(p.y) class Flight(): def __init__(self, capacity): self.capacity = capacity self.passengers = [] def add_passenger(self, name): if not self.open_seats()...
class Point: def __init__(self, input1, input2): self.x = input1 self.y = input2 p = point(2, 8) print(p.x) print(p.y) class Flight: def __init__(self, capacity): self.capacity = capacity self.passengers = [] def add_passenger(self, name): if not self.open_seats()...
def getUserFollowers(self, usernameId, maxid=''): if maxid == '': return self.SendRequest('friendships/' + str(usernameId) + '/followers/?rank_token=' + self.rank_token) else: return self.SendRequest('friendships/' + str(usernameId) + '/followers/?rank_token=' + self.rank_token...
def get_user_followers(self, usernameId, maxid=''): if maxid == '': return self.SendRequest('friendships/' + str(usernameId) + '/followers/?rank_token=' + self.rank_token) else: return self.SendRequest('friendships/' + str(usernameId) + '/followers/?rank_token=' + self.rank_token + '&max_id=' + ...
a,b,c=map(int,input().split()) S = -671 for i in range(11,a): S+=1440 S += b*60 +c if S<0: print(-1) else: print(S)
(a, b, c) = map(int, input().split()) s = -671 for i in range(11, a): s += 1440 s += b * 60 + c if S < 0: print(-1) else: print(S)
class vowels: def __init__(self, string): self.string = string self.vowels = 'AaEeOoYyUuIi' self.index = 0 def __iter__(self): return self def __next__(self): if self.index == len(self.string): raise StopIteration() current_idx = self.index ...
class Vowels: def __init__(self, string): self.string = string self.vowels = 'AaEeOoYyUuIi' self.index = 0 def __iter__(self): return self def __next__(self): if self.index == len(self.string): raise stop_iteration() current_idx = self.index ...
def test(): print("FOO test FOO") class TestOutputSave: def setup(self): print("BAR OutputTest.setup BAR") def test(self): print("BAR OutputTest.test BAR") def teardown(self): print("BAR OutputTest.teardown BAR") def test_fail(): print('FIBBLE') assert 0 def test_err...
def test(): print('FOO test FOO') class Testoutputsave: def setup(self): print('BAR OutputTest.setup BAR') def test(self): print('BAR OutputTest.test BAR') def teardown(self): print('BAR OutputTest.teardown BAR') def test_fail(): print('FIBBLE') assert 0 def test_er...