content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Iterator(object): def __init__(self, iterable, looping: bool = False): self.iterable = iterable self.lastPos = 0 self.looping = looping def __next__(self): pos = self.lastPos self.lastPos += 1 if self.lastPos >= len(self.iterable): if self.looping: self.lastPos = 0 else: raise StopIt...
class Iterator(object): def __init__(self, iterable, looping: bool=False): self.iterable = iterable self.lastPos = 0 self.looping = looping def __next__(self): pos = self.lastPos self.lastPos += 1 if self.lastPos >= len(self.iterable): if self.loopin...
################################################################################## #### Runtime configuration ################################################################################## sampleCounter = 0 ################################################################################## #### General configurati...
sample_counter = 0 version = '1.0.2103.0401' lcd_i2c_expander_type = 'PCF8574' lcd_i2c_address = 39 lcd_column_count = 20 lcd_row_count = 4
# REPLACE EVERYTHING IN CURLY BRACKETS {}, INCLUDING THE BRACKETS THEMSELVES. # THEN RENAME THIS FILE TO constants.py AND MOVE IT INTO YOUR PROJECT'S ROOT CONNECT_BASE_URL = '{YOUR BASE URL}/api/xml?action=' CONNECT_LOGIN = '{YOUR LOGIN}' CONNECT_PWD = '{YOUR PASSWORD}' # USERS YOU WANT TO BE ABLE TO EXCLUDE FROM REP...
connect_base_url = '{YOUR BASE URL}/api/xml?action=' connect_login = '{YOUR LOGIN}' connect_pwd = '{YOUR PASSWORD}' connect_admin_users = ['{USER1LOGIN}', '{USER2LOGIN}', '{USER3LOGIN}']
# -*- coding: utf-8 -*- def crearCombinaciones(abecedario): for d1 in abecedario: for d2 in abecedario: for d3 in abecedario: for d4 in abecedario: #print(d1 + '' + d2 + '' + d3 + '' + d4) f.write(d1 + '' + d2 + '' + d3 + '' + d4) ...
def crear_combinaciones(abecedario): for d1 in abecedario: for d2 in abecedario: for d3 in abecedario: for d4 in abecedario: f.write(d1 + '' + d2 + '' + d3 + '' + d4) f.write('\n') abecedario = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', ...
set_name(0x8009CFEC, "VID_OpenModule__Fv", SN_NOWARN) set_name(0x8009D0AC, "InitScreens__Fv", SN_NOWARN) set_name(0x8009D19C, "MEM_SetupMem__Fv", SN_NOWARN) set_name(0x8009D1C8, "SetupWorkRam__Fv", SN_NOWARN) set_name(0x8009D258, "SYSI_Init__Fv", SN_NOWARN) set_name(0x8009D364, "GM_Open__Fv", SN_NOWARN) set_name(0x8009...
set_name(2148126700, 'VID_OpenModule__Fv', SN_NOWARN) set_name(2148126892, 'InitScreens__Fv', SN_NOWARN) set_name(2148127132, 'MEM_SetupMem__Fv', SN_NOWARN) set_name(2148127176, 'SetupWorkRam__Fv', SN_NOWARN) set_name(2148127320, 'SYSI_Init__Fv', SN_NOWARN) set_name(2148127588, 'GM_Open__Fv', SN_NOWARN) set_name(214812...
lr_scheduler = dict( name='poly_scheduler', epochs=30, power=0.9 )
lr_scheduler = dict(name='poly_scheduler', epochs=30, power=0.9)
size(800, 600) background(255) triangle(20, 20, 20, 50, 50, 20) triangle(200, 100, 200, 150, 300, 320) triangle(700, 500, 800, 550, 600, 600)
size(800, 600) background(255) triangle(20, 20, 20, 50, 50, 20) triangle(200, 100, 200, 150, 300, 320) triangle(700, 500, 800, 550, 600, 600)
#part 1 count = 0 expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'} received_fields = set() with open("input.txt") as f: for line in f: if line != '\n': fields = {i[:3] for i in line.split(' ')} received_fields.update(fields) else: difference = e...
count = 0 expected_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'} received_fields = set() with open('input.txt') as f: for line in f: if line != '\n': fields = {i[:3] for i in line.split(' ')} received_fields.update(fields) else: difference = expected_...
ACTION_CREATED = 'created' ACTION_UPDATED = 'updated' ACTION_DELETED = 'deleted' ACTION_OTHER = 'other' ACTION_CHOICES = ( (ACTION_CREATED, ACTION_CREATED), (ACTION_UPDATED, ACTION_UPDATED), (ACTION_DELETED, ACTION_DELETED), (ACTION_OTHER, ACTION_OTHER), ) LOG_LEVEL_CRITICAL = 'CRITICAL' LOG_LEVEL_ERRO...
action_created = 'created' action_updated = 'updated' action_deleted = 'deleted' action_other = 'other' action_choices = ((ACTION_CREATED, ACTION_CREATED), (ACTION_UPDATED, ACTION_UPDATED), (ACTION_DELETED, ACTION_DELETED), (ACTION_OTHER, ACTION_OTHER)) log_level_critical = 'CRITICAL' log_level_error = 'ERROR' log_leve...
def interest(n, principle_amount): def years(x): return principle_amount + (n * principle_amount * x) / 100 return years principle = 100000 home_loan = interest(7, principle) # percentage of 7 personal_loan = interest(11, principle) # percentage of 11 print(home_loan(20)) # for 20 years print(per...
def interest(n, principle_amount): def years(x): return principle_amount + n * principle_amount * x / 100 return years principle = 100000 home_loan = interest(7, principle) personal_loan = interest(11, principle) print(home_loan(20)) print(personal_loan(3))
class ProducerEvent: timestamp = 0 csvName = "" houseId = 0 deviceId = 0 id = 0 def __init__(self, timestamp, ids, csv_name): self.timestamp = int(timestamp) self.csvName = csv_name # ids_list = list(map(int, ids.replace("[", "").replace("]", "").replace("pv_producer", "...
class Producerevent: timestamp = 0 csv_name = '' house_id = 0 device_id = 0 id = 0 def __init__(self, timestamp, ids, csv_name): self.timestamp = int(timestamp) self.csvName = csv_name ids_list = csv_name.split('_') self.houseId = int(ids_list[0]) self.de...
# some mnemonics as specific to capstone CJMP_INS = ["je", "jne", "js", "jns", "jp", "jnp", "jo", "jno", "jl", "jle", "jg", "jge", "jb", "jbe", "ja", "jae", "jcxz", "jecxz", "jrcxz"] LOOP_INS = ["loop", "loopne", "loope"] JMP_INS = ["jmp", "ljmp"] CALL_INS = ["call", "lcall"] RET_INS = ["ret", "retn", "retf", "iret"] ...
cjmp_ins = ['je', 'jne', 'js', 'jns', 'jp', 'jnp', 'jo', 'jno', 'jl', 'jle', 'jg', 'jge', 'jb', 'jbe', 'ja', 'jae', 'jcxz', 'jecxz', 'jrcxz'] loop_ins = ['loop', 'loopne', 'loope'] jmp_ins = ['jmp', 'ljmp'] call_ins = ['call', 'lcall'] ret_ins = ['ret', 'retn', 'retf', 'iret'] end_ins = ['ret', 'retn', 'retf', 'iret', ...
def main(): # input N = int(input()) # compute N = int(1.08*N) # output if N < 206: print('Yay!') elif N == 206: print('so-so') else: print(':(') if __name__ == '__main__': main()
def main(): n = int(input()) n = int(1.08 * N) if N < 206: print('Yay!') elif N == 206: print('so-so') else: print(':(') if __name__ == '__main__': main()
# -*- coding: utf-8 -*- strings = { 'test.fallback': 'A fallback string' }
strings = {'test.fallback': 'A fallback string'}
def climb_stairs2(n: int) -> int: if n == 1 or n == 2: return n n1 = 1 n2 = 2 t = 0 for i in range(3, n + 1): t = n1 + n2 n1 = n2 n2 = t return t class StairClimber: # total variable needed for the recursive solution total = 0 # recursive, mathy w...
def climb_stairs2(n: int) -> int: if n == 1 or n == 2: return n n1 = 1 n2 = 2 t = 0 for i in range(3, n + 1): t = n1 + n2 n1 = n2 n2 = t return t class Stairclimber: total = 0 def climb_stairs(self, n: int) -> int: if n == 0: self.tot...
#!usr/bin/python # -*- coding:utf8 -*- def gen_func(): try: yield "http://projectesdu.com" except GeneratorExit: pass yield 2 yield 3 return "bobby" if __name__ == "__main__": gen = gen_func() next(gen) gen.close() next(gen)
def gen_func(): try: yield 'http://projectesdu.com' except GeneratorExit: pass yield 2 yield 3 return 'bobby' if __name__ == '__main__': gen = gen_func() next(gen) gen.close() next(gen)
list_images = [ ".jpeg",".jpg",".png",".gif",".webp",".tiff",".psd",".raw",".bmp",".heif",".indd",".svg",".ico" ] list_documents = [ ".doc",".txt",".pdf",".xlsx",".docx",".xls",".rtf",".md",".ods",".ppt",".pptx" ] list_videos = [ ".mp4",".m4v",".f4v",".f4a",".m4b",".m4r",".f4b",".mov",".3gp", "....
list_images = ['.jpeg', '.jpg', '.png', '.gif', '.webp', '.tiff', '.psd', '.raw', '.bmp', '.heif', '.indd', '.svg', '.ico'] list_documents = ['.doc', '.txt', '.pdf', '.xlsx', '.docx', '.xls', '.rtf', '.md', '.ods', '.ppt', '.pptx'] list_videos = ['.mp4', '.m4v', '.f4v', '.f4a', '.m4b', '.m4r', '.f4b', '.mov', '.3gp', '...
# Least Common Multiple (LCM) Calculator - Burak Karabey def LCM(x, y): if x > y: limit = x else: limit = y prime_numbers = [] # Start of Finding Prime Number if limit < 2: return prime_numbers.append(0) elif limit == 2: return prime_numbers.append(2) else: ...
def lcm(x, y): if x > y: limit = x else: limit = y prime_numbers = [] if limit < 2: return prime_numbers.append(0) elif limit == 2: return prime_numbers.append(2) else: prime_numbers.append(2) for t in range(3, limit): find_prime = Fals...
def is_prime(n): if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True T = int(input()) for _ in range(T): if...
def is_prime(n): if n <= 1: return False elif n <= 3: return True elif n % 2 == 0 or n % 3 == 0: return False i = 5 while i * i <= n: if n % i == 0 or n % (i + 2) == 0: return False i += 6 return True t = int(input()) for _ in range(T): if ...
#!/usr/bin/env python3 sum=0 a=1 while a<=100: sum +=a a+=1 print(sum)
sum = 0 a = 1 while a <= 100: sum += a a += 1 print(sum)
class PositionedObjectError(Exception): def __init__(self, *args): super().__init__(*args) class RelativePositionNotSettableError(PositionedObjectError): pass class RelativeXNotSettableError(RelativePositionNotSettableError): pass class RelativeYNotSettableError(RelativePositionNotSettableErro...
class Positionedobjecterror(Exception): def __init__(self, *args): super().__init__(*args) class Relativepositionnotsettableerror(PositionedObjectError): pass class Relativexnotsettableerror(RelativePositionNotSettableError): pass class Relativeynotsettableerror(RelativePositionNotSettableError)...
# Image types INTENSITY = 'intensity' LABEL = 'label' SAMPLING_MAP = 'sampling_map' # Keys for dataset samples PATH = 'path' TYPE = 'type' STEM = 'stem' DATA = 'data' AFFINE = 'affine' # For aggregator IMAGE = 'image' LOCATION = 'location' # In PyTorch convention CHANNELS_DIMENSION = 1 # Code repository REPO_URL = ...
intensity = 'intensity' label = 'label' sampling_map = 'sampling_map' path = 'path' type = 'type' stem = 'stem' data = 'data' affine = 'affine' image = 'image' location = 'location' channels_dimension = 1 repo_url = 'https://github.com/fepegar/torchio/' data_repo = 'https://github.com/fepegar/torchio-data/raw/master/da...
#!/usr/local/bin/python3 # Copyright 2019 NineFx Inc. # Justin Baum # 3 June 2019 # Precis Code-Generator ReasonML # https://github.com/NineFX/smeagol/blob/master/spec/code_gen/precis_cp.txt fp = open('precis_cp.txt', 'r') ranges = [] line = fp.readline() code = "DISALLOWED" prev = "DISALLOWED" firstOccurence = 0 co...
fp = open('precis_cp.txt', 'r') ranges = [] line = fp.readline() code = 'DISALLOWED' prev = 'DISALLOWED' first_occurence = 0 count = 0 while line: count += 1 line = fp.readline() if len(line) < 2: break linesplit = line.split(';') codepoint = int(linesplit[0]) code = linesplit[1][:-1] ...
# https://leetcode.com/problems/unique-morse-code-words/ class Solution: def uniqueMorseRepresentations(self, words: List[str]) -> int: dictx = {"a": ".-", "b": "-...", "c": "-.-.", "d": "-..", "e": ".", "f": "..-.", "g": "--.", "h": "....", "i": "..", "j": ".---", "k": "-...
class Solution: def unique_morse_representations(self, words: List[str]) -> int: dictx = {'a': '.-', 'b': '-...', 'c': '-.-.', 'd': '-..', 'e': '.', 'f': '..-.', 'g': '--.', 'h': '....', 'i': '..', 'j': '.---', 'k': '-.-', 'l': '.-..', 'm': '--', 'n': '-.', 'o': '---', 'p': '.--.', 'q': '--.-', 'r': '.-.',...
class BadBatchRequestException(Exception): def __init__(self, org, repo, message=None): super() self.org = org self.repo = repo self.message = message class UnknownBatchOperationException(Exception): def __init__(self, org, repo, operation, message=None): super() ...
class Badbatchrequestexception(Exception): def __init__(self, org, repo, message=None): super() self.org = org self.repo = repo self.message = message class Unknownbatchoperationexception(Exception): def __init__(self, org, repo, operation, message=None): super() ...
class Agent: def __init__(self, name): self.name = name def reset(self, state): # Completely resets the state of the Agent for a new game return def make_action(self, state): # Returns a valid move in (row, column) format where 0 <= row, column < board_len move = (0, 0) return move def u...
class Agent: def __init__(self, name): self.name = name def reset(self, state): return def make_action(self, state): move = (0, 0) return move def update_state(self, move): return @staticmethod def get_params(): return ()
# # PySNMP MIB module ONEACCESS-SYS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ONEACCESS-SYS-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:25:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) ...
TOKEN = b'd4r3d3v!l' def chall(): s = Sign() while True: choice = input("> ").rstrip() if choice == 'P': print("\nN : {}".format(hex(s.n))) print("\ne : {}".format(hex(s.e))) elif choice == 'S': try: msg = bytes.fromhex(input('msg to si...
token = b'd4r3d3v!l' def chall(): s = sign() while True: choice = input('> ').rstrip() if choice == 'P': print('\nN : {}'.format(hex(s.n))) print('\ne : {}'.format(hex(s.e))) elif choice == 'S': try: msg = bytes.fromhex(input('msg to s...
# Python Class 2406 # Lesson 12 Problem 1 # Author: snowapple (471208) class Game: def __init__(self, n): '''__init__(n) -> Game creates an instance of the Game class''' if n% 2 == 0: #n has to be odd print('Please enter an odd n!') raise ValueError self.n ...
class Game: def __init__(self, n): """__init__(n) -> Game creates an instance of the Game class""" if n % 2 == 0: print('Please enter an odd n!') raise ValueError self.n = n self.board = [[0 for x in range(self.n)] for x in range(self.n)] self...
def BFS(graph,root,p1,max1): checked = [] visited=[] energy=[] level=[] l=[] l.append(root) level.append(l) checked.append(root) inienergy=14600 threshold=10 l1=0 flag=0 energy.append(inienergy) while(len(checked)>0): l1=l1+1 #print...
def bfs(graph, root, p1, max1): checked = [] visited = [] energy = [] level = [] l = [] l.append(root) level.append(l) checked.append(root) inienergy = 14600 threshold = 10 l1 = 0 flag = 0 energy.append(inienergy) while len(checked) > 0: l1 = l1 + 1 ...
s="this this is a a cat cat cat ram ram jai it" l=[] count=[] i=0 #j=0 str="" for i in s: #print(i,end="") if i==" ": if str in l: for j in range(len(l)): if str == l[j]: count[j] += 1 str="" continue else: ...
s = 'this this is a a cat cat cat ram ram jai it' l = [] count = [] i = 0 str = '' for i in s: if i == ' ': if str in l: for j in range(len(l)): if str == l[j]: count[j] += 1 str = '' continue else: l...
class LRUCache: def __init__(self, capacity: int): self.db = dict() self.capacity = capacity self.time = 0 def get(self, key: int) -> int: if key in self.db: self.db[key][1] = self.time self.time += 1 return self.db[key][0] else: ...
class Lrucache: def __init__(self, capacity: int): self.db = dict() self.capacity = capacity self.time = 0 def get(self, key: int) -> int: if key in self.db: self.db[key][1] = self.time self.time += 1 return self.db[key][0] else: ...
# 2021.04.14 # Problem Statement: # https://leetcode.com/problems/majority-element/ class Solution: def majorityElement(self, nums: List[int]) -> int: # trivial question, no need to explain if len(nums) == 1: return nums[0] dict = {} for element in nums: if element not i...
class Solution: def majority_element(self, nums: List[int]) -> int: if len(nums) == 1: return nums[0] dict = {} for element in nums: if element not in dict.keys(): dict[element] = 1 else: dict[element] = dict[element] + 1 ...
def ParseGraphVertexEdge(file): with open(file, 'r') as fw: read_data = fw.read() res = read_data.splitlines(False) def ParseV(v_str): ''' @type v_str: string :param v_str: :return: ''' return [int(i) for i...
def parse_graph_vertex_edge(file): with open(file, 'r') as fw: read_data = fw.read() res = read_data.splitlines(False) def parse_v(v_str): """ @type v_str: string :param v_str: :return: """ return [int(i) for i in v_str...
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n = len(nums1) m = len(nums2) if (n > m): return self.findMedianSortedArrays(nums2, nums1) start = 0 end = n realmidinmergedarray = (n + m + 1) // 2 wh...
class Solution: def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float: n = len(nums1) m = len(nums2) if n > m: return self.findMedianSortedArrays(nums2, nums1) start = 0 end = n realmidinmergedarray = (n + m + 1) // 2 wh...
data_rows = [2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, 25, 27] data_rows_cool = [2, 3, 4, 6, 7, 8, 10, 12, 14] hig_temp_techs = [2, 7, 8, 13, 14, 16, 18, 20, 22] med_temp_techs = [3, 4, 5, 9, 10, 11] low_temp_techs = [24, 25] no_imput_rows_color = [232, 232, 232]
data_rows = [2, 3, 4, 5, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, 25, 27] data_rows_cool = [2, 3, 4, 6, 7, 8, 10, 12, 14] hig_temp_techs = [2, 7, 8, 13, 14, 16, 18, 20, 22] med_temp_techs = [3, 4, 5, 9, 10, 11] low_temp_techs = [24, 25] no_imput_rows_color = [232, 232, 232]
def letter_counter(token, word): count = 0 for letter in word: if letter == token: count = count + 1 else: continue return count
def letter_counter(token, word): count = 0 for letter in word: if letter == token: count = count + 1 else: continue return count
@React.command() async def redirect(ctx, *, url): await ctx.message.delete() try: embed = discord.Embed(color=int(json.load(open(f'./Themes/{json.load(open("config.json"))["theme"]}.json'))['embed_color'].replace('#', '0x'), 0), title='Redirect Checker') embed.set_thumbnail(url=json.load(open(f'...
@React.command() async def redirect(ctx, *, url): await ctx.message.delete() try: embed = discord.Embed(color=int(json.load(open(f"./Themes/{json.load(open('config.json'))['theme']}.json"))['embed_color'].replace('#', '0x'), 0), title='Redirect Checker') embed.set_thumbnail(url=json.load(open(f"...
arq_entrada = open("FORMAT.FLC", 'r') conjunto_entradas = \ {'SISTEMA FUZZY': '', 'CONJUNTO FUZZY': '', 'GRANULARIDADE': 3, 'OPERADOR COMPOSICAO': '', 'OPERADOR AGREGACAO': '', 'INFERENCIA': '', 'REGRA': False, 'DEFAULT': ''} for linha in arq_entrada.readlines(): #print(linha) variavel = linha.split(':')[0] ...
arq_entrada = open('FORMAT.FLC', 'r') conjunto_entradas = {'SISTEMA FUZZY': '', 'CONJUNTO FUZZY': '', 'GRANULARIDADE': 3, 'OPERADOR COMPOSICAO': '', 'OPERADOR AGREGACAO': '', 'INFERENCIA': '', 'REGRA': False, 'DEFAULT': ''} for linha in arq_entrada.readlines(): variavel = linha.split(':')[0] valor = linha.split...
num = 1 num = 2 num = 3 num = 4 num = 5
num = 1 num = 2 num = 3 num = 4 num = 5
class Parser: def __init__(self, file_path): self.dottedproductions = {'S\'': [['.', 'S']]} file_program = self.read_program(file_path) self.terminals = file_program[0] self.nonTerminals = file_program[1] self.productions = {} self.transactions = file_program[2:] ...
class Parser: def __init__(self, file_path): self.dottedproductions = {"S'": [['.', 'S']]} file_program = self.read_program(file_path) self.terminals = file_program[0] self.nonTerminals = file_program[1] self.productions = {} self.transactions = file_program[2:] ...
class instancemethod(object): def __init__(self, func): self._func = func def __get__(self, obj, type_=None): return lambda *args, **kwargs: self._func(obj, *args, **kwargs) class Func(object): def __init__(self): pass def __call__(self, *args, **kwargs): return self, args, kwargs class A(object): ...
class Instancemethod(object): def __init__(self, func): self._func = func def __get__(self, obj, type_=None): return lambda *args, **kwargs: self._func(obj, *args, **kwargs) class Func(object): def __init__(self): pass def __call__(self, *args, **kwargs): return (sel...
#!/usr/bin/env python # https://adventofcode.com/2020/day/1 # Topic: Report repair my_list = [] with open("../data/1.puzzle.txt") as fp: Lines = fp.readlines() for line in Lines: my_list.append(int(line)) my_list.sort() num1 = 0 num2 = 0 for idx, x in enumerate(my_list): for y in range(0, len(my_list) - id...
my_list = [] with open('../data/1.puzzle.txt') as fp: lines = fp.readlines() for line in Lines: my_list.append(int(line)) my_list.sort() num1 = 0 num2 = 0 for (idx, x) in enumerate(my_list): for y in range(0, len(my_list) - idx): if x + my_list[len(my_list) - 1 - y] == 2020: num1...
class MasterConfig: def __init__(self, args): self.IP = args.ip self.PORT = args.port self.PERSISTENCE_DIR = args.persistence_dir self.SENDER_QUEUE_LENGTH = args.sender_queue_length self.SENDER_TIMEOUT = args.sender_timeout self.UI_PORT = args.ui_port self.CPU...
class Masterconfig: def __init__(self, args): self.IP = args.ip self.PORT = args.port self.PERSISTENCE_DIR = args.persistence_dir self.SENDER_QUEUE_LENGTH = args.sender_queue_length self.SENDER_TIMEOUT = args.sender_timeout self.UI_PORT = args.ui_port self.CP...
'''knot> pytest tests ''' def test_noting(): assert True
"""knot> pytest tests """ def test_noting(): assert True
#******************************************************************** # Filename: SingletonPattern_With.Metaclass.py # Author: Javier Montenegro (https://javiermontenegro.github.io/) # Copyright: # Details: This code is the implementation of the singleton pattern. #************************************************...
class Metasingleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class Logger(metaclass=MetaSingleton): pass if __name__ == '__main__...
def junta_listas(listas): planarizada = [] for lista in listas: for e in lista: planarizada.append(e) return planarizada lista = [[1, 2, 3], [4, 5, 6], [7, 8], [9], [10]] print(junta_listas(lista))
def junta_listas(listas): planarizada = [] for lista in listas: for e in lista: planarizada.append(e) return planarizada lista = [[1, 2, 3], [4, 5, 6], [7, 8], [9], [10]] print(junta_listas(lista))
S = input() n = S.count("N") s = S.count("S") e = S.count("E") w = S.count("W") home = False if n and s: if e and w: print("Yes") elif not e and not w: print("Yes") else: print("No") elif not n and not s: if e and w: print("Yes") elif not e and not w: print...
s = input() n = S.count('N') s = S.count('S') e = S.count('E') w = S.count('W') home = False if n and s: if e and w: print('Yes') elif not e and (not w): print('Yes') else: print('No') elif not n and (not s): if e and w: print('Yes') elif not e and (not w): pr...
# lec5prob9-semordnilap.py # edX MITx 6.00.1x # Introduction to Computer Science and Programming Using Python # Lecture 5, problem 9 # A semordnilap is a word or a phrase that spells a different word when backwards # ("semordnilap" is a semordnilap of "palindromes"). Here are some examples: # # nametag / gateman # dog ...
def semordnilap(str1, str2): """ str1: a string str2: a string returns: True if str1 and str2 are semordnilap; False otherwise. """ if not (len(str1) or len(str2)): return True if not (len(str1) and len(str2)): return False if str1[0] != str2[-1]: re...
__title__ = 'fobi.contrib.plugins.form_elements.fields.' \ 'hidden_model_object.default' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = 'Copyright (c) 2014-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('IGNORED_MODELS',) IGNORED_MODELS = []
__title__ = 'fobi.contrib.plugins.form_elements.fields.hidden_model_object.default' __author__ = 'Artur Barseghyan <artur.barseghyan@gmail.com>' __copyright__ = 'Copyright (c) 2014-2017 Artur Barseghyan' __license__ = 'GPL 2.0/LGPL 2.1' __all__ = ('IGNORED_MODELS',) ignored_models = []
# Description: Sequence Built-in Methods # Sequence Methods word = 'Hello' print(len(word[1:3])) # 2 print(ord('A')) # 65 print(chr(65)) # A print(str(65)) # 65 # Looping Sequence # 1. The position index and corresponding value can be retrieved at the same time using the e...
word = 'Hello' print(len(word[1:3])) print(ord('A')) print(chr(65)) print(str(65)) for (i, v) in enumerate(['tic', 'tac', 'toe']): print(i, v) questions = ['name', 'quest', 'favorite color'] answers = ['lancelot', 'the holy grail', 'blue'] for (q, a) in zip(questions, answers): print('What is your {0}? It is {...
__author__ = "Inada Naoki <songofacandy@gmail.com>" version_info = (1,4,2,'final',0) __version__ = "1.4.2"
__author__ = 'Inada Naoki <songofacandy@gmail.com>' version_info = (1, 4, 2, 'final', 0) __version__ = '1.4.2'
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate Leakage': 0.00662954, 'Peak Dynamic': 0.0, 'Runtime Dynamic': 0.0, 'Subthres...
budget = float(input()) statists = int(input()) one_costume_price = float(input()) decor_price = 0.1 * budget costumes_price = statists * one_costume_price if statists >= 150: costumes_price -= 0.1 * costumes_price total_price = decor_price + costumes_price money_left = budget - total_price money_needed = total_...
budget = float(input()) statists = int(input()) one_costume_price = float(input()) decor_price = 0.1 * budget costumes_price = statists * one_costume_price if statists >= 150: costumes_price -= 0.1 * costumes_price total_price = decor_price + costumes_price money_left = budget - total_price money_needed = total_pri...
''' Created on Jan 19, 2016 @author: elefebvre '''
""" Created on Jan 19, 2016 @author: elefebvre """
a=int(input()) b=int(input()) if a>b:a,b=b,a for i in range(a+1,b): if i%5==2 or i%5==3:print(i)
a = int(input()) b = int(input()) if a > b: (a, b) = (b, a) for i in range(a + 1, b): if i % 5 == 2 or i % 5 == 3: print(i)
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: res = [] def backtrack(nums, temp): if not nums: res.append(temp) return for i in range(len(nums)): backtrack(nums[:i]+nums[i+1:], temp+[nums[i]]) ba...
class Solution: def permute(self, nums: List[int]) -> List[List[int]]: res = [] def backtrack(nums, temp): if not nums: res.append(temp) return for i in range(len(nums)): backtrack(nums[:i] + nums[i + 1:], temp + [nums[i]]) ...
class LibTiffPackage (Package): def __init__(self): Package.__init__(self, 'tiff', '4.0.9', configure_flags=[ ], sources=[ 'http://download.osgeo.org/libtiff/tiff-%{version}.tar.gz', ...
class Libtiffpackage(Package): def __init__(self): Package.__init__(self, 'tiff', '4.0.9', configure_flags=[], sources=['http://download.osgeo.org/libtiff/tiff-%{version}.tar.gz']) self.needs_lipo = True lib_tiff_package()
''' Encapsulation : Part 1 Encapsulation is the process of restricting access to methods and variables in a class in order to prevent direct data modification so that it prevents accidental data modification. Encapsulation basically allows the internal representation of an object to be hidden from the v...
""" Encapsulation : Part 1 Encapsulation is the process of restricting access to methods and variables in a class in order to prevent direct data modification so that it prevents accidental data modification. Encapsulation basically allows the internal representation of an object to be hidden from the v...
class UndefinedMockBehaviorError(Exception): pass class MethodWasNotCalledError(Exception): pass
class Undefinedmockbehaviorerror(Exception): pass class Methodwasnotcallederror(Exception): pass
class Solution: def decodeString(self, s: str) -> str: St = [] num = 0 curr = '' for c in s: if c.isdigit(): num = num*10 + int(c) elif c == '[': St.append([num, curr]) num = 0 curr = '' ...
class Solution: def decode_string(self, s: str) -> str: st = [] num = 0 curr = '' for c in s: if c.isdigit(): num = num * 10 + int(c) elif c == '[': St.append([num, curr]) num = 0 curr = '' ...
# Belajar default argument value #defaul name berfungsi memberikan pengisian default pada parameter #sehingga pengisian parameter bersifat opsional def say_hello(nama="aris"): #menggunakan sama dengan lalu ketik default value nya print(f"Hello {nama}!") say_hello("karachi") say_hello() #akan error jika ti...
def say_hello(nama='aris'): print(f'Hello {nama}!') say_hello('karachi') say_hello() def says_hello(nama_pertama='uchiha', nama_kedua=''): print(f'Hello {nama_pertama}-{nama_kedua}!') says_hello('muhammad', 'aris') says_hello(nama_kedua='shishui') says_hello(nama_kedua='uchiha', nama_pertama='madara') says_hel...
# getattr(object, name[, default]) class C: def A(self): pass print(getattr(C, 'A'))
class C: def a(self): pass print(getattr(C, 'A'))
# # Copyright (C) 2017 The Android Open Source Project # # 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 la...
model = model() i1 = input('op1', 'TENSOR_FLOAT32', '{1, 2, 3, 2}') i2 = input('op2', 'TENSOR_FLOAT32', '{1, 2, 3, 2}') i3 = input('op3', 'TENSOR_FLOAT32', '{1, 2, 3, 2}') axis0 = int32_scalar('axis0', 3) r = output('result', 'TENSOR_FLOAT32', '{1, 2, 3, 6}') model = model.Operation('CONCATENATION', i1, i2, i3, axis0)....
class PseudoData(dict): def __init__(self, name_func_dict, sweep): super(PseudoData, self).__init__() self.name_func_dict = name_func_dict self.sweep = sweep def __getitem__(self, key): if key in self.keys(): return dict.__getitem__(self, key) elif key in sel...
class Pseudodata(dict): def __init__(self, name_func_dict, sweep): super(PseudoData, self).__init__() self.name_func_dict = name_func_dict self.sweep = sweep def __getitem__(self, key): if key in self.keys(): return dict.__getitem__(self, key) elif key in se...
# LAB EXERCISE 05 print('Lab Exercise 05 \n') # SETUP pop_tv_shows = [ {"Title": "WandaVision", "Creator": ["Jac Schaeffer"], "Rating": 8.2, "Genre": "Action"}, {"Title": "Attack on Titan", "Creator": ["Hajime Isayama"], "Rating": 8.9, "Genre": "Animation"}, {"Title": "Bridgerton", "Creator": ["Chris Van D...
print('Lab Exercise 05 \n') pop_tv_shows = [{'Title': 'WandaVision', 'Creator': ['Jac Schaeffer'], 'Rating': 8.2, 'Genre': 'Action'}, {'Title': 'Attack on Titan', 'Creator': ['Hajime Isayama'], 'Rating': 8.9, 'Genre': 'Animation'}, {'Title': 'Bridgerton', 'Creator': ['Chris Van Dusen'], 'Rating': 7.3, 'Genre': 'Drama'}...
__author__ = 'chira' # "return" used for mathematical function composition def f(x): # x is an INPUT y = 2*x + 3 return y # y is an OUTPUT def g(x): # x is an INPUT y = pow(x,2) return y # y is an OUTPUT def h(x,y): # x and y are INPUTS z = pow(x,2) + 3*y; return z # z i...
__author__ = 'chira' def f(x): y = 2 * x + 3 return y def g(x): y = pow(x, 2) return y def h(x, y): z = pow(x, 2) + 3 * y return z output = 0 output = f(1) print('f(%d) = %d' % (1, output)) output = g(5) print('g(%d) = %d' % (5, output)) output = f(25) print('f(%d) = %d' % (25, output)) outpu...
def balancedSums(arr): if n == 1: return 'YES' sumL = 0 sumR = 0 i =0 j = n-1 while i <= j: if i ==j and sumL == sumR: return 'YES' elif sumL > sumR: sumR+=arr[j] j =j-1 else: sumL+=arr[i] i =i +1 re...
def balanced_sums(arr): if n == 1: return 'YES' sum_l = 0 sum_r = 0 i = 0 j = n - 1 while i <= j: if i == j and sumL == sumR: return 'YES' elif sumL > sumR: sum_r += arr[j] j = j - 1 else: sum_l += arr[i] ...
def perfect_square(x): if (x == 0 or x == 1): return x i = 1 result = 1 while (result <= x): i += 1 result = i * i return i - 1 x = int(input('Enter no.')) print(perfect_square(x))
def perfect_square(x): if x == 0 or x == 1: return x i = 1 result = 1 while result <= x: i += 1 result = i * i return i - 1 x = int(input('Enter no.')) print(perfect_square(x))
# Default delimiters INPUT1 = ''' pid 2 uptime 675 version 1.2.5 END pid 1 uptime 2 version 3 END ''' OUTPUT1 = '''{"pid": "2", "uptime": "675", "version": "1.2.5"} {"pid": "1", "uptime": "2", "version": "3"} ''' # --field-delim '=', --record-delim '%\n' INPUT2 = ''' a=1 b=2 c=3 % d=4 e=5 f=6 % ''' OUTPUT2 = '''{"a"...
input1 = '\npid 2\nuptime 675\nversion 1.2.5 END\npid 1\nuptime 2\nversion 3\nEND\n' output1 = '{"pid": "2", "uptime": "675", "version": "1.2.5"}\n{"pid": "1", "uptime": "2", "version": "3"}\n' input2 = '\na=1\nb=2\nc=3\n%\nd=4\ne=5\nf=6\n%\n' output2 = '{"a": "1", "b": "2", "c": "3"}\n{"d": "4", "e": "5", "f": "6"}\n'...
def capitalize(string): sttings_upper = string.title() for word in string.split(): words = word[:-1] + word[0-1].upper() + " " return sttings_upper[:-1] print(capitalize("GoLand is a new commercial IDE by JetBrains aimed at providing an ergonomic environment " "for Go developmen...
def capitalize(string): sttings_upper = string.title() for word in string.split(): words = word[:-1] + word[0 - 1].upper() + ' ' return sttings_upper[:-1] print(capitalize('GoLand is a new commercial IDE by JetBrains aimed at providing an ergonomic environment for Go development. The new IDE extends...
class Solution: def compareVersion(self, version1: str, version2: str) -> int: l1 = [int(s) for s in version1.split(".")] l2 = [int(s) for s in version2.split(".")] len1, len2 = len(l1), len(l2) if len1 > len2: l2 += [0] * (len1 - len2) elif len1 < len2: ...
class Solution: def compare_version(self, version1: str, version2: str) -> int: l1 = [int(s) for s in version1.split('.')] l2 = [int(s) for s in version2.split('.')] (len1, len2) = (len(l1), len(l2)) if len1 > len2: l2 += [0] * (len1 - len2) elif len1 < len2: ...
############# constants TITLE = "Cheese Maze" DEVELOPER = "Jack Gartner" HISTORY = "A mouse wants eat his cheese, Make it to the Hashtag to win, watch out for plus signs, $ is a teleport, P is a power up, Obtain the Key (K) in order to unlock the door (D)" INSTRUCTIONS = "left arrow key\t\t\tto move left\nright arrow k...
title = 'Cheese Maze' developer = 'Jack Gartner' history = 'A mouse wants eat his cheese, Make it to the Hashtag to win, watch out for plus signs, $ is a teleport, P is a power up, Obtain the Key (K) in order to unlock the door (D)' instructions = 'left arrow key\t\t\tto move left\nright arrow key\t\t\tto move right\nu...
score = float(input("Enter Score: ")) if score < 1 and score > 0: if score >= 0.9: print('A') elif score >= 0.8: print('B') elif score >= 0.7: print('C') elif score >= 0.6: print('D') else: print('F') else: print('Value of score is out of range.') l...
score = float(input('Enter Score: ')) if score < 1 and score > 0: if score >= 0.9: print('A') elif score >= 0.8: print('B') elif score >= 0.7: print('C') elif score >= 0.6: print('D') else: print('F') else: print('Value of score is out of range.') largest ...
''' Created on May 19, 2019 @author: ballance ''' # TODO: implement simulation-access methods # - yield # - get sim time # - ... # # The launcher will ultimately implement these methods #
""" Created on May 19, 2019 @author: ballance """
def find_even_index(arr): for index, int in enumerate(arr): left = sum_range(arr, 0, index) right = sum_range(arr, index, len(arr)) if left == right: return index return -1 def sum_range(arr, a, b): return sum(arr[a:b + 1])
def find_even_index(arr): for (index, int) in enumerate(arr): left = sum_range(arr, 0, index) right = sum_range(arr, index, len(arr)) if left == right: return index return -1 def sum_range(arr, a, b): return sum(arr[a:b + 1])
INSTALLED_APPS = ( "testapp", ) DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } SECRET_KEY = "django_tests_secret_key"
installed_apps = ('testapp',) databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}} secret_key = 'django_tests_secret_key'
# Databricks notebook source # MAGIC %md # Run transform # MAGIC this will load the schema, the raw txt tables, then transform the dataframes to structured dataframes. # COMMAND ---------- # MAGIC %run ./transform # COMMAND ---------- # MAGIC %md # Store # MAGIC write the transformed dataframes to our base-path # ...
for table in df_openalex_c: target = f'{base_path}parquet/{table}' if table in partition_sizes: partitions = partition_sizes[table] else: partitions = partition_sizes['default'] if file_exists(target): print(f'{target} already exists, skip') else: print(f'writing {tar...
# Ex4. # # Create a program that is going to take a whole number as an input, and will calculate the factorial of the number. # # Factorial example: 5! = 5 * 4 * 3 * 2 * 1 = 120 factorial = 1 number = int(input('Enter a number: ')) for i in range(1, number+1): factorial *= i print(f'Factorial of {number} is {facto...
factorial = 1 number = int(input('Enter a number: ')) for i in range(1, number + 1): factorial *= i print(f'Factorial of {number} is {factorial}')
def read_lines_of_file(filename): with open(filename) as f: content = f.readlines() return content,len(content) alltext,alltextlen = read_lines_of_file('read.txt') for line in alltext: print(line.rstrip()) print("Number of lines read from file --> %d" %(alltextlen))
def read_lines_of_file(filename): with open(filename) as f: content = f.readlines() return (content, len(content)) (alltext, alltextlen) = read_lines_of_file('read.txt') for line in alltext: print(line.rstrip()) print('Number of lines read from file --> %d' % alltextlen)
class Authenticator(): def validate(self, username, password): raise NotImplementedError() # pragma: no cover def verify(self, username): raise NotImplementedError() # pragma: no cover def get_password(self, username): raise NotImplementedError() # pragma: no cover
class Authenticator: def validate(self, username, password): raise not_implemented_error() def verify(self, username): raise not_implemented_error() def get_password(self, username): raise not_implemented_error()
#!/usr/local/bin/python3 class Generator(): def __init__(self, init, factor, modulo, multiple): self.value = init self.factor = factor self.modulo = modulo self.multiple = multiple def getNext(self): self.value = (self.value * self.factor) % self.modulo while (s...
class Generator: def __init__(self, init, factor, modulo, multiple): self.value = init self.factor = factor self.modulo = modulo self.multiple = multiple def get_next(self): self.value = self.value * self.factor % self.modulo while self.value % self.multiple != ...
price = 1000000 good_credit = True high_income = True if good_credit and high_income: down_payment = 1.0 * price print(f"eligible for loan") else: down_payment = 2.0 * price print(f"ineligible for loan") print(f"down payment is {down_payment}")
price = 1000000 good_credit = True high_income = True if good_credit and high_income: down_payment = 1.0 * price print(f'eligible for loan') else: down_payment = 2.0 * price print(f'ineligible for loan') print(f'down payment is {down_payment}')
# Constants shared between C++ code and python # TODO: Share properly via a configuration file # ControllerWithSimpleHistory::EvaluationPeriod EVALUATION_PERIOD_SEQUENCES = 64 # kWorkWindowSize in SysConsts.hpp STATE_TRANSFER_WINDOW = 300
evaluation_period_sequences = 64 state_transfer_window = 300
# Python program to print # ASCII Value of Character # In c we can assign different # characters of which we want ASCII value c = 'g' # print the ASCII value of assigned character in c print("The ASCII value of '" + c + "' is", ord(c))
c = 'g' print("The ASCII value of '" + c + "' is", ord(c))
def find(tree, key, value): items = tree.get("children", []) if isinstance(tree, dict) else tree for item in items: if item[key] == value: yield item else: yield from find(item, key, value) def find_path(tree, key, value, path=()): items = tree.get("children", []) i...
def find(tree, key, value): items = tree.get('children', []) if isinstance(tree, dict) else tree for item in items: if item[key] == value: yield item else: yield from find(item, key, value) def find_path(tree, key, value, path=()): items = tree.get('children', []) if...
''' Problem: 13 Reasons Why Given 3 integers A, B, C. Do the following steps- Swap A and B. Multiply A by C. Add C to B. Output new values of A and B. ''' # When ran, you will see a blank line, as that is needed for the submission. # If you are debugging and want it to be easier, change it too # input ...
""" Problem: 13 Reasons Why Given 3 integers A, B, C. Do the following steps- Swap A and B. Multiply A by C. Add C to B. Output new values of A and B. """ input = input() input_list = input.split(' ') a = int(inputList[1]) b = int(inputList[0]) c = int(inputList[2]) a = A * C b = C + B a = str(A) b = st...
class Solution: def maxIncreaseKeepingSkyline(self, grid): skyline = [] for v_line in grid: skyline.append([max(v_line)] * len(grid)) for x, h_line in enumerate(list(zip(*grid))): max_h = max(h_line) for y in range(len(skyline)): skyline[...
class Solution: def max_increase_keeping_skyline(self, grid): skyline = [] for v_line in grid: skyline.append([max(v_line)] * len(grid)) for (x, h_line) in enumerate(list(zip(*grid))): max_h = max(h_line) for y in range(len(skyline)): skyl...
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: output = [[]] result = [] for num in sorted(nums): res = [lst + [num] for lst in output] output += res for subset in output: if subset not in result: ...
class Solution: def subsets_with_dup(self, nums: List[int]) -> List[List[int]]: output = [[]] result = [] for num in sorted(nums): res = [lst + [num] for lst in output] output += res for subset in output: if subset not in result: r...
with open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/general_form_ocr.txt') as f: text = f.readlines() f2 = open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/dlo_address.txt', 'w+') # data = list(set(text)) # data.sort() # # count2 = 0 # count = {e: 0 for e in data} # count2 = 0 for e in text: ...
with open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/general_form_ocr.txt') as f: text = f.readlines() f2 = open('/home/ai/hdd/tupm/projects/textGenOCR/trdg/dicts/dlo_address.txt', 'w+') for e in text: e = e.strip() length = len(e) if length > 25: f2.write(f'{e[:length // 2]}\n') ...
def foo(): ''' >>> class bad(): ... pass ''' pass
def foo(): """ >>> class bad(): ... pass """ pass
class InstanceObjectManager: def __init__(self, parent): self.parent = parent # All Instance Id's of instanced objects on this server. self.localInstanceIds = set() # Dict of {Temp Id: Instance Object} self.tempId2iObject = {} # Dict of {Instance Id: Instance Object} self.instanceId2iObject = {} #...
class Instanceobjectmanager: def __init__(self, parent): self.parent = parent self.localInstanceIds = set() self.tempId2iObject = {} self.instanceId2iObject = {} self.locationDict = {} def store_temp_object(self, tempId, iObject): if tempId in self.tempId2iObjec...
def append(list1, list2): pass def concat(lists): pass def filter(function, list): pass def length(list): pass def map(function, list): pass def foldl(function, list, initial): pass def foldr(function, list, initial): pass def reverse(list): pass
def append(list1, list2): pass def concat(lists): pass def filter(function, list): pass def length(list): pass def map(function, list): pass def foldl(function, list, initial): pass def foldr(function, list, initial): pass def reverse(list): pass
class Solution: def rob(self, nums: List[int]) -> int: def dp(i: int) -> int: if i == 0: return nums[0] if i == 1: return max(nums[0], nums[1]) if i not in memo: memo[i] = max(dp(i-1), nums[i]+dp(i-2)) return mem...
class Solution: def rob(self, nums: List[int]) -> int: def dp(i: int) -> int: if i == 0: return nums[0] if i == 1: return max(nums[0], nums[1]) if i not in memo: memo[i] = max(dp(i - 1), nums[i] + dp(i - 2)) re...
#!/usr/bin/env python3 ############################################################################### # Copyright 2018 The Apollo Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy...
def segment_overlap(a, b, x, y): if b < x or a > y: return False return True def vector_projection_overlap(p0, p1, p2, p3): v = p1.subtract(p0) n_square = v.norm_square() v0 = p2.subtract(p0) v1 = p3.subtract(p0) t0 = v0.dot(v) t1 = v1.dot(v) if t0 > t1: t = t0 ...
class Matrix: def transpose(self, matrix): return list(zip(*matrix)) def column(self, matrix, i): return [row[i] for row in matrix]
class Matrix: def transpose(self, matrix): return list(zip(*matrix)) def column(self, matrix, i): return [row[i] for row in matrix]
def create_histo_table(dataname, dimPerfMap, lines, histoLambda, meanLambda, subsectitle, header): colPairs = len(dimPerfMap) colspecs = '|c|c|' * colPairs lines.append("\\begin{table}[H]") lines.append("\centering") lines.append("\caption{%s: %s}" % (subsectitle, header)) lines.append("\\begin{adjustbox}{wid...
def create_histo_table(dataname, dimPerfMap, lines, histoLambda, meanLambda, subsectitle, header): col_pairs = len(dimPerfMap) colspecs = '|c|c|' * colPairs lines.append('\\begin{table}[H]') lines.append('\\centering') lines.append('\\caption{%s: %s}' % (subsectitle, header)) lines.append('\\beg...
example_schema_array = {"type": "array", "items": {"type": "string"}} example_array = ["string"] example_schema_integer = {"type": "integer", "minimum": 3, "maximum": 5} example_integer = 3 example_schema_number = {"type": "number", "minimum": 3, "maximum": 5} example_number = 3.2 example_schema_object = {"type": "obje...
example_schema_array = {'type': 'array', 'items': {'type': 'string'}} example_array = ['string'] example_schema_integer = {'type': 'integer', 'minimum': 3, 'maximum': 5} example_integer = 3 example_schema_number = {'type': 'number', 'minimum': 3, 'maximum': 5} example_number = 3.2 example_schema_object = {'type': 'obje...
# region headers # escript-template v20190611 / stephane.bourdeaud@nutanix.com # * author: MITU Bogdan Nicolae (EEAS-EXT) <Bogdan-Nicolae.MITU@ext.eeas.europa.eu> # * stephane.bourdeaud@emeagso.lab # * version: 2019/09/18 # task_name: CalmSetProjectOwner # description: Given a Calm project UUID, ...
username = '@@{pc.username}@@' username_secret = '@@{pc.secret}@@' api_server = '@@{pc_ip}@@' nutanix_calm_user_uuid = '@@{nutanix_calm_user_uuid}@@' nutanix_calm_user_upn = '@@{calm_username}@@' project_uuid = '@@{project_uuid}@@' api_server_port = '9440' api_server_endpoint = '/api/nutanix/v3/projects_internal/{}'.fo...
class TCPControlFlags(): def __init__(self): '''Control Bits govern the entire process of connection establishment, data transmissions and connection termination. The control bits are listed as follows, they are''' '''It indicates if we need to use Urgent pointer field or not. If it is set to 1 th...
class Tcpcontrolflags: def __init__(self): """Control Bits govern the entire process of connection establishment, data transmissions and connection termination. The control bits are listed as follows, they are""" 'It indicates if we need to use Urgent pointer field or not. If it is set to 1 then on...