content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
_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
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...
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
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__)
#!/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...
# 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 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', '...
#!/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...
# 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
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])
# -*- coding: utf-8 -*- def test_task_run(): print("test task run module") assert 1 == 1
def test_task_run(): print('test task run module') assert 1 == 1
n=int(input("Enter the Decimal Number:")) def covbin(n): if(n==0): return 0 else: return (n%2)+(10*covbin(n//2)) print("Binary is=",covbin(n))
n = int(input('Enter the Decimal Number:')) def covbin(n): if n == 0: return 0 else: return n % 2 + 10 * covbin(n // 2) print('Binary is=', covbin(n))
__all__ = ['descriptor', 'es_transport', 'flushing_buffer', 'line_buffer', 'sqs_transport', 'transport_exceptions', 'transport_result', 'transport_utils']
__all__ = ['descriptor', 'es_transport', 'flushing_buffer', 'line_buffer', 'sqs_transport', 'transport_exceptions', 'transport_result', 'transport_utils']
def total_centro_custo(D_e): D_return = {} # Pecorre dados de cada pessoa for v in D_e.values(): if v['centro de custo'] not in D_return: D_return[v['centro de custo']] = 0 D_return[v['centro de custo']] += v['valor'] return D_return
def total_centro_custo(D_e): d_return = {} for v in D_e.values(): if v['centro de custo'] not in D_return: D_return[v['centro de custo']] = 0 D_return[v['centro de custo']] += v['valor'] return D_return
def print_n(s, n): while n >= 0: print(s) n -= 1
def print_n(s, n): while n >= 0: print(s) n -= 1
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. # A copy of the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "licens...
package_xml_element_order = ['name', 'version', 'description', 'author', 'maintainer', 'license', 'url', 'buildtool_depend', 'build_depend', 'build_export_depend', 'depend', 'exec_depend', 'test_depend', 'member_of_group', 'doc_depend', 'conflict', 'replace', 'export'] cmake_lists_renamed_variables = {'${CATKIN_DEVEL_P...
class CommandModule: def __init__(self, name, bus, conn, chan, conf): self.name = name self.conf = conf self.chan = chan self.conn = conn self.bus = bus def send(self, msg): self.conn.privmsg(self.chan, msg)...
class Commandmodule: def __init__(self, name, bus, conn, chan, conf): self.name = name self.conf = conf self.chan = chan self.conn = conn self.bus = bus def send(self, msg): self.conn.privmsg(self.chan, msg) def error(self, msg): self.status('error:...
text = input('Enter a text: ') character = input('Enter a character that you can search in "'+text+'": ') result = text.count(character) print('The character "'+character+'" appears '+str(result)+' times in "'+text+'".')
text = input('Enter a text: ') character = input('Enter a character that you can search in "' + text + '": ') result = text.count(character) print('The character "' + character + '" appears ' + str(result) + ' times in "' + text + '".')
class BME280: '''Class to mock temp sensor''' def __init__(self): '''Constructor for mock''' def get_temperature(self): '''Temp''' return 20.0
class Bme280: """Class to mock temp sensor""" def __init__(self): """Constructor for mock""" def get_temperature(self): """Temp""" return 20.0
def test_movie_tech_sections(ia): movie = ia.get_movie('0133093', info=['technical']) tech = movie.get('tech', []) assert set(tech.keys()) == set(['sound mix', 'color', 'aspect ratio', 'camera', 'laboratory', 'cinematographic process', 'printed film format', ...
def test_movie_tech_sections(ia): movie = ia.get_movie('0133093', info=['technical']) tech = movie.get('tech', []) assert set(tech.keys()) == set(['sound mix', 'color', 'aspect ratio', 'camera', 'laboratory', 'cinematographic process', 'printed film format', 'negative format', 'runtime', 'film length'])
#!/usr/bin/env python3 #Swimming in the pool excercise def getValue(): try: valueInput = int(input()) except ValueError: print("Wrong type") quit() else: return valueInput def calcResidue(length, coordinate): halfOfLength = length / 2 residue = length - coordinate if residue < halfOfLength: return res...
def get_value(): try: value_input = int(input()) except ValueError: print('Wrong type') quit() else: return valueInput def calc_residue(length, coordinate): half_of_length = length / 2 residue = length - coordinate if residue < halfOfLength: return residu...
class Robot: def greet(self): print('Hello Viraj') class RobotChild(Robot): def greet(self): print('Hello Scott') # Instantiate RobotChild Class child = RobotChild() # Invoke Greet method from RobotChild class child.greet()
class Robot: def greet(self): print('Hello Viraj') class Robotchild(Robot): def greet(self): print('Hello Scott') child = robot_child() child.greet()
#!/usr/bin/env python3 def welcome(): print("Welcome") def hi(name): print("Hi " + name + "!") welcome() username = input("Who are there? ") hi(name=username) hi(username)
def welcome(): print('Welcome') def hi(name): print('Hi ' + name + '!') welcome() username = input('Who are there? ') hi(name=username) hi(username)
classes_names = [ 'book', 'bottle', 'cabinet', 'ceiling', 'chair', 'cone', 'counter', 'dishwasher', 'faucet', 'fire extinguisher', 'floor', 'garbage bin', 'microwave', 'paper towel dispenser', 'paper', 'pot', 'refridgerator', 'stove burner', 'table', 'unknown', 'wall', 'bowl', 'magnet', 'sink', 'air vent', 'box', 'door...
classes_names = ['book', 'bottle', 'cabinet', 'ceiling', 'chair', 'cone', 'counter', 'dishwasher', 'faucet', 'fire extinguisher', 'floor', 'garbage bin', 'microwave', 'paper towel dispenser', 'paper', 'pot', 'refridgerator', 'stove burner', 'table', 'unknown', 'wall', 'bowl', 'magnet', 'sink', 'air vent', 'box', 'door ...
''' Return the nth Fibonacci number F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2 ''' def Fibonacci(n): ''' return nth fibonacci number to reduce O(n), we invoke recursion only once during one call (Fn-1, Fn-2) ''' if n <= 1: return (n,0) else: (a,b) = Fibonacci(n-1) return (a+b,a) #p...
""" Return the nth Fibonacci number F0 = 0 F1 = 1 Fn = Fn-1 + Fn-2 """ def fibonacci(n): """ return nth fibonacci number to reduce O(n), we invoke recursion only once during one call (Fn-1, Fn-2) """ if n <= 1: return (n, 0) else: (a, b) = fibonacci(n - 1) return (a + b,...
thisdict = { "brand":"Ford", "model":"Mustang", "year":1964 } for x in thisdict.values(): print(x)
thisdict = {'brand': 'Ford', 'model': 'Mustang', 'year': 1964} for x in thisdict.values(): print(x)
name = "ada lovelace" print(name.title()) print(name.upper()) print(name.lower())
name = 'ada lovelace' print(name.title()) print(name.upper()) print(name.lower())
def has_style(tag): return tag.has_attr('style') def has_class(tag): return tag.has_attr('class') def clean(soup): if soup.name == 'br' or soup.name == 'img' or soup.name == 'p' or soup.name == 'div': return try: ll = 0 for j in soup.strings: ll += len(j.replace('\n', '')) if ll == 0: soup.decompose...
def has_style(tag): return tag.has_attr('style') def has_class(tag): return tag.has_attr('class') def clean(soup): if soup.name == 'br' or soup.name == 'img' or soup.name == 'p' or (soup.name == 'div'): return try: ll = 0 for j in soup.strings: ll += len(j.replace('...
# # PySNMP MIB module HIRSCHMANN-PIM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HIRSCHMANN-PIM-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:31:12 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) ...
load( "@d2l_rules_csharp//csharp:defs.bzl", "csharp_register_toolchains", "csharp_repositories", "import_nuget_package", ) def selenium_register_dotnet(): csharp_register_toolchains() csharp_repositories() native.register_toolchains("//third_party/dotnet/ilmerge:all") import_nuget_pac...
load('@d2l_rules_csharp//csharp:defs.bzl', 'csharp_register_toolchains', 'csharp_repositories', 'import_nuget_package') def selenium_register_dotnet(): csharp_register_toolchains() csharp_repositories() native.register_toolchains('//third_party/dotnet/ilmerge:all') import_nuget_package(name='json.net',...
wifi_ssid = "" wifi_password = "" mqtt_username = "" mqtt_password = "" mqtt_address = "" mqtt_port = 8883
wifi_ssid = '' wifi_password = '' mqtt_username = '' mqtt_password = '' mqtt_address = '' mqtt_port = 8883
# NOTE: \a is the delimiter for chat pages # Quest ids can be found in Quests.py SCRIPT = ''' ID reward_100 SHOW laffMeter LERP_POS laffMeter 0 0 0 1 LERP_SCALE laffMeter 0.2 0.2 0.2 1 WAIT 1.5 ADD_LAFFMETER 1 WAIT 1 LERP_POS laffMeter -1.18 0 -0.87 1 LERP_SCALE laffMeter 0.075 0.075 0.075 1 WAIT 1 FINISH_QUEST_MOVIE ...
script = '\nID reward_100\nSHOW laffMeter\nLERP_POS laffMeter 0 0 0 1\nLERP_SCALE laffMeter 0.2 0.2 0.2 1\nWAIT 1.5\nADD_LAFFMETER 1\nWAIT 1\nLERP_POS laffMeter -1.18 0 -0.87 1\nLERP_SCALE laffMeter 0.075 0.075 0.075 1\nWAIT 1\nFINISH_QUEST_MOVIE\n\n# TUTORIAL\n\nID tutorial_mickey\nLOAD_SFX soundRun "phase_3.5/audio/s...
while True: valores = input().split() n = int(valores[0]) d = a = int(valores[1]) e = b = int(valores[2]) if n == 0 and a == 0 and b == 0: break while e != 0: d, e = e, d % e c = (a * b) // d a_l = len(range(a, n + 1, a)) b_l = len(range(b, n + 1, b)) c_...
while True: valores = input().split() n = int(valores[0]) d = a = int(valores[1]) e = b = int(valores[2]) if n == 0 and a == 0 and (b == 0): break while e != 0: (d, e) = (e, d % e) c = a * b // d a_l = len(range(a, n + 1, a)) b_l = len(range(b, n + 1, b)) c_l = le...
def convert_to_string(idx_list, form_manager): w_list = [] for i in range(len(idx_list)): w_list.append(form_manager.get_idx_symbol(int(idx_list[i]))) return " ".join(w_list) def is_all_same(c1, c2, form_manager): all_same = False if len(c1) == len(c2): all_same = True for ...
def convert_to_string(idx_list, form_manager): w_list = [] for i in range(len(idx_list)): w_list.append(form_manager.get_idx_symbol(int(idx_list[i]))) return ' '.join(w_list) def is_all_same(c1, c2, form_manager): all_same = False if len(c1) == len(c2): all_same = True for j...
def test_geoadd(judge_command): judge_command( 'GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"', { "command": "GEOADD", "key": "Sicily", "longitude": "15.087269", "latitude": "37.502669", "member": '"Catania"', ...
def test_geoadd(judge_command): judge_command('GEOADD Sicily 13.361389 38.115556 "Palermo" 15.087269 37.502669 "Catania"', {'command': 'GEOADD', 'key': 'Sicily', 'longitude': '15.087269', 'latitude': '37.502669', 'member': '"Catania"'}) def test_georadiusbymember(judge_command): judge_command('GEORADIUSBYMEMBE...
# Copyright 2019 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. PYTHON_VERSION_COMPATIBILITY = 'PY2+3' DEPS = [ 'recipe_engine/cipd', 'recipe_engine/commit_position', 'recipe_engine/context', 'recipe_engine/file'...
python_version_compatibility = 'PY2+3' deps = ['recipe_engine/cipd', 'recipe_engine/commit_position', 'recipe_engine/context', 'recipe_engine/file', 'recipe_engine/golang', 'recipe_engine/json', 'recipe_engine/nodejs', 'recipe_engine/path', 'recipe_engine/raw_io', 'recipe_engine/step', 'depot_tools/depot_tools', 'depot...
class Cup(object): def __init__(self, name): self.name = name self.price = 0 class MyClass: pass def myfunc(): pass if __name__ == '__main__': cup1 = Cup('aaa') cup2 = Cup('bbb') # get attribute of object print(getattr(cup1, 'name')) print(getattr(cup2, 'name')) ...
class Cup(object): def __init__(self, name): self.name = name self.price = 0 class Myclass: pass def myfunc(): pass if __name__ == '__main__': cup1 = cup('aaa') cup2 = cup('bbb') print(getattr(cup1, 'name')) print(getattr(cup2, 'name')) try: name = getattr(cup1...
# set, himpunan: super_hero = {'superman','ironman','hulk','flash'} print(super_hero) print('1=====================') super_hero.add('gundala') super_hero.add('121') print(super_hero) print('2=====================') super_hero.add('hulk') print(super_hero) print(sorted(super_hero)) print('3========...
super_hero = {'superman', 'ironman', 'hulk', 'flash'} print(super_hero) print('1=====================') super_hero.add('gundala') super_hero.add('121') print(super_hero) print('2=====================') super_hero.add('hulk') print(super_hero) print(sorted(super_hero)) print('3=====================') ganjil = {1, 3, 5, ...
# Python carefully avoids evaluating bools more than once in a variety of situations. # Eg: # In the statement # if a or b: # it doesn't simply compute (a or b) and then evaluate the result to decide whether to # jump. If a is true it jumps directly to the body of the if statement. # We can confirm that this behaviour...
class Explodingbool: def __init__(self, value): self.value = value self.booled = False def __bool__(self): assert not self.booled self.booled = True return self.value y = exploding_bool(False) and False and True and False print(y) if exploding_bool(True) or False or Tru...
def firstZero(arr, low, high): if (high >= low): # Check if mid element is first 0 mid = low + int((high - low) / 2) if (( mid == 0 or arr[mid-1] == 1) and arr[mid] == 0): return mid # If mid element is not 0 if (...
def first_zero(arr, low, high): if high >= low: mid = low + int((high - low) / 2) if (mid == 0 or arr[mid - 1] == 1) and arr[mid] == 0: return mid if arr[mid] == 1: return first_zero(arr, mid + 1, high) else: return first_zero(arr, low, mid - 1) ...
# augmented vertex class Vertex: def __init__(self, element, location): self.element = element self.location = location def getElement(self): return self.element def setElement(self, element): self.element = element def getLocation(self): return self.location ...
class Vertex: def __init__(self, element, location): self.element = element self.location = location def get_element(self): return self.element def set_element(self, element): self.element = element def get_location(self): return self.location def set_loc...
def get_node_info(file): nodes = set() df = [line.strip().split() for line in open('input/%s.txt' % file).readlines() if line.startswith('/dev')] for nodeinfo in df: # Filesystem Size Used Avail Use% # /dev/grid/node-x0-y0 92T 68T ...
def get_node_info(file): nodes = set() df = [line.strip().split() for line in open('input/%s.txt' % file).readlines() if line.startswith('/dev')] for nodeinfo in df: (_, x, y) = nodeinfo[0].split('-') size = int(nodeinfo[1][:-1]) used = int(nodeinfo[2][:-1]) node = (int(x[1:]...
class Problem: initial_state = [None, None, None, None, None, None, None, None] row = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] col = [0,1,2,3,4,5,6,7] def check_if_attacked(self, state): # returns True if attacked try: index = state.index(None) - 1 except ValueEr...
class Problem: initial_state = [None, None, None, None, None, None, None, None] row = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] col = [0, 1, 2, 3, 4, 5, 6, 7] def check_if_attacked(self, state): try: index = state.index(None) - 1 except ValueError: index = 7 ...
# Easy # https://leetcode.com/problems/climbing-stairs/ class Solution: # Time complexity : O(n) # Space complexity: O(1) # Fibonacci sequence def climbStairs(self, n: int) -> int: a, b = 1, 2 for _ in range(1, n): a, b = b, a + b return a
class Solution: def climb_stairs(self, n: int) -> int: (a, b) = (1, 2) for _ in range(1, n): (a, b) = (b, a + b) return a
file = {'amy':5, 'bob':8, 'candy':6, 'doby':9, 'john':0} print("Amy's number is:" +'\n\t' + str(file['amy']) +'.') print("\nBob's number is:" +'\n\t' + str(file['bob']) +'.')
file = {'amy': 5, 'bob': 8, 'candy': 6, 'doby': 9, 'john': 0} print("Amy's number is:" + '\n\t' + str(file['amy']) + '.') print("\nBob's number is:" + '\n\t' + str(file['bob']) + '.')
class Solution: def myAtoi(self, str): if len(str) == 0: return 0 res = 0 max_int = 2147483647 min_int = -2147483648 for i in range(0, len(str)): c = str[i] if c != ' ': break s = str[i:] pos = False ...
class Solution: def my_atoi(self, str): if len(str) == 0: return 0 res = 0 max_int = 2147483647 min_int = -2147483648 for i in range(0, len(str)): c = str[i] if c != ' ': break s = str[i:] pos = False ...
class Config: def __init__(self): self.basename = 'delta_video' self.directory = '/home/eleanor/Documents/gcamp_analysis_files_temp/171019-06-bottom-experiment/data' self.topics = ['/multi_tracker/1/delta_video',] self.record_length_hours = 1
class Config: def __init__(self): self.basename = 'delta_video' self.directory = '/home/eleanor/Documents/gcamp_analysis_files_temp/171019-06-bottom-experiment/data' self.topics = ['/multi_tracker/1/delta_video'] self.record_length_hours = 1
class Memory: def __init__(self, size): self.mem = bytearray(size) self.bin_size = 0 def read8(self, addr): val = self.mem[addr] #if addr > self.bin_size: # print(f'Read {val:02x} at {addr}') return val def write8(self, addr, val): self.mem[addr]...
class Memory: def __init__(self, size): self.mem = bytearray(size) self.bin_size = 0 def read8(self, addr): val = self.mem[addr] return val def write8(self, addr, val): self.mem[addr] = val def write_bin(self, addr, data): self.mem[addr:addr + len(data...
__author__ = 'Jeffrey Seifried' __description__ = 'A library for forecasting sun positions' __email__ = 'jeffrey.seifried@gmail.com' __program__ = 'analemma' __url__ = 'http://github.com/jeffseif/{}'.format(__program__) __version__ = '1.0.0' __year__ = '2020'
__author__ = 'Jeffrey Seifried' __description__ = 'A library for forecasting sun positions' __email__ = 'jeffrey.seifried@gmail.com' __program__ = 'analemma' __url__ = 'http://github.com/jeffseif/{}'.format(__program__) __version__ = '1.0.0' __year__ = '2020'
# flake8: noqa # https://github.com/trezor/python-mnemonic/blob/master/vectors.json trezor_vectors = { "english": [ { "id": 0, "entropy": "00000000000000000000000000000000", "mnemonic": "abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about", "salt"...
trezor_vectors = {'english': [{'id': 0, 'entropy': '00000000000000000000000000000000', 'mnemonic': 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about', 'salt': 'TREZOR', 'binary': '00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 00000000000 00000000000...
# -*- coding: utf-8 -*- # Copyright 2011 Fanficdownloader team # # 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 appli...
pass
# https://leetcode.com/problems/single-number-iii/ class Solution: def singleNumber(self, nums: List[int]) -> List[int]: d = {} for num in nums: if num in d: d[num] += 1 else: d[num] = 1 result = [] for key, v...
class Solution: def single_number(self, nums: List[int]) -> List[int]: d = {} for num in nums: if num in d: d[num] += 1 else: d[num] = 1 result = [] for (key, value) in d.items(): if value == 1: resu...
# https://stackoverflow.com/questions/1883980/find-the-nth-occurrence-of-substring-in-a-string def find_nth(haystack, needle, n): start = haystack.find(needle) while start >= 0 and n > 1: start = haystack.find(needle, start+len(needle)) n -= 1 return start file_to_be_read = input("Which fil...
def find_nth(haystack, needle, n): start = haystack.find(needle) while start >= 0 and n > 1: start = haystack.find(needle, start + len(needle)) n -= 1 return start file_to_be_read = input('Which file do you want to open? (Please specify the full filename.)\n') rtz_file = open(file_to_be_read...
a=int(input("Enter a number")) if a%2==0: print(a,"is an Even Number") else: print(a,"is an Odd Number")
a = int(input('Enter a number')) if a % 2 == 0: print(a, 'is an Even Number') else: print(a, 'is an Odd Number')
# wczytanie wszystkich trzech plikow with open('../dane/dane5-1.txt') as f: data1 = [] for line in f.readlines(): data1.append(int(line[:-1])) with open('../dane/dane5-2.txt') as f: data2 = [] for line in f.readlines(): data2.append(int(line[:-1])) with open('../dane/dane5-3.txt') as f: ...
with open('../dane/dane5-1.txt') as f: data1 = [] for line in f.readlines(): data1.append(int(line[:-1])) with open('../dane/dane5-2.txt') as f: data2 = [] for line in f.readlines(): data2.append(int(line[:-1])) with open('../dane/dane5-3.txt') as f: data3 = [] for line in f.read...
numbers = list(range(0, 110, 10)) numbers = (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100) second = [] x = 0 while x < len(numbers): t = numbers[x] *2.5 if t % 2 == 0: second.append(int(t)) x += 1 print(second) print(x)
numbers = list(range(0, 110, 10)) numbers = (0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100) second = [] x = 0 while x < len(numbers): t = numbers[x] * 2.5 if t % 2 == 0: second.append(int(t)) x += 1 print(second) print(x)
class initial(object): pass INITIAL = initial() another = INITIAL print(another is INITIAL)
class Initial(object): pass initial = initial() another = INITIAL print(another is INITIAL)
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com) {*[1,2,3], *[4,5,6]} # EXPECTED: [ ..., BUILD_SET_UNPACK(2), ... ]
{*[1, 2, 3], *[4, 5, 6]} [..., build_set_unpack(2), ...]
def capital_indexes(string: str) -> list: return [index for index, char in enumerate(string) if char.isupper()] # return [letter for letter in range(len(indexes)) if indexes[letter].isupper()] def tests() -> None: print(capital_indexes("mYtESt")) # [1, 3, 4] print(capital_indexes("owO")) if __name_...
def capital_indexes(string: str) -> list: return [index for (index, char) in enumerate(string) if char.isupper()] def tests() -> None: print(capital_indexes('mYtESt')) print(capital_indexes('owO')) if __name__ == '__main__': tests()
# dataset settings dataset_type = 'ImageNet' img_norm_cfg = dict( mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [ dict(type='LoadImageFromFile'), dict(type='RandomResizedCrop', size=224, backend='pillow'), dict(type='RandomFlip', flip_prob=0.5, direction='hor...
dataset_type = 'ImageNet' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) train_pipeline = [dict(type='LoadImageFromFile'), dict(type='RandomResizedCrop', size=224, backend='pillow'), dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'), dict(type='Normalize', **i...
class StakeHolder: def __init__(self, staker, amount_pending_for_approval, amount_approved, block_no_created): self._staker = staker self._amount_pending_for_approval = amount_pending_for_approval self._amount_approved = amount_approved self._block_no_created = block_no_created ...
class Stakeholder: def __init__(self, staker, amount_pending_for_approval, amount_approved, block_no_created): self._staker = staker self._amount_pending_for_approval = amount_pending_for_approval self._amount_approved = amount_approved self._block_no_created = block_no_created ...