content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def test_accounts(client): client.session.get.return_value.json.return_value.update({'accounts': [1, ]}) client.accounts() client.session.get.called_once_with('https://api.getdrip.com/v2/accounts/') def test_account(client): client.session.get.return_value.json.return_value.update({'accounts': [1, ]...
def test_accounts(client): client.session.get.return_value.json.return_value.update({'accounts': [1]}) client.accounts() client.session.get.called_once_with('https://api.getdrip.com/v2/accounts/') def test_account(client): client.session.get.return_value.json.return_value.update({'accounts': [1]}) ...
""" for image in os.listdir(images_path): img = Image.open(os.path.join(images_path,image)) frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) for landmark in landmarks_points: print(landmark) ...
""" for image in os.listdir(images_path): img = Image.open(os.path.join(images_path,image)) frame_draw = img.copy() draw = ImageDraw.Draw(frame_draw) for box in boxes: draw.rectangle(box.tolist(), outline=(255, 0, 0), width=6) for landmark in landmarks_points: print(landmark) ...
# model model = Model() i1 = Input("op1", "TENSOR_INT32", "{1, 2, 2, 1}") i2 = Output("op2", "TENSOR_INT32", "{1, 2, 2, 1}") model = model.Operation("ZEROS_LIKE_EX", i1).To(i2) # Example 1. Input in operand 0, input0 = {i1: # input 0 [-2, -1, 0, 3]} output0 = {i2: # output 0 [0, 0, 0, 0]} # Inst...
model = model() i1 = input('op1', 'TENSOR_INT32', '{1, 2, 2, 1}') i2 = output('op2', 'TENSOR_INT32', '{1, 2, 2, 1}') model = model.Operation('ZEROS_LIKE_EX', i1).To(i2) input0 = {i1: [-2, -1, 0, 3]} output0 = {i2: [0, 0, 0, 0]} example((input0, output0))
# -*- coding: utf-8 -*- """ Global Configuration """ mssql = { 'server' : 'localhost\SQL2016', 'database' : 'bkrob', 'username' : 'bkrob_adm', 'password' : 'bkrob_adm' } google_geocode_api = 'api key'
""" Global Configuration """ mssql = {'server': 'localhost\\SQL2016', 'database': 'bkrob', 'username': 'bkrob_adm', 'password': 'bkrob_adm'} google_geocode_api = 'api key'
def hello(): # Hey i'm a comment # I am a helpful note for humans, and will not be ran pass if __name__ == '__main__': hello()
def hello(): pass if __name__ == '__main__': hello()
# Prob 2 # Create a small program that will: # Ask for user input # Count the number of vowels in the user text ('a', 'e', 'i', 'o', 'u', 'y') # Display the number of vowels in user text print("Please enter a string") my_string = input() vowels = ['a', 'e', 'i', 'o', 'u', 'y'] count = 0 for letter in my_string.lower()...
print('Please enter a string') my_string = input() vowels = ['a', 'e', 'i', 'o', 'u', 'y'] count = 0 for letter in my_string.lower(): if letter in vowels: count += 1 print('Number of vowels in string: ' + str(count)) print('Please enter a Gmail email') email = input() print(email[-10:] == '@gmail.com')
def my_func(arr1, arr2, arr3): ln1 = len(arr1) ln2 = len(arr2) ln3 = len(arr3) ptr1 = 0 ptr2 = 0 ptr3 = 0 while ptr1 < ln1 and ptr2 < ln2 and ptr3 < ln3: if arr1[ptr1] < arr2[ptr2]: if arr3[ptr3] < arr2[ptr2]: arr1[ptr1] = -1 arr3[ptr3...
def my_func(arr1, arr2, arr3): ln1 = len(arr1) ln2 = len(arr2) ln3 = len(arr3) ptr1 = 0 ptr2 = 0 ptr3 = 0 while ptr1 < ln1 and ptr2 < ln2 and (ptr3 < ln3): if arr1[ptr1] < arr2[ptr2]: if arr3[ptr3] < arr2[ptr2]: arr1[ptr1] = -1 arr3[ptr3] =...
# # PySNMP MIB module RAPTOR-SNMPv1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RAPTOR-SNMPv1-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:43:39 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Ma...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_intersection, value_size_constraint, constraints_union, value_range_constraint) ...
class AppNotFoundError(Exception): pass class ClassNotFoundError(Exception): pass
class Appnotfounderror(Exception): pass class Classnotfounderror(Exception): pass
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 29 10:26:43 2020 @author: fa19 """
""" Created on Sun Nov 29 10:26:43 2020 @author: fa19 """
class FilterDoesNotExistError(Exception): """ Raised when a filter does not exist. """ pass class APIError(Exception): """ Error returned by the API. """ pass class ValidationError(Exception): """ Raised when filters receive invalid data """ pass
class Filterdoesnotexisterror(Exception): """ Raised when a filter does not exist. """ pass class Apierror(Exception): """ Error returned by the API. """ pass class Validationerror(Exception): """ Raised when filters receive invalid data """ pass
#!/usr/bin/env python3 """ Boolean data 1 bit 0,1 """ def encode(value): return [int(value) & 0x01] def decode(data): return (data & 0x01)
""" Boolean data 1 bit 0,1 """ def encode(value): return [int(value) & 1] def decode(data): return data & 1
#!/usr/bin/env python3 # fileencoding=utf-8 def char_width(char): # For japanese. if len(char) == 1: return 1 else: return 2 def string_width(_string): char_width_list = [] for c in _string.decode('utf-8'): char_width_list.append(char_width(c)) return char_width_list d...
def char_width(char): if len(char) == 1: return 1 else: return 2 def string_width(_string): char_width_list = [] for c in _string.decode('utf-8'): char_width_list.append(char_width(c)) return char_width_list def add_space(_string, num): return _string + ' ' * num def c...
x = "Hello" y = 15 print(bool(x)) print(bool(y))
x = 'Hello' y = 15 print(bool(x)) print(bool(y))
class Solution: def findMedianSortedArrarys(self, A, B): lengthA = len(A) lengthB = len(B) new_arr = [] i = j = 0 while i < lengthA and j < lengthB: if A[i] < B[j]: new_arr.append(A[i]) i += 1 else: new_...
class Solution: def find_median_sorted_arrarys(self, A, B): length_a = len(A) length_b = len(B) new_arr = [] i = j = 0 while i < lengthA and j < lengthB: if A[i] < B[j]: new_arr.append(A[i]) i += 1 else: ...
#!/usr/bin/env python3 count = 0 with open("romeo.txt") as romeo: text = romeo.readlines() for line in text: if "ROMEO" in line: count += 1 print(count)
count = 0 with open('romeo.txt') as romeo: text = romeo.readlines() for line in text: if 'ROMEO' in line: count += 1 print(count)
# 22004 | Fixing the Fence (Evan intro) sm.setSpeakerID(1013103) sm.sendNext("Ah, did you bring all the Thick Branches? That's my kid! What shall i give you as reward?... Let's see... Oh, right! \r\n #fUI/UIWindow2.img/QuestIcon/4/0# \r\n #v3010097# Strong Wooden Chair \r\n #fUI/UIWindow2.img/QuestIcon/8/0# 210 exp")...
sm.setSpeakerID(1013103) sm.sendNext("Ah, did you bring all the Thick Branches? That's my kid! What shall i give you as reward?... Let's see... Oh, right! \r\n #fUI/UIWindow2.img/QuestIcon/4/0# \r\n #v3010097# Strong Wooden Chair \r\n #fUI/UIWindow2.img/QuestIcon/8/0# 210 exp") if sm.canHold(3010097): sm.giveItem(3...
# Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def levelOrder(self, A): queue = [] ansr_queue = [] queue.append(A) marker = "$" queue.append(marker) ...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def level_order(self, A): queue = [] ansr_queue = [] queue.append(A) marker = '$' queue.append(marker) row = [] while len(queu...
""" SPI typing class This class includes full support for using ESP32 SPI peripheral in master mode Only SPI master mode is supported for now. Python exception wil be raised if the requested spihost is used by SD Card driver (sdcard in spi mode). If the requested spihost is VSPI and the psRAM is used at 80 MHz, the ...
""" SPI typing class This class includes full support for using ESP32 SPI peripheral in master mode Only SPI master mode is supported for now. Python exception wil be raised if the requested spihost is used by SD Card driver (sdcard in spi mode). If the requested spihost is VSPI and the psRAM is used at 80 MHz, the ...
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ # using library # itertools.permutations(nums) - tuples on iterating # return list(map(list, itertools.permutations(nums))) # recursive # i...
class Solution: def permute(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ result = [[]] for n in nums: new_permutations = [] for permutation in result: for i in range(len(permutation) + 1): ...
class Solution: def numberOfWays(self, numPeople: int) -> int: kMod = int(1e9) + 7 # dp[i] := # of ways i handshakes pair w//o crossing dp = [1] + [0] * (numPeople // 2) for i in range(1, numPeople // 2 + 1): for j in range(i): dp[i] += dp[j] * dp[i - 1 - j] dp[i] %= kMod r...
class Solution: def number_of_ways(self, numPeople: int) -> int: k_mod = int(1000000000.0) + 7 dp = [1] + [0] * (numPeople // 2) for i in range(1, numPeople // 2 + 1): for j in range(i): dp[i] += dp[j] * dp[i - 1 - j] dp[i] %= kMod return ...
# Language: Python 3 n = int(input()) if (n % 2 != 0): print("Weird") elif (2 <= n <= 5): print("Not Weird") elif (6 <= n <= 20): print("Weird") else: print("Not Weird")
n = int(input()) if n % 2 != 0: print('Weird') elif 2 <= n <= 5: print('Not Weird') elif 6 <= n <= 20: print('Weird') else: print('Not Weird')
bot_token = "" bot_token_dev = "" db_url = "" mod_db_url = "" cloudflare_email = "" cloudflare_token = "" error_webhook_token = "" error_webhook_id = 0 consumer_key = "" consumer_secret_key = "" access_token = "" access_token_secret = ""
bot_token = '' bot_token_dev = '' db_url = '' mod_db_url = '' cloudflare_email = '' cloudflare_token = '' error_webhook_token = '' error_webhook_id = 0 consumer_key = '' consumer_secret_key = '' access_token = '' access_token_secret = ''
# map function #iterable as list or array #function as def or lambda #map(function,iterable) or numbers=[1,2,3,4,5,6] #example def Sqrt(number): return number**2 a=list(map(Sqrt,numbers)) print(a) #example b=list(map(lambda number:number**3,numbers)) print(b) #map(str,int,double variable as ...
numbers = [1, 2, 3, 4, 5, 6] def sqrt(number): return number ** 2 a = list(map(Sqrt, numbers)) print(a) b = list(map(lambda number: number ** 3, numbers)) print(b) str_numbers = ['1', '2', '3', '4', '5', '6'] c = list(map(int, str_numbers)) print(c)
# # PySNMP MIB module ChrTrap-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrTrap-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:36:20 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, 0...
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_union, constraints_intersection) ...
# Time: 218 ms # Memory: 4 KB for i in range(5): m = list(map(int, input().split())) if 1 in m: r, c = (m.index(1)), (i) sol = abs(r - 2) + abs(2 - c) print(sol)
for i in range(5): m = list(map(int, input().split())) if 1 in m: (r, c) = (m.index(1), i) sol = abs(r - 2) + abs(2 - c) print(sol)
nama = "azmi" umur_5_tahun_lalu = 23 print ("nama saya") print(nama) print("sedangkan umur saat ini adalah") print(umur_5_tahun_lalu + 5) if (nama == "nathan") : print("selamat datang Nathan!") elif (nama == "azmi") : print("selamat datang Azmi!") else : print("Selamat datang pak") print(nama)
nama = 'azmi' umur_5_tahun_lalu = 23 print('nama saya') print(nama) print('sedangkan umur saat ini adalah') print(umur_5_tahun_lalu + 5) if nama == 'nathan': print('selamat datang Nathan!') elif nama == 'azmi': print('selamat datang Azmi!') else: print('Selamat datang pak') print(nama)
def exact_cover(X, Y): X = {j: set() for j in X} for i, row in Y.items(): for j in row: X[j].add(i) return X, Y def select(X, Y, r): cols = [] for j in Y[r]: for i in X[j]: for k in Y[i]: if k != j: X[k].re...
def exact_cover(X, Y): x = {j: set() for j in X} for (i, row) in Y.items(): for j in row: X[j].add(i) return (X, Y) def select(X, Y, r): cols = [] for j in Y[r]: for i in X[j]: for k in Y[i]: if k != j: X[k].remove(i) ...
class Node(object): '''Binary Tree Node''' def __init__(self, data): self.data = data self.left = None self.right = None class BinaryTree(object): '''Building binary Tree''' def __init__(self, data): self.root = Node(data) def addLeft(self, data): if self...
class Node(object): """Binary Tree Node""" def __init__(self, data): self.data = data self.left = None self.right = None class Binarytree(object): """Building binary Tree""" def __init__(self, data): self.root = node(data) def add_left(self, data): if self...
def is_k_anonymous(df, partition, sensitive_column, k=3): """ :param df: The dataframe on which to check the partition. :param partition: The partition of the dataframe to check. :param sensitive_column: The name of the sensitive column :param k: The desired k ...
def is_k_anonymous(df, partition, sensitive_column, k=3): """ :param df: The dataframe on which to check the partition. :param partition: The partition of the dataframe to check. :param sensitive_column: The name of the sensitive column :param k: The desired k ...
YELLOW = (255, 255, 0) CYAN = (0, 255, 255) RED = (255, 0, 0)
yellow = (255, 255, 0) cyan = (0, 255, 255) red = (255, 0, 0)
# this is a python file created in jupyter notbook def list_fruits(fruits=[]): for fruit in fruits: print(fruit) fruits = ['apple','kiwi','banana'] list_fruit(fruits)
def list_fruits(fruits=[]): for fruit in fruits: print(fruit) fruits = ['apple', 'kiwi', 'banana'] list_fruit(fruits)
lst = [['Harry', 37.21],['Berry', 37.21],['Tina', 37.2],['Akriti', 41],['Harsh', 39]] second_highest = sorted(list(set([marks for name, marks in lst])))[1] print('\n'.join([a for a,b in sorted(lst) if b == second_highest]))
lst = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], ['Akriti', 41], ['Harsh', 39]] second_highest = sorted(list(set([marks for (name, marks) in lst])))[1] print('\n'.join([a for (a, b) in sorted(lst) if b == second_highest]))
_menu_name = "Networking" _ordering = [ "wpa_cli", "network", "nmap", "upnp"]
_menu_name = 'Networking' _ordering = ['wpa_cli', 'network', 'nmap', 'upnp']
i = 0 while True: n, q = map(int, input().split()) if n == 0 and q == 0: break marble_numbers = [] while n>0: n -= 1 num = int(input()) marble_numbers.append(num) marble_numbers.sort() i += 1 print(f"CASE# {i}:") while q > 0: q ...
i = 0 while True: (n, q) = map(int, input().split()) if n == 0 and q == 0: break marble_numbers = [] while n > 0: n -= 1 num = int(input()) marble_numbers.append(num) marble_numbers.sort() i += 1 print(f'CASE# {i}:') while q > 0: q -= 1 qy ...
class Board: ''' A 3x3 board for TicTacToe ''' __board = '' __print_board = '' def __init__(self): self.__board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] self.make_printable() def __str__(self): self.make_printable() return self.__print_board ...
class Board: """ A 3x3 board for TicTacToe """ __board = '' __print_board = '' def __init__(self): self.__board = [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']] self.make_printable() def __str__(self): self.make_printable() return self.__print_board ...
#TempConvert_loop.py for i in range(3): val = input("Input the temp:(32C)") if val[-1] in ['C','c']: f = 1.8 * float(val[0:-1]) + 32 print("Converted temp is: %.2fF"%f) elif val[-1] in ['F','f']: c = (float(val[0:-1]) - 32) / 1.8 print("Converted temp is: %.2fC"%c) else: print("Wrong input")
for i in range(3): val = input('Input the temp:(32C)') if val[-1] in ['C', 'c']: f = 1.8 * float(val[0:-1]) + 32 print('Converted temp is: %.2fF' % f) elif val[-1] in ['F', 'f']: c = (float(val[0:-1]) - 32) / 1.8 print('Converted temp is: %.2fC' % c) else: print('...
CLASSIFIER_SCALE = 1.1 CLASSIFIER_NEIGHBORS = 5 CLASSIFIER_MIN_SZ = (50, 50) MIN_SAMPLES_PER_USER = 50 FACE_BOX_COLOR = (255, 0, 255) FACE_TXT_COLOR = (115, 249, 255) LBP_RADIUS = 2 LBP_NEIGHBORS = 16 LBP_GRID_X = 8 LBP_GRID_Y = 8 KNOWN_USER_FILE = 'users.lst' LBPH_MACHINE_LEARNING_FILE = 'lbph_face_recognizer.yam...
classifier_scale = 1.1 classifier_neighbors = 5 classifier_min_sz = (50, 50) min_samples_per_user = 50 face_box_color = (255, 0, 255) face_txt_color = (115, 249, 255) lbp_radius = 2 lbp_neighbors = 16 lbp_grid_x = 8 lbp_grid_y = 8 known_user_file = 'users.lst' lbph_machine_learning_file = 'lbph_face_recognizer.yaml' he...
potencia = int(input()) tempo = int(input()) qw = potencia / 1000 hr = tempo / 60 kwh = hr * qw print('{:.1f} kWh'.format(kwh))
potencia = int(input()) tempo = int(input()) qw = potencia / 1000 hr = tempo / 60 kwh = hr * qw print('{:.1f} kWh'.format(kwh))
n = 60 for i in range(10000): 2 ** n
n = 60 for i in range(10000): 2 ** n
"""Script to fix indentation of given ``.po`` files.""" __author__ = """Julien Palard""" __email__ = "julien@palard.fr" __version__ = "1.0.0"
"""Script to fix indentation of given ``.po`` files.""" __author__ = 'Julien Palard' __email__ = 'julien@palard.fr' __version__ = '1.0.0'
class Solution(object): def XXX(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [1]*n dp = [dp]*m for i in range(m): for j in range(n): if i!=0 and j!=0: dp[i][j] = dp[i-1][j] + dp[i][j-1]...
class Solution(object): def xxx(self, m, n): """ :type m: int :type n: int :rtype: int """ dp = [1] * n dp = [dp] * m for i in range(m): for j in range(n): if i != 0 and j != 0: dp[i][j] = dp[i - 1][j] +...
# ................................................................................................................. level_dict["bombs"] = { "scheme": "red_scheme", "size": (9,9,9), "intro": "bombs", "help": ...
level_dict['bombs'] = {'scheme': 'red_scheme', 'size': (9, 9, 9), 'intro': 'bombs', 'help': ('$scale(1.5)mission:\nget to the exit!\n\n' + 'to get to the exit,\nuse the bombs',), 'player': {'position': (0, -4, 0)}, 'exits': [{'name': 'exit', 'active': 1, 'position': (0, 2, 0)}], 'create': '\nworld.addObjectAtPos (KikiB...
class BaseDecoder(object): def __init__(self, name="BaseDecoder"): self.name = name print(name) def decode(self, **kwargs): """ Using for greedy decoding for a given input, may corresponding with gold target, return the log_probability of decoder steps. """ ...
class Basedecoder(object): def __init__(self, name='BaseDecoder'): self.name = name print(name) def decode(self, **kwargs): """ Using for greedy decoding for a given input, may corresponding with gold target, return the log_probability of decoder steps. """ ...
class Calculator: def __init__(self, socket): self.socket = socket def run(self): self.socket.emit('response', 'Here is your result')
class Calculator: def __init__(self, socket): self.socket = socket def run(self): self.socket.emit('response', 'Here is your result')
#import sys def interpret_bf_code(bf_code, memory_size = 30000): ''' (str, (int)) -> str This function interprets code in the BrainFuck language, which is passed in via bf_code parameter and returns the output of executing that code. If so specified in BrainFuck code, the function reads input ...
def interpret_bf_code(bf_code, memory_size=30000): """ (str, (int)) -> str This function interprets code in the BrainFuck language, which is passed in via bf_code parameter and returns the output of executing that code. If so specified in BrainFuck code, the function reads input from user. ...
# flatten 2D arrays into a single array A = [[1, 2, 3], [4], [5, 6]] # iterative version def flatten_iterative(A): result = [] for array in A: for element in array: result.append(element) return result print(flatten_iterative(A)) # recursively traverse 2 dimensional list out of order...
a = [[1, 2, 3], [4], [5, 6]] def flatten_iterative(A): result = [] for array in A: for element in array: result.append(element) return result print(flatten_iterative(A)) def traverse_list(A): result = [] def traverse_list_rec(A, i, j): if i >= len(A) or j >= len(A[i]):...
# This class provides a way to drive a robot which has a drive train equipped # with separate motors powering the left and right sides of a robot. # Two different drive methods exist: # Arcade Drive: combines 2-axes of a joystick to control steering and driving speed. # Tank Drive: uses two joysticks to control mot...
responsiveness = 60 min = 4000 center = 6000 max = 8000 class Simpleservo: def __init__(self, maestro, channel): self.maestro = maestro self.channel = channel self.maestro.setAccel(self.channel, 0) self.maestro.setSpeed(self.channel, RESPONSIVENESS) self.min = MIN s...
""" ------------------------------------------------------------------------------- G E N E R A L I N F O R M A T I O N ------------------------------------------------------------------------------- This file contains general constants and information about the variables saved in the netCDF file needed for plotge...
""" ------------------------------------------------------------------------------- G E N E R A L I N F O R M A T I O N ------------------------------------------------------------------------------- This file contains general constants and information about the variables saved in the netCDF file needed for plotge...
if __name__ == '__main__': l = input().strip().split() data = [int(i) for i in l] n = int(input()) sum = [0 for i in range(0, len(data)+1)] sum[0] = data[0] for i in range(1, len(data)): sum[i] = sum[i-1] + data[i] # print(sum) found = False for length in range(0, len(data...
if __name__ == '__main__': l = input().strip().split() data = [int(i) for i in l] n = int(input()) sum = [0 for i in range(0, len(data) + 1)] sum[0] = data[0] for i in range(1, len(data)): sum[i] = sum[i - 1] + data[i] found = False for length in range(0, len(data)): for ...
i = 1 while True: inp = input() if inp == "Hajj": inp = "Hajj-e-Akbar" elif inp == "Umrah": inp = "Hajj-e-Asghar" else: break print("Case {}: {}".format(i, inp)) i += 1
i = 1 while True: inp = input() if inp == 'Hajj': inp = 'Hajj-e-Akbar' elif inp == 'Umrah': inp = 'Hajj-e-Asghar' else: break print('Case {}: {}'.format(i, inp)) i += 1
class Report: def __init__(self, report): self.report = report @property def name(self): return self.report['name'] @property def filename(self): return self.report['filename'] @property def klass(self): return self.report['class'] @property def s...
class Report: def __init__(self, report): self.report = report @property def name(self): return self.report['name'] @property def filename(self): return self.report['filename'] @property def klass(self): return self.report['class'] @property def s...
def main_menu(): input_map = {'1': 'compute', '2': 'storage', '3': 'default', '4': 'exit'} print('\nSelect from the options below:') print(' 1. Set up or remove a compute service') print(' 2. Set up or remove a storage service') print(' 3. Change settings for compute or storage service (i.e. de...
def main_menu(): input_map = {'1': 'compute', '2': 'storage', '3': 'default', '4': 'exit'} print('\nSelect from the options below:') print(' 1. Set up or remove a compute service') print(' 2. Set up or remove a storage service') print(' 3. Change settings for compute or storage service (i.e. defa...
class Request: pass class DirectoryInfoRequest(Request): def __init__(self, path): super().__init__() self.path = path class AdditionalEntryPropertiesRequest(Request): def __init__(self, filepath): super().__init__() self.filepath = filepath
class Request: pass class Directoryinforequest(Request): def __init__(self, path): super().__init__() self.path = path class Additionalentrypropertiesrequest(Request): def __init__(self, filepath): super().__init__() self.filepath = filepath
######################## #######lecture 15####### ######################## class Node: def __init__(self , value=None): self.value = value self.next = None # def __str__(self): # return str(self.value) class Stack: def __init__(self , node=None): self.top = node ...
class Node: def __init__(self, value=None): self.value = value self.next = None class Stack: def __init__(self, node=None): self.top = node def __str__(self): if self.top == None: return 'Stack is empty' else: output = '' while ...
version_info = (0, 0, '6a1') __version__ = '.'.join(map(str, version_info)) if __name__ == '__main__': print(__version__)
version_info = (0, 0, '6a1') __version__ = '.'.join(map(str, version_info)) if __name__ == '__main__': print(__version__)
# Python equivalent of an array is a list def reverse_array(a_list): """ https://www.hackerrank.com/challenges/01_arrays-ds/problem We can reverse an array by simply providing the step value in list slice parameters -1 means go backwards one by one """ return a_list[::-1]
def reverse_array(a_list): """ https://www.hackerrank.com/challenges/01_arrays-ds/problem We can reverse an array by simply providing the step value in list slice parameters -1 means go backwards one by one """ return a_list[::-1]
#!/usr/local/bin/python3 try: arquivo = open('pessoas.csv') for it in arquivo: print('Nome {}, Idade {}'.format(*it.strip().split(','))) finally: arquivo.close()
try: arquivo = open('pessoas.csv') for it in arquivo: print('Nome {}, Idade {}'.format(*it.strip().split(','))) finally: arquivo.close()
@authenticated def delete(self): model = self.db.query([model_name]).filter([delete_filter]).first() self.db.delete(model) self.db.commit() return JsonResponse(self, '000')
@authenticated def delete(self): model = self.db.query([model_name]).filter([delete_filter]).first() self.db.delete(model) self.db.commit() return json_response(self, '000')
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def longestZigZag(self, root: Tre...
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def longest_zig_zag(self, root: TreeNode) -> int: self.result = 0 self.dfs(root) return self.result def dfs(self, root): if root == None: ...
def equal_slices(total, num, per_person): res = num * per_person if res <= total: return True return False foo = equal_slices(11, 11, 1) print(str(foo))
def equal_slices(total, num, per_person): res = num * per_person if res <= total: return True return False foo = equal_slices(11, 11, 1) print(str(foo))
class FileExtractorTimeoutException(Exception): pass class ParamsInvalidException(Exception): pass class NoProperExtractorFindException(Exception): def __init__(self): super().__init__('NoProperExtractorFind Exception')
class Fileextractortimeoutexception(Exception): pass class Paramsinvalidexception(Exception): pass class Noproperextractorfindexception(Exception): def __init__(self): super().__init__('NoProperExtractorFind Exception')
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Purpose: Agent API Methods ''' __author__ = 'Matt Joyce' __email__ = 'matt@joyce.nyc' __copyright__ = 'Copyright 2016, Symphony Communication Services LLC' class Base(object): def __init__(self, *args, **kwargs): super(Base, self).__init__(*...
""" Purpose: Agent API Methods """ __author__ = 'Matt Joyce' __email__ = 'matt@joyce.nyc' __copyright__ = 'Copyright 2016, Symphony Communication Services LLC' class Base(object): def __init__(self, *args, **kwargs): super(Base, self).__init__(*args, **kwargs) def test_echo(self, test_str...
s = input() k1 = input() k2 = input() out = "" for c in s: found = False for i in range(len(k1)): if c == k1[i]: out += k2[i] found = True break elif c == k2[i]: out += k1[i] found = True break if not found: out ...
s = input() k1 = input() k2 = input() out = '' for c in s: found = False for i in range(len(k1)): if c == k1[i]: out += k2[i] found = True break elif c == k2[i]: out += k1[i] found = True break if not found: out ...
# This program converts the speeds 60 kph # through 130 kph (in 10 kph increments) # to mph. START_SPEED = 60 END_SPEED = 131 INCREMENT = 10 CONVERSION_FACTOR = 0.6214 # Print the table headings. print('KPH\tMPH') print('--------------') # Print the speeds for kph in range(START_SPEED, END_SPEED, INCREMENT): ...
start_speed = 60 end_speed = 131 increment = 10 conversion_factor = 0.6214 print('KPH\tMPH') print('--------------') for kph in range(START_SPEED, END_SPEED, INCREMENT): mph = kph * CONVERSION_FACTOR print(kph, '\t', format(mph, '.1f'))
d = dict() d['quincy'] = 1 d['beau'] = 5 d['kris'] = 9 for (k,i) in d.items(): print(k, i)
d = dict() d['quincy'] = 1 d['beau'] = 5 d['kris'] = 9 for (k, i) in d.items(): print(k, i)
# Africa 2010 # Problem A: Store Credit # Jon Hanson # # Declare Variables # ifile = 'input.txt' # simple input ofile = 'output.txt' # simple output #ifile = 'A-large-practice.in' # official input #ofile = 'A-large-practice.out' # official output caselist = [] # list containing cases # # Problem S...
ifile = 'input.txt' ofile = 'output.txt' caselist = [] class Credcase(object): def __init__(self, credit, itemCount, items): self.credit = int(credit) self.itemCount = int(itemCount) self.items = list(map(int, items.split())) self.cost = -1 self.solution = [] def try_s...
class PodpingCustomJsonPayloadExceeded(RuntimeError): """Raise when the size of a json string exceeds the custom_json payload limit""" class TooManyCustomJsonsPerBlock(RuntimeError): """Raise when trying to write more than 5 custom_jsons in a single block"""
class Podpingcustomjsonpayloadexceeded(RuntimeError): """Raise when the size of a json string exceeds the custom_json payload limit""" class Toomanycustomjsonsperblock(RuntimeError): """Raise when trying to write more than 5 custom_jsons in a single block"""
# Version 1: build products of before and after i, Time: O(n), Space: O(n) class Solution: def productExceptSelf(self, nums): """ :type nums: List[int] :rtype: List[int] """ # scan from left to right to find products before i before_i = [i for i in range(len(nums))] ...
class Solution: def product_except_self(self, nums): """ :type nums: List[int] :rtype: List[int] """ before_i = [i for i in range(len(nums))] prod = 1 for i in range(len(nums)): before_i[i] = prod prod *= nums[i] after_i = [i f...
def most_frequent(data): """ determines the most frequently occurring string in the sequence. """ # your code here max = 0 res = '' for each in data: if max < data.count(each): res = each max = data.count(each) return res if __name__ == '__main__': ...
def most_frequent(data): """ determines the most frequently occurring string in the sequence. """ max = 0 res = '' for each in data: if max < data.count(each): res = each max = data.count(each) return res if __name__ == '__main__': assert most_frequent...
# Crie um programa que leia varios numeros # inteiros pelo teclado. O programa so # vai parar quando o usuario digitar o # valor 999, que eh a condicao de parada. # No final, mostre quantos numeros foram # digitados e qual foi a soma entre eles # (desconsiderando o flag). n = s = c = 0 while True: n = int(input('Di...
n = s = c = 0 while True: n = int(input('Digite um numero [999 para parar]: ')) if n == 999: break s += n c += 1 print(f'A soma dos numeros eh: {s}') print(f'A quantidade de numero digitada foi: {c}')
class AdapterError(Exception): pass class ServiceAPIError(Exception): pass
class Adaptererror(Exception): pass class Serviceapierror(Exception): pass
#!/usr/bin/env python problem4 = max(i*j for i in range(100, 1000+1) for j in range(i, 1000+1) \ if str(i*j) == str(i*j)[::-1]) print(problem4)
problem4 = max((i * j for i in range(100, 1000 + 1) for j in range(i, 1000 + 1) if str(i * j) == str(i * j)[::-1])) print(problem4)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Unit tests for dataset class.""" # import datetime # import os # import unittest # # from pma_api import db, create_app # from pma_api.db_models import Dataset # # from .config import TEST_STATIC_DIR # # # # TODO: incomplete # class TestDataset(unittest.TestCase): # ...
"""Unit tests for dataset class."""
#!/usr/bin/env python class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': lo, hi = 0, len(nums)-1 while lo <= hi: mi = lo + (hi-lo)//2 if target == nums[mi]: return mi if nums[lo] <= nums[mi]: if nums[lo] <= target < nums[...
class Solution: def search(self, nums: 'List[int]', target: 'int') -> 'int': (lo, hi) = (0, len(nums) - 1) while lo <= hi: mi = lo + (hi - lo) // 2 if target == nums[mi]: return mi if nums[lo] <= nums[mi]: if nums[lo] <= target < n...
def add_time(start, duration, day=None): time, period = start.split() initial_period = period hr_start, min_start = time.split(':') hr_duration, min_duration = duration.split(':') min_new = int(min_start) + int(min_duration) hr_new = int(hr_start) + int(hr_duration) periods_later = 0 days_later = 0...
def add_time(start, duration, day=None): (time, period) = start.split() initial_period = period (hr_start, min_start) = time.split(':') (hr_duration, min_duration) = duration.split(':') min_new = int(min_start) + int(min_duration) hr_new = int(hr_start) + int(hr_duration) periods_later = 0 ...
# Histogram of life_exp, 15 bins plt.hist(life_exp, bins = 15) # Show and clear plot plt.show() plt.clf() # Histogram of life_exp1950, 15 bins plt.hist(life_exp1950, bins = 15) # Show and clear plot again plt.show() plt.clf()
plt.hist(life_exp, bins=15) plt.show() plt.clf() plt.hist(life_exp1950, bins=15) plt.show() plt.clf()
class Solution(object): def numberToWords(self, num): under_twenty = ["", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen"] under_hundred_above_twenty = ["Twenty", "Thi...
class Solution(object): def number_to_words(self, num): under_twenty = ['', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'] under_hundred_above_twenty = ['Twenty', '...
""" [9/10/2014] Challenge #179 [Intermediate] Roguelike - The traveller Game https://www.reddit.com/r/dailyprogrammer/comments/2g1c80/9102014_challenge_179_intermediate_roguelike_the/ #Description: So I was fooling around once with an idea to make a fun Rogue like game. If you do not know what a Rogue Like is check ...
""" [9/10/2014] Challenge #179 [Intermediate] Roguelike - The traveller Game https://www.reddit.com/r/dailyprogrammer/comments/2g1c80/9102014_challenge_179_intermediate_roguelike_the/ #Description: So I was fooling around once with an idea to make a fun Rogue like game. If you do not know what a Rogue Like is check ...
""" Selection sort. """ def selection_sort(A, unused_0=0, unused_1=1): for j in range(len(A)-1): iMin = j for i in range(j+1, len(A)): if A[i] < A[iMin]: iMin = i if iMin != j: A[j], A[iMin] = A[iMin], A[j]
""" Selection sort. """ def selection_sort(A, unused_0=0, unused_1=1): for j in range(len(A) - 1): i_min = j for i in range(j + 1, len(A)): if A[i] < A[iMin]: i_min = i if iMin != j: (A[j], A[iMin]) = (A[iMin], A[j])
""" This file is part of Totara Enterprise Extensions. Copyright (C) 2020 onwards Totara Learning Solutions LTD Totara Enterprise Extensions is provided only to Totara Learning Solutions LTD's customers and partners, pursuant to the terms and conditions of a separate agreement with Totara Learning Solutions LTD or it...
""" This file is part of Totara Enterprise Extensions. Copyright (C) 2020 onwards Totara Learning Solutions LTD Totara Enterprise Extensions is provided only to Totara Learning Solutions LTD's customers and partners, pursuant to the terms and conditions of a separate agreement with Totara Learning Solutions LTD or it...
#!/usr/bin/env python3.7 # -*- coding: utf-8 -*- # Source: https://youtu.be/6oL-0TdVy28 class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class BinaryTree(object): def __init__(self, root): self.root = Node(root) def pr...
class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None class Binarytree(object): def __init__(self, root): self.root = node(root) def print_tree(self, traversal_type): if traversal_type == 'preorder': retur...
#!/usr/bin/env python # Software License Agreement (BSD License) # # Copyright (c) 2011, Willow Garage, Inc. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistributions of source code...
def bonus(robot): song = ((76, 16), (76, 16), (72, 8), (76, 16), (79, 32), (67, 32), (72, 24), (67, 24), (64, 24), (69, 16), (71, 16), (70, 8), (69, 16), (79, 16), (76, 16), (72, 8), (74, 16), (71, 24), (60, 16), (79, 8), (78, 8), (77, 8), (74, 8), (75, 8), (76, 16), (67, 8), (69, 8), (72, 16), (69, 8), (72, 8), (7...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, root: TreeNode, subRoot: TreeNode) -> bool: if not root: return Fals...
class Solution: def is_subtree(self, root: TreeNode, subRoot: TreeNode) -> bool: if not root: return False return self.isEqualtree(root, subRoot) or self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot) def is_equaltree(self, root1, root2): if not root1 ...
'''Helper to filter sets of data''' class SetFilter: '''Helper class to filter list''' @staticmethod def diff(a_set, b_set): '''Filter by not intersection''' return not set(b_set).intersection(set(a_set)) @staticmethod def exact(a_set, b_set): '''Filter by eq''' return set(a_set) == set(b_se...
"""Helper to filter sets of data""" class Setfilter: """Helper class to filter list""" @staticmethod def diff(a_set, b_set): """Filter by not intersection""" return not set(b_set).intersection(set(a_set)) @staticmethod def exact(a_set, b_set): """Filter by eq""" re...
code_begin = """#!/usr/bin/env bash curl""" code_header = """ --header "{header}:{value}" """ code_proxy = " -x {proxy}" code_post = """ --data "{data}" """ code_search = """ | egrep --color " {search_string} |$" """ code_nosearch = """ -v --request {method} {url} {headers} --include"""
code_begin = '#!/usr/bin/env bash\ncurl' code_header = ' --header "{header}:{value}" ' code_proxy = ' -x {proxy}' code_post = ' --data "{data}" ' code_search = ' | egrep --color " {search_string} |$" ' code_nosearch = ' -v --request {method} {url} {headers} --include'
# Solution to Exercise #1 # ... env = MultiAgentArena() obs = env.reset() while True: # Compute actions separately for each agent. a1 = dummy_trainer.compute_action(obs["agent1"]) a2 = dummy_trainer.compute_action(obs["agent2"]) # Send the action-dict to the env. obs, rewards, dones, _ = env.step...
env = multi_agent_arena() obs = env.reset() while True: a1 = dummy_trainer.compute_action(obs['agent1']) a2 = dummy_trainer.compute_action(obs['agent2']) (obs, rewards, dones, _) = env.step({'agent1': a1, 'agent2': a2}) out.clear_output(wait=True) env.render() time.sleep(0.1) if dones['agent...
#!/usr/bin/env python # -*- coding: utf-8 -*- count = 0 while count < 10: count += 1 if count % 2 == 0: continue print(count, end=" ")
count = 0 while count < 10: count += 1 if count % 2 == 0: continue print(count, end=' ')
def bubble_sort(arr): length = len(arr) for i in range(length): for j in range(0, length - i - 1): if arr[j] > arr[j + 1]: arr[j], arr[j + 1] = arr[j + 1], arr[j] def main(): random_list = [12, 4, 5, 6, 25, 14, 15] bubble_sort(random_list) print(random_list) if...
def bubble_sort(arr): length = len(arr) for i in range(length): for j in range(0, length - i - 1): if arr[j] > arr[j + 1]: (arr[j], arr[j + 1]) = (arr[j + 1], arr[j]) def main(): random_list = [12, 4, 5, 6, 25, 14, 15] bubble_sort(random_list) print(random_list) ...
def bowling_score(frames): frames = [list(r) for r in frames.split(' ')] points = 0 for f in range(0, 8): if frames[f][0] == 'X': points += 10 if frames[f+1][0] == 'X': points += 10 if frames[f+2][0] == 'X': p...
def bowling_score(frames): frames = [list(r) for r in frames.split(' ')] points = 0 for f in range(0, 8): if frames[f][0] == 'X': points += 10 if frames[f + 1][0] == 'X': points += 10 if frames[f + 2][0] == 'X': points += 10...
# -*- coding: utf-8 -*- __soap_format = ( '<?xml version="1.0" encoding="UTF-8"?>\n' '<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" ' 'xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" ' 'xmlns:xsi="http://www.w3.org/2001/XM...
__soap_format = '<?xml version="1.0" encoding="UTF-8"?>\n<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:ns1="{url}"><SOAP-ENV...
ACCEL_FSR_2G = 0 ACCEL_FSR_4G = 1 ACCEL_FSR_8G = 2 ACCEL_FSR_16G = 3
accel_fsr_2_g = 0 accel_fsr_4_g = 1 accel_fsr_8_g = 2 accel_fsr_16_g = 3
SUCCESS = 0 FAILURE = 1 # NOTE: click.abort() uses this # for when tests are already running ALREADY_RUNNING = 2
success = 0 failure = 1 already_running = 2
karman_line_earth = 100_000*m // km karman_line_mars = 80_000*m // km karman_line_venus = 250_000*m // km
karman_line_earth = 100000 * m // km karman_line_mars = 80000 * m // km karman_line_venus = 250000 * m // km
def extractWLTranslations(item): """ # 'WL Translations' """ vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Chapter Releases' in item['tags'] and ('OSI' in item['tags'] or item['title'].startswith('OSI ...
def extract_wl_translations(item): """ # 'WL Translations' """ (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title']) if not (chp or vol or frag) or 'preview' in item['title'].lower(): return None if 'Chapter Releases' in item['tags'] and ('OSI' in item['tags'] or item...
class Car: def __init__(self, make, petrol_consumption): self.make = make self.petrol_consumption = petrol_consumption def petrol_calculation(self, price = 22.5): return self.petrol_consumption * price ford = Car("ford", 10) money = ford.petrol_calculation() print(money)
class Car: def __init__(self, make, petrol_consumption): self.make = make self.petrol_consumption = petrol_consumption def petrol_calculation(self, price=22.5): return self.petrol_consumption * price ford = car('ford', 10) money = ford.petrol_calculation() print(money)
# Mouse Move # # November 12, 2018 # By Robin Nash [c,r] = [int(i) for i in input().split(" ") if i != " "] x,y = 0,0 while True: pair = [int(i) for i in input().split(" ") if i != " "] if pair == [0,0]: break x += pair[0] y += pair[1] pair = [x,y] for i in range(2): ...
[c, r] = [int(i) for i in input().split(' ') if i != ' '] (x, y) = (0, 0) while True: pair = [int(i) for i in input().split(' ') if i != ' '] if pair == [0, 0]: break x += pair[0] y += pair[1] pair = [x, y] for i in range(2): if pair[i] > [c, r][i]: pair[i] = [c, r][i...
class Solution: def thirdMax(self, nums: List[int]) -> int: hq = [] for x in nums: if x not in hq: if len(hq) < 3: heapq.heappush(hq, x) else: heapq.heappushpop(hq, x) if len(hq) < 3: return hq[-1...
class Solution: def third_max(self, nums: List[int]) -> int: hq = [] for x in nums: if x not in hq: if len(hq) < 3: heapq.heappush(hq, x) else: heapq.heappushpop(hq, x) if len(hq) < 3: return hq[...
s = input() k = int(input()) ans = set() for i in range(len(s)): for j in range(1, k+1): ans.add(s[i:i+j]) # print(ans) print(sorted(list(ans))[k-1])
s = input() k = int(input()) ans = set() for i in range(len(s)): for j in range(1, k + 1): ans.add(s[i:i + j]) print(sorted(list(ans))[k - 1])
""" File: copyfile.py Project 7.3 Copies the text from a given input file to a given output file. """ # Take the inputs inName = input("Enter the input file name: ") outName = input("Enter the output file name: ") # Open the input file and read the text inputFile = open(inName, 'r') text = inputFile.read() # Open t...
""" File: copyfile.py Project 7.3 Copies the text from a given input file to a given output file. """ in_name = input('Enter the input file name: ') out_name = input('Enter the output file name: ') input_file = open(inName, 'r') text = inputFile.read() out_file = open(outName, 'w') outFile.write(text) outFile.close()