content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def set_isic_configs(args): args.batch_size = 128 args.fixmatch_k_img = 8192 args.simclr_batch_size = 512 args.stop_labeled = 9134 args.add_labeled = 1015 args.start_labeled = 203 args.merged = False args.pseudo_labeling_num = 20264 - args.stop_labeled if args.novel_class_detection:...
def set_isic_configs(args): args.batch_size = 128 args.fixmatch_k_img = 8192 args.simclr_batch_size = 512 args.stop_labeled = 9134 args.add_labeled = 1015 args.start_labeled = 203 args.merged = False args.pseudo_labeling_num = 20264 - args.stop_labeled if args.novel_class_detection: ...
############################################################################### # Define everything needed to build nightly Julia for gc debugging ############################################################################### julia_gc_debug_factory = util.BuildFactory() julia_gc_debug_factory.useProgress = True julia...
julia_gc_debug_factory = util.BuildFactory() julia_gc_debug_factory.useProgress = True julia_gc_debug_factory.addSteps([steps.Git(name='Julia checkout', repourl=util.Property('repository', default='git://github.com/JuliaLang/julia.git'), mode='incremental', method='clean', submodules=True, clobberOnFailure=True, progre...
n,k=map(int,input().split()) l=[int(x) for x in input().split()] l.sort() s=set([]) ans=0 for i in l: if i%k==0: if i//k not in s: s.add(i) ans+=1 else: ans+=1 s.add(i) print(ans) # https://codeforces.com/problemset/problem/274/A
(n, k) = map(int, input().split()) l = [int(x) for x in input().split()] l.sort() s = set([]) ans = 0 for i in l: if i % k == 0: if i // k not in s: s.add(i) ans += 1 else: ans += 1 s.add(i) print(ans)
""" @author Huaze Shen @date 2019-08-01 """ def max_sub_array(nums): return helper(nums, 0, len(nums) - 1) def helper(nums, left, right): if left == right: return nums[left] p = (left + right) // 2 left_sum = helper(nums, left, p) right_sum = helper(nums, p + 1, right) cross_sum = cr...
""" @author Huaze Shen @date 2019-08-01 """ def max_sub_array(nums): return helper(nums, 0, len(nums) - 1) def helper(nums, left, right): if left == right: return nums[left] p = (left + right) // 2 left_sum = helper(nums, left, p) right_sum = helper(nums, p + 1, right) cross_sum = cros...
num = int(input('digite um numero: ')) total = 0 for c in range(1, num + 1): if num % c == 0: print('\033[33m', end=' ') total = total + 1 else: print('\033[31m', end=' ') print('{}'.format(c), end=' ') print('\n\033[m0 o numero {} foi dividido {} veses '.format(num, total)) if total...
num = int(input('digite um numero: ')) total = 0 for c in range(1, num + 1): if num % c == 0: print('\x1b[33m', end=' ') total = total + 1 else: print('\x1b[31m', end=' ') print('{}'.format(c), end=' ') print('\n\x1b[m0 o numero {} foi dividido {} veses '.format(num, total)) if total...
def fib(n): if n <= 1: return n tab = [i for i in range(n+1)] tab[0] = 0 tab[1] = 1 for i in range(2, n + 1): tab[i] = tab[i-1] + tab[i-2] return tab[n] if __name__ == '__main__': print(fib(4))
def fib(n): if n <= 1: return n tab = [i for i in range(n + 1)] tab[0] = 0 tab[1] = 1 for i in range(2, n + 1): tab[i] = tab[i - 1] + tab[i - 2] return tab[n] if __name__ == '__main__': print(fib(4))
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode: def helper(arr): if not arr: retur...
class Solution: def construct_maximum_binary_tree(self, nums: List[int]) -> TreeNode: def helper(arr): if not arr: return None max_element = max(arr) max_element_index = arr.index(max(arr)) left_arr = arr[:max_element_index] right...
# -*- coding: utf-8 -*- def test_config_profile(pepper_cli, session_minion_id): '''Test the using a profile''' ret = pepper_cli('*', 'test.ping', profile='pepper') assert ret[session_minion_id] is True
def test_config_profile(pepper_cli, session_minion_id): """Test the using a profile""" ret = pepper_cli('*', 'test.ping', profile='pepper') assert ret[session_minion_id] is True
''' Candies and two Sisters ''' t = int(input()) for i in range(t): n = int(input()) half = n // 2 method = n - 1 - half print(method)
""" Candies and two Sisters """ t = int(input()) for i in range(t): n = int(input()) half = n // 2 method = n - 1 - half print(method)
def infer_breach(value, lowerLimit, upperLimit): if value < lowerLimit: return 'TOO_LOW' if value > upperLimit: return 'TOO_HIGH' return 'NORMAL' def classify_temperature_breach(coolingType, temperatureInC): reference_for_upperLimit = { 'PASSIVE_COOLING' : [0,35], 'HI_ACTIVE_COOLING' ...
def infer_breach(value, lowerLimit, upperLimit): if value < lowerLimit: return 'TOO_LOW' if value > upperLimit: return 'TOO_HIGH' return 'NORMAL' def classify_temperature_breach(coolingType, temperatureInC): reference_for_upper_limit = {'PASSIVE_COOLING': [0, 35], 'HI_ACTIVE_COOLING': [...
# -*- coding: utf-8 -*- # # "config" here is a python module that must have "parser" function. # That function should generate signature of the email and # pass that to "eeas" object (passed as arg) methods. # Not calling any of these would mean that email can't be classified. # # Already present in the namespace: it,...
def parser(eeas, tags, msg): agg_name = fingerprint = None msg_type = None subject = msg.headers.get('subject') if subject: if 'cron-jobs' in tags: m = re.search('^Cron\\s+<(?P<src>[^>]+)>\\s+(?P<name>.*)$', subject) if m: msg_type = 'cron' ...
{ 'variables': { 'firmware_path': '../src', 'lpc18xx_path': '../lpc18xx', 'usb_path': '../deps/usb', 'runtime_path': "../deps/runtime", 'builtin_path': '../builtin', 'tools_path': '../tools', 'otp_path': '../otp', 'erase_path': '../erase', 'boot_path': '../boot', 'cc3k_path': '...
{'variables': {'firmware_path': '../src', 'lpc18xx_path': '../lpc18xx', 'usb_path': '../deps/usb', 'runtime_path': '../deps/runtime', 'builtin_path': '../builtin', 'tools_path': '../tools', 'otp_path': '../otp', 'erase_path': '../erase', 'boot_path': '../boot', 'cc3k_path': '../cc3k_patch', 'COLONY_STATE_CACHE%': '0', ...
def find_low_index(arr, key): low = 0 high = len(arr) - 1 mid = int(high / 2) # Binary Search while low <= high: mid_elem = arr[mid] if mid_elem < key: low = mid + 1 else: high = mid - 1 mid = low + int((high - low) / 2) if low < len(arr...
def find_low_index(arr, key): low = 0 high = len(arr) - 1 mid = int(high / 2) while low <= high: mid_elem = arr[mid] if mid_elem < key: low = mid + 1 else: high = mid - 1 mid = low + int((high - low) / 2) if low < len(arr) and arr[low] == key: ...
#!/usr/bin/env python3 # # Utility functions # # Author: Joe Block <jblock@zscaler.com> # License: Apache 2.0 # Copyright 2022, ZScaler Inc. def dumpObject(obj): """ Dump an object for debugging """ for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr)))
def dump_object(obj): """ Dump an object for debugging """ for attr in dir(obj): print('obj.%s = %r' % (attr, getattr(obj, attr)))
# https://leetcode.com/problems/sqrtx/ class Solution: def mySqrt(self, x): i = 0 while x > i * i: i += 1 return i - 1
class Solution: def my_sqrt(self, x): i = 0 while x > i * i: i += 1 return i - 1
def sort(a: list) -> list: for i in range(len(a) - 1): for j in range(len(a) - i - 1): if a[j] > a[j + 1]: a[j], a[j + 1] = a[j + 1], a[j] return a a = [5, 6, 7, 8, 1, 2, 0, 3, 4, 5, 9] print(sort(a))
def sort(a: list) -> list: for i in range(len(a) - 1): for j in range(len(a) - i - 1): if a[j] > a[j + 1]: (a[j], a[j + 1]) = (a[j + 1], a[j]) return a a = [5, 6, 7, 8, 1, 2, 0, 3, 4, 5, 9] print(sort(a))
# ------------------------------------ # CODE BOOLA 2015 PYTHON WORKSHOP # Mike Wu, Jonathan Chang, Kevin Tan # Puzzle Challenges Number 5 # ------------------------------------ # Last one of the group! # You a deserve a break after this one. # ------------------------------------ # INSTRUCTIONS: # Let's keep w...
def convert(s): pass
BASE_PHRASES = """ **** ahead Be wary of **** Try **** Need **** Imminent ****... Weakness:**** **** ****? Good Luck I did it! Here! I can't take this... Praise the Sun! """.strip().split("\n") FILL_PHRASES = """ Enemy Tough enemy Hollow Soldier Knight Sniper Caster Giant Skeleton Ghost Bug Poison bug Lizard Drake Fli...
base_phrases = "\n**** ahead\nBe wary of ****\nTry ****\nNeed ****\nImminent ****...\nWeakness:****\n****\n****?\nGood Luck\nI did it!\nHere!\nI can't take this...\nPraise the Sun!\n".strip().split('\n') fill_phrases = '\nEnemy\nTough enemy\nHollow\nSoldier\nKnight\nSniper\nCaster\nGiant\nSkeleton\nGhost\nBug\nPoison b...
def verbose_on(*args, **kwargs): """ dumb wrapper for print, see verbose_off and verbose """ print(*args, **kwargs) def verbose_off(*args, **kwargs): """ dummy function provides alternative to verbose_off """ _ = args, kwargs # dumb way of doing optional verbose output, see verbose...
def verbose_on(*args, **kwargs): """ dumb wrapper for print, see verbose_off and verbose """ print(*args, **kwargs) def verbose_off(*args, **kwargs): """ dummy function provides alternative to verbose_off """ _ = (args, kwargs) verbose = verbose_off
def jumps(lines, part2): a = 0 steps = 0 while a < len(lines): val = lines[a] if part2 and val > 2: lines[a] = lines[a] - 1 else: lines[a] += 1 a += val steps += 1 return steps lines = [] with open("inputs/5.txt") as f: for line in f:...
def jumps(lines, part2): a = 0 steps = 0 while a < len(lines): val = lines[a] if part2 and val > 2: lines[a] = lines[a] - 1 else: lines[a] += 1 a += val steps += 1 return steps lines = [] with open('inputs/5.txt') as f: for line in f: ...
def digit_stack(commands): value, stack = 0, [] for cmd in commands: if ' ' in cmd: stack.append(int(cmd[-1])) elif stack: value += stack[-1] if cmd == 'PEEK' else stack.pop() return value
def digit_stack(commands): (value, stack) = (0, []) for cmd in commands: if ' ' in cmd: stack.append(int(cmd[-1])) elif stack: value += stack[-1] if cmd == 'PEEK' else stack.pop() return value
print("Format is fghjstei:t:____n") print("Letters to ignore : Letters to include (yellow) : Letters correctly placed (green)") clue = input("What's the clue? ").split(':') #clue = "arosearose::_____".split(':') ignore = clue[0] use = clue[1] placed = clue[2] print(ignore, use, placed, " criteria letters.") with open...
print('Format is fghjstei:t:____n') print('Letters to ignore : Letters to include (yellow) : Letters correctly placed (green)') clue = input("What's the clue? ").split(':') ignore = clue[0] use = clue[1] placed = clue[2] print(ignore, use, placed, ' criteria letters.') with open('5letterwords.txt', 'r') as f: word...
class Product: def __init__(self, name, price, recipe): self.name = name self.price = price self.recipe = recipe def get_price(self): return self.price def make(self): print(self.recipe) class CashBox: def __init__(self): self.credit = 0 #why do i ...
class Product: def __init__(self, name, price, recipe): self.name = name self.price = price self.recipe = recipe def get_price(self): return self.price def make(self): print(self.recipe) class Cashbox: def __init__(self): self.credit = 0 self....
#TESTS is a dict with all you tests. #Keys for this will be categories' names. #Each test is dict with # "input" -- input data for user function # "answer" -- your right answer # "explanation" -- not necessary key, it's using for additional info in animation. TESTS = { "1. Small By Hand 1 (Example)": [ { ...
tests = {'1. Small By Hand 1 (Example)': [{'input': [5, [[1, 5], [11, 15], [2, 14], [21, 25]]], 'answer': 1, 'explanation': [25, [5]]}, {'input': [6, [[1, 5], [11, 15], [2, 14], [21, 25]]], 'answer': 2, 'explanation': [25, [5, 10]]}, {'input': [11, [[1, 5], [11, 15], [2, 14], [21, 25]]], 'answer': 3, 'explanation': [25...
# -*- coding: utf-8 -*- """ Created on Fri Feb 2 12:37:51 2018 @author: User """ def graph(src, dest): paths = {} paths['A'] = ['A', 'B', 'C','D', 'E', 'F', 'G'] paths['B'] = ['B', 'D', 'F', 'G'] for key, value in paths.items(): if src in key: if dest in value: ...
""" Created on Fri Feb 2 12:37:51 2018 @author: User """ def graph(src, dest): paths = {} paths['A'] = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] paths['B'] = ['B', 'D', 'F', 'G'] for (key, value) in paths.items(): if src in key: if dest in value: print('link') ...
class Solution: def containsNearbyAlmostDuplicate(self, nums: List[int], k: int, t: int) -> bool: """ 0 1 2 3 [1,3,2,1] t = 2, k = 2 ^ num 8 t = 2 left = 8 - 2 = 6 right = 8 + 2 = 10 0 1 2 3 4 5 [5,10,10] ...
class Solution: def contains_nearby_almost_duplicate(self, nums: List[int], k: int, t: int) -> bool: """ 0 1 2 3 [1,3,2,1] t = 2, k = 2 ^ num 8 t = 2 left = 8 - 2 = 6 right = 8 + 2 = 10 0 1 2 3 4 5 [5,10,10] ...
height=4.5 h_inch=height*12 h_meter=(height*2.54)/100 print('Height is ',h_inch,'inch') print('Height is ',h_meter,'meter')
height = 4.5 h_inch = height * 12 h_meter = height * 2.54 / 100 print('Height is ', h_inch, 'inch') print('Height is ', h_meter, 'meter')
with open("advent5.txt", "r") as file: input_ = file.read().split('\n') row_ids = [] for seat in input_: rows = seat[:7] cols = seat[7:] row_range = range(128) for letter in rows: middle_index = len(row_range)//2 if letter == "F": row_range = row_range[:middle_index] ...
with open('advent5.txt', 'r') as file: input_ = file.read().split('\n') row_ids = [] for seat in input_: rows = seat[:7] cols = seat[7:] row_range = range(128) for letter in rows: middle_index = len(row_range) // 2 if letter == 'F': row_range = row_range[:middle_index] ...
# -*- coding: utf-8 -*- FILE_NAME = '.gitignore' def read_file(): """Read gitignore file and return its data. :return: gitignore data """ with open(FILE_NAME) as f: data = f.read() return data def write_file(data): """Write in gitignore file :param data: the data to be insert in...
file_name = '.gitignore' def read_file(): """Read gitignore file and return its data. :return: gitignore data """ with open(FILE_NAME) as f: data = f.read() return data def write_file(data): """Write in gitignore file :param data: the data to be insert in gitignore file """ ...
shepherd = "Mary" age = 32 stuff_in_string = "Shepherd {} is {} years old.".format(shepherd, age) print(stuff_in_string) shepherd = "Martha" age = 34 # Note f before first quote of string stuff_in_string = "Shepherd %s is %d years old." % (shepherd, age) print(stuff_in_string)
shepherd = 'Mary' age = 32 stuff_in_string = 'Shepherd {} is {} years old.'.format(shepherd, age) print(stuff_in_string) shepherd = 'Martha' age = 34 stuff_in_string = 'Shepherd %s is %d years old.' % (shepherd, age) print(stuff_in_string)
def dict_contains(child_dict, parent_dict): for key, value in child_dict.items(): if key not in parent_dict: return False if parent_dict[key] != value: return False return True
def dict_contains(child_dict, parent_dict): for (key, value) in child_dict.items(): if key not in parent_dict: return False if parent_dict[key] != value: return False return True
class Solution: def wordPattern(self, pattern: str, s: str) -> bool: words = s.split(' ') patternMap, wordMap = {}, {} if len(pattern) != len(words): return False for index, char in enumerate(pattern): if char in patternMap: if patternMap[char]...
class Solution: def word_pattern(self, pattern: str, s: str) -> bool: words = s.split(' ') (pattern_map, word_map) = ({}, {}) if len(pattern) != len(words): return False for (index, char) in enumerate(pattern): if char in patternMap: if patter...
#!/usr/bin/env python # # Copyright (c) 2015 Pavel Lazar pavel.lazar (at) gmail.com # # The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. ##################################################################### class ClickConfiguration(object): REQUIREMENTS_PATTERN = 'require(package "{package}");' ...
class Clickconfiguration(object): requirements_pattern = 'require(package "{package}");' def __init__(self, requirements=None, elements=None, connections=None): self.requirements = requirements or [] self.elements = elements or [] self.connections = connections or [] self._eleme...
scale = 1000000 prime_checker = [i for i in range(scale + 1)] prime_checker[1] = 0 for i in range(2, int(scale ** 0.5) + 1): if prime_checker[i] != 0: for j in range(2, (scale // i) + 1): prime_checker[i * j] = 0 for _ in range(int(input())): count = 0 k = int(input()) for a in ran...
scale = 1000000 prime_checker = [i for i in range(scale + 1)] prime_checker[1] = 0 for i in range(2, int(scale ** 0.5) + 1): if prime_checker[i] != 0: for j in range(2, scale // i + 1): prime_checker[i * j] = 0 for _ in range(int(input())): count = 0 k = int(input()) for a in range(2...
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Income, obj[9]: Bar, obj[10]: Coffeehouse, obj[11]: Restaurant20to50, obj[12]: Direction_same, obj[13]: Distance # {"feature": "Distance", "instances": ...
def find_decision(obj): if obj[13] > 1: if obj[7] > 7: if obj[2] <= 3: if obj[0] <= 1: if obj[4] <= 2: if obj[8] <= 5: return 'False' elif obj[8] > 5: if ob...
class User: ''' Class that generates new instances of Users ''' user_list=[] def __init__(self,username,password): self.username=username self.password=password def save_user(self): ''' save_user method saves user objects to the user_list ''' User.user_list.append(self) @classme...
class User: """ Class that generates new instances of Users """ user_list = [] def __init__(self, username, password): self.username = username self.password = password def save_user(self): """ save_user method saves user objects to the user_list """ User.us...
#!/usr/bin/env python # -*- coding: utf-8 -*- # vim: fenc=utf-8:et:ts=4:sts=4:sw=4:fdm=marker # Algorithm based on https://github.com/ogham/rust-term-grid/ which is MIT # licensed. """ A grid is an mutable datastructure whose items can be printed in a grid in such a way as to minimize the number of lines. """ class G...
""" A grid is an mutable datastructure whose items can be printed in a grid in such a way as to minimize the number of lines. """ class Grid(object): default_margin = ' ' "\n Arguments:\n items (list): List of strings to put in the grid. \n seperator (str): String seperating grid columns.\n ...
""" An unweighted, undirected node in a graph. """ class UnweightedNode: def __init__(self, data): self.data = data self.__neighbor_nodes = [] def add_neighbor(self, node): self.__neighbor_nodes.append(node) def get_neighbors_in_order(self): return self.__neighbor_nodes
""" An unweighted, undirected node in a graph. """ class Unweightednode: def __init__(self, data): self.data = data self.__neighbor_nodes = [] def add_neighbor(self, node): self.__neighbor_nodes.append(node) def get_neighbors_in_order(self): return self.__neighbor_nodes
# -*- coding: utf-8 -*- """ Created on Tue Jan 25 13:57:59 2022 @author: ranusingh1993 """
""" Created on Tue Jan 25 13:57:59 2022 @author: ranusingh1993 """
#deleting a element from list # deleting one or more element at same time from list is possible using the keyword del. It can also delete the list entirely. list_pri=[1,3,5,7,8,11,13,17,19,23] del list_pri[4] print(list_pri) #[1,3,5,7,11,13,17,19,23] del list_pri[0:9] print(list_pri) del list_pri print(list_pr...
list_pri = [1, 3, 5, 7, 8, 11, 13, 17, 19, 23] del list_pri[4] print(list_pri) del list_pri[0:9] print(list_pri) del list_pri print(list_pri)
# Category description for the widget registry NAME = "SOLEIL SRW Light Sources" DESCRIPTION = "Widgets for SOLEIL SRW" BACKGROUND = "#b8bcdb" ICON = "icons/source.png" PRIORITY = 210
name = 'SOLEIL SRW Light Sources' description = 'Widgets for SOLEIL SRW' background = '#b8bcdb' icon = 'icons/source.png' priority = 210
_base_ = '../htc/htc_r50_fpn_1x_coco_1280.py' # optimizer optimizer = dict(lr=0.005) model = dict( pretrained=\ './checkpoints/lesa_pretrained_imagenet/'+\ 'lesa_wrn50_pretrained/'+\ 'lesa_wrn50/'+\ 'checkpoint.pth', backbone=dict( type='ResNet', depth=50, num...
_base_ = '../htc/htc_r50_fpn_1x_coco_1280.py' optimizer = dict(lr=0.005) model = dict(pretrained='./checkpoints/lesa_pretrained_imagenet/' + 'lesa_wrn50_pretrained/' + 'lesa_wrn50/' + 'checkpoint.pth', backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(0, 1, 2, 3), frozen_stages=1, norm_cfg=dict(type='BN...
# -*- coding: utf-8 -*- def list_remove_duplicates(dup_list): """Remove duplicates from a list. Args: dup_list (list): List. Returns: list: Return a list of unique values. """ return list(set(dup_list))
def list_remove_duplicates(dup_list): """Remove duplicates from a list. Args: dup_list (list): List. Returns: list: Return a list of unique values. """ return list(set(dup_list))
class GitHubRequestException(BaseException): pass class GithubDecodeError(BaseException): pass
class Githubrequestexception(BaseException): pass class Githubdecodeerror(BaseException): pass
tests = int(input()) def solve(C, R): c = C//9 r = R//9 if not C%9 ==0: c += 1 if not R%9 == 0: r += 1 if c < r: return [0, c] else: return [1, r] for t in range(tests): C, R = map(int, input().split()) ans = solve(C, R) print(ans[0], ans[1])
tests = int(input()) def solve(C, R): c = C // 9 r = R // 9 if not C % 9 == 0: c += 1 if not R % 9 == 0: r += 1 if c < r: return [0, c] else: return [1, r] for t in range(tests): (c, r) = map(int, input().split()) ans = solve(C, R) print(ans[0], ans[1...
#!/usr/bin/env python3 s = input() i = 0 while i < len(s): print(s[i:]) i = i + 1
s = input() i = 0 while i < len(s): print(s[i:]) i = i + 1
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Exception handle. """
""" Exception handle. """
def greeting(name): print("Hello " + name + "!") def goodbye(name): print("Goodbye " + name + "!")
def greeting(name): print('Hello ' + name + '!') def goodbye(name): print('Goodbye ' + name + '!')
''' The Models folder consists of files representing trained/retrained models as part of build jobs, etc. The model names can be appropriately set as projectname_date_time or project_build_id (in case the model is created as part of build jobs). Another approach is to store the model files in a separate storage such as...
""" The Models folder consists of files representing trained/retrained models as part of build jobs, etc. The model names can be appropriately set as projectname_date_time or project_build_id (in case the model is created as part of build jobs). Another approach is to store the model files in a separate storage such as...
x=int(input("lungima saritura initiala")) n=int(input("numar sarituri pana scade")) p=int(input("cu cate procente scade")) m=int(input("numar sarituri totale")) s=0 for i in range (m): s+=x if i+1 == n: k=p*x//100 x-=k n*=2 print(s)
x = int(input('lungima saritura initiala')) n = int(input('numar sarituri pana scade')) p = int(input('cu cate procente scade')) m = int(input('numar sarituri totale')) s = 0 for i in range(m): s += x if i + 1 == n: k = p * x // 100 x -= k n *= 2 print(s)
# Number of classes N_CLASSES = 1000 # Root directory of the `MS-ASL` dataset _MSASL_DIR = 'D:/datasets/msasl' # Directory of the `MS-ASL` dataset specification files _MSASL_SPECS_DIR = f'{_MSASL_DIR}/specs' # Directory of the filtered `MS-ASL` dataset specification files _MSASL_FILTERED_SPECS_DIR = f'{_MSASL_DIR}/f...
n_classes = 1000 _msasl_dir = 'D:/datasets/msasl' _msasl_specs_dir = f'{_MSASL_DIR}/specs' _msasl_filtered_specs_dir = f'{_MSASL_DIR}/filtered_specs' _msasl_videos_dir = f'{_MSASL_DIR}/videos' _msasl_tf_records_dir = f'{_MSASL_DIR}/tf_records'
class StorageError(Exception): pass class RegistrationError(Exception): pass
class Storageerror(Exception): pass class Registrationerror(Exception): pass
class SetupMaster(object): def check_os(): if 'CentOS Linux' in platform.linux_distribution(): redhat_setup() else: debian_setup()
class Setupmaster(object): def check_os(): if 'CentOS Linux' in platform.linux_distribution(): redhat_setup() else: debian_setup()
''' A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. The answer is guaranteed to fit in a 32-bit integer. Example 1: Input: s = "12" Outp...
""" A message containing letters from A-Z is being encoded to numbers using the following mapping: 'A' -> 1 'B' -> 2 ... 'Z' -> 26 Given a non-empty string containing only digits, determine the total number of ways to decode it. The answer is guaranteed to fit in a 32-bit integer. Example 1: Input: s = "12" Outp...
class HandlerOperator: """Handler operator. """ def __init__(self, allow_fail=False, should_rerun=False): """Constructor. """ self.allow_fail = allow_fail self.should_rerun = should_rerun def execute(self, handler): """Execute. """ raise NotImple...
class Handleroperator: """Handler operator. """ def __init__(self, allow_fail=False, should_rerun=False): """Constructor. """ self.allow_fail = allow_fail self.should_rerun = should_rerun def execute(self, handler): """Execute. """ raise not_impl...
# -*- coding: utf-8 -*- """ Created on Wed Jan 13 09:51:45 2021 @author: Rakin Shahriar """ #h,m,s = map(int,input().split()) try: h,m,s = map(int,input().split()) if(h<12 and h>0 and m<60 and s<60): print((12-h),":",(60-m),":",(60-s)) elif(h==12): print(12,":",(60-m),":",(60-s)) else...
""" Created on Wed Jan 13 09:51:45 2021 @author: Rakin Shahriar """ try: (h, m, s) = map(int, input().split()) if h < 12 and h > 0 and (m < 60) and (s < 60): print(12 - h, ':', 60 - m, ':', 60 - s) elif h == 12: print(12, ':', 60 - m, ':', 60 - s) else: print('Sorry! Invalid inp...
def get_parameters(code_header): begin = -1 end = -1 for i in range(0, len(code_header)): if code_header[i] == '(': begin = i for i in reversed(range(0, len(code_header))): if code_header[i] == ')': end = i if begin == -1 or end == -1: parameter = None...
def get_parameters(code_header): begin = -1 end = -1 for i in range(0, len(code_header)): if code_header[i] == '(': begin = i for i in reversed(range(0, len(code_header))): if code_header[i] == ')': end = i if begin == -1 or end == -1: parameter = None...
class MockGetResponse(object): def __init__(self, text): self.text = text class MockSession(object): def get(self, url): if url.find('login') < 0: return MockGetResponse(""" <ajax_response_xml_root> <IF_ERRORPARAM>SUCC</IF_ERRORPARAM> ...
class Mockgetresponse(object): def __init__(self, text): self.text = text class Mocksession(object): def get(self, url): if url.find('login') < 0: return mock_get_response('\n <ajax_response_xml_root>\n <IF_ERRORPARAM>SUCC</IF_ERRORPARAM>\n ...
cmdlist = [ ("ViewerFramework","customizationCommands","setUserPreference",""" Command providing a GUI to allow the user to set available\n userPreference."""), ("ViewerFramework","customizationCommands","setOnAddObjectCommands","""Command to specify commands that have to be carried out when an object\n is added ...
cmdlist = [('ViewerFramework', 'customizationCommands', 'setUserPreference', ' Command providing a GUI to allow the user to set available\n userPreference.'), ('ViewerFramework', 'customizationCommands', 'setOnAddObjectCommands', 'Command to specify commands that have to be carried out when an object\n is added t...
class RenguMapPass: def __call__(self, obj: dict): return obj
class Rengumappass: def __call__(self, obj: dict): return obj
fiboarr=[0,1] def fibonacci(n): if n<=0: print("Invalid input") elif n<=len(fiboarr): return fiboarr[n-1] else: for i in range(len(fiboarr)-1,n-1): fiboarr.append(fiboarr[i]+fiboarr[i-1]) print(fiboarr) return fiboarr[n-1] print(fibonacci(10))
fiboarr = [0, 1] def fibonacci(n): if n <= 0: print('Invalid input') elif n <= len(fiboarr): return fiboarr[n - 1] else: for i in range(len(fiboarr) - 1, n - 1): fiboarr.append(fiboarr[i] + fiboarr[i - 1]) print(fiboarr) return fiboarr[n - 1] print(fibona...
dec = int(input("Enter any Number: ")) print (" The decimal value of" ,dec, "is:") print (bin(dec)," In binary.") print (oct(dec),"In octal.") print (hex(dec),"In hexadecimal.")
dec = int(input('Enter any Number: ')) print(' The decimal value of', dec, 'is:') print(bin(dec), ' In binary.') print(oct(dec), 'In octal.') print(hex(dec), 'In hexadecimal.')
__author__ = "Andrea de Marco <andrea.demarco@buongiorno.com>" __version__ = '0.2' __classifiers__ = [ 'Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', ...
__author__ = 'Andrea de Marco <andrea.demarco@buongiorno.com>' __version__ = '0.2' __classifiers__ = ['Development Status :: 4 - Beta', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: GNU General Public License (GPL)', 'Operating System :: OS Independent', 'Topic :: Internet :: WWW...
def of_codon(): pass def of_rna(): pass
def of_codon(): pass def of_rna(): pass
if __name__ == '__main__': a = int(input("Enter a number : ")) if sum([pow(int(d), 3) for d in str(a)]) == a: print(a, " is an armstrong number") else: print(a, " is not an armstrong number")
if __name__ == '__main__': a = int(input('Enter a number : ')) if sum([pow(int(d), 3) for d in str(a)]) == a: print(a, ' is an armstrong number') else: print(a, ' is not an armstrong number')
nums = list(map(int, input().split(' '))) odd_num_list = [num for num in nums if num % 2 == 1] print(len(odd_num_list))
nums = list(map(int, input().split(' '))) odd_num_list = [num for num in nums if num % 2 == 1] print(len(odd_num_list))
posActu = int(input()) nbVillages = int(input()) nbVillagesProches = 0 for i in range(nbVillages): posVillage = int(input()) diff = posActu - posVillage if (diff <= 50 and diff >= -50): nbVillagesProches += 1 print(nbVillagesProches)
pos_actu = int(input()) nb_villages = int(input()) nb_villages_proches = 0 for i in range(nbVillages): pos_village = int(input()) diff = posActu - posVillage if diff <= 50 and diff >= -50: nb_villages_proches += 1 print(nbVillagesProches)
###################################### ######### O(n^2) algorithm ######### ###################################### # def get_single_max_profit(prices: list[int]) -> int: # lowest = sys.maxsize # max_profit = 0 # for price in prices: # if price < lowest: # lowest = price # # pro...
class Solution: def max_profit(self, prices: list[int]) -> int: profits = [] max_profit = 0 current_min = prices[0] for price in prices: current_min = min(current_min, price) max_profit = max(max_profit, price - current_min) profits.append(max_pro...
# Copyright 2018 Johns Hopkins University (author: Daniel Povey) # Apache 2.0 class CoreConfig: """ A class to store certain configuration information that is needed by core parts of Waldo, and read and write this information from a config file on disk. """ def __init__(self): ...
class Coreconfig: """ A class to store certain configuration information that is needed by core parts of Waldo, and read and write this information from a config file on disk. """ def __init__(self): """ Initialize default config values. This is mainly just to illustrat...
child1 = {"name": "Emil", "year": 2004} child2 = {"name": "Tobias", "year": 2007} child3 = {"name": "Linus", "year": 2011} myfamily = {"child1": child1, "child2": child2, "child3": child3} print(myfamily)
child1 = {'name': 'Emil', 'year': 2004} child2 = {'name': 'Tobias', 'year': 2007} child3 = {'name': 'Linus', 'year': 2011} myfamily = {'child1': child1, 'child2': child2, 'child3': child3} print(myfamily)
async def test_clear_shopping_cart_should_be_a_success(client): resp = await client.post('/v1/shopping_cart/items', json={ 'id': '5', 'quantity': 2 }) assert resp.status == 201 assert (await resp.json()) == { 'id': '5', 'name': 'Playstation 5', 'price': 3000 ...
async def test_clear_shopping_cart_should_be_a_success(client): resp = await client.post('/v1/shopping_cart/items', json={'id': '5', 'quantity': 2}) assert resp.status == 201 assert await resp.json() == {'id': '5', 'name': 'Playstation 5', 'price': 3000} resp = await client.post('/v1/shopping_cart/items...
""" This is a lazy way to avoid opening a json, simply import this file to collect your BIDS sidecar templates instead. :param sidecar_template_full: a dictionary containing every field specified in the BIDS standard for PET imaging data :param sidecar_template_short: a dictionary containing only the required fields i...
""" This is a lazy way to avoid opening a json, simply import this file to collect your BIDS sidecar templates instead. :param sidecar_template_full: a dictionary containing every field specified in the BIDS standard for PET imaging data :param sidecar_template_short: a dictionary containing only the required fields i...
class Solution: def removeDuplicates(self, S: str) -> str: a = [] for i in S: if len(a) == 0: a.append(i) elif a[-1] == i: a.pop() else: a.append(i) return ''.join(str(i) for i in a)
class Solution: def remove_duplicates(self, S: str) -> str: a = [] for i in S: if len(a) == 0: a.append(i) elif a[-1] == i: a.pop() else: a.append(i) return ''.join((str(i) for i in a))
""" Copyright 2016 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
""" Copyright 2016 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software dist...
#!/usr/bin/env python h = 'Hello!' if __name__ == '__main__': print(h.upper())
h = 'Hello!' if __name__ == '__main__': print(h.upper())
# height: Number of edges in longest path from the node to a leaf node. # So, # height of a tree = height of root node # height of a tree with 1 node = 0 # depth: # depth is no of edges in path from root to that node # depth of root node = 0 class Node: def __init__(self, data) ...
class Node: def __init__(self, data) -> None: self.data = data self.left = None self.right = None def build_tree(self, data): if self.data == data: return elif data < self.data: if self.left: self.left.buildTree(data) ...
""" Author: Kagaya john Tutorial 14 : functions """ """ Python Functions A function is a block of code which only runs when it is called. You can pass data, known as parameters, into a function. A function can return data as a result. Creating a Function In Python a function is defined using the def keyword: E...
""" Author: Kagaya john Tutorial 14 : functions """ '\nPython Functions\nA function is a block of code which only runs when it is called.\n\nYou can pass data, known as parameters, into a function.\n\nA function can return data as a result.\n\nCreating a Function\nIn Python a function is defined using the def keywor...
# Implement cat and dog queue for animal shelter class AnimalShelter: def __init__(self) -> None: self.cats=[] self.dogs=[] def enqueue(self,animal,type): if type=='cat': self.cats.append(animal) else: self.dogs.append(animal) def dequeueCat(self): ...
class Animalshelter: def __init__(self) -> None: self.cats = [] self.dogs = [] def enqueue(self, animal, type): if type == 'cat': self.cats.append(animal) else: self.dogs.append(animal) def dequeue_cat(self): if len(self.cats) == 0: ...
class Solution: def isRectangleOverlap(self, rec1, rec2): """ :type rec1: List[int] :type rec2: List[int] :rtype: bool """ def isOverlap(x1, x2, x3, x4): if x1 == x3 and x2 == x4: return True elif x1 < x3 < x2 or x1 < x4 < x2 or...
class Solution: def is_rectangle_overlap(self, rec1, rec2): """ :type rec1: List[int] :type rec2: List[int] :rtype: bool """ def is_overlap(x1, x2, x3, x4): if x1 == x3 and x2 == x4: return True elif x1 < x3 < x2 or x1 < x4 < ...
#!/usr/bin/env python3 def pkcs7_padding(msg, block_size): padding_length = block_size - (len(msg) % block_size) if padding_length == 0: padding_length = block_size padding = bytes([padding_length] * padding_length) return msg + padding if __name__ == '__main__': print(pkcs7_padding(b'YELLOW S...
def pkcs7_padding(msg, block_size): padding_length = block_size - len(msg) % block_size if padding_length == 0: padding_length = block_size padding = bytes([padding_length] * padding_length) return msg + padding if __name__ == '__main__': print(pkcs7_padding(b'YELLOW SUBMARINE', 20))
class Solution: def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and not t2: return None if not t1 or not t2: return t1 or t2 t1.val += t2.val q = deque([(t1, t2)]) while q: n1, n2 = q.popleft() if n1.left...
class Solution: def merge_trees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and (not t2): return None if not t1 or not t2: return t1 or t2 t1.val += t2.val q = deque([(t1, t2)]) while q: (n1, n2) = q.popleft() if n...
"""This module contains data for UI menu items.""" # ============================================================================= # GLOBALS # ============================================================================= DEFAULT_VALUES = { "componentexport": False, "lightexport": "", "quantize": "half", ...
"""This module contains data for UI menu items.""" default_values = {'componentexport': False, 'lightexport': '', 'quantize': 'half', 'pfilter': '', 'priority': -1, 'sfilter': 'alpha', 'vextype': 'vector'} lightexport_menu_items = (('', 'No light exports'), ('per-light', 'Export variable for each light'), ('single', 'M...
def evenOdd(x): if (x % 2 == 0): print("even") else: print("odd") evenOdd(6) evenOdd(5) ####################### String ="Monerah Balhareth" print(String) ###################### def table(num): for x in range(1,11): print (num," * ", x,"=",num*x) table(19) ###################...
def even_odd(x): if x % 2 == 0: print('even') else: print('odd') even_odd(6) even_odd(5) string = 'Monerah Balhareth' print(String) def table(num): for x in range(1, 11): print(num, ' * ', x, '=', num * x) table(19) def f(x): return x / 0 try: print(f(5)) except ValueError:...
# -*- coding: utf-8 -*- #BEGIN_HEADER #END_HEADER class RESKESearchDemo: ''' Module Name: RESKESearchDemo Module Description: A KBase module: RESKESearchDemo ''' ######## WARNING FOR GEVENT USERS ####### noqa # Since asynchronous IO can lead to methods - even the same method - # ...
class Reskesearchdemo: """ Module Name: RESKESearchDemo Module Description: A KBase module: RESKESearchDemo """ version = '0.0.1' git_url = 'https://github.com/kbaseapps/RESKESearchDemo' git_commit_hash = '8107c2de43886e7d6910585064044b84d349e94b' def __init__(self, config): ...
class LabeledBox: def __init__(self, x1: int, y1: int, x2: int, y2: int, label: str): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.label = label
class Labeledbox: def __init__(self, x1: int, y1: int, x2: int, y2: int, label: str): self.x1 = x1 self.y1 = y1 self.x2 = x2 self.y2 = y2 self.label = label
class BlockType: Empty = 1 << 0 OutBound = 1 << 1 # Wall = 2 RedApple = 1 << 2 BlueApple = 1 << 3 # Agents Self = 1 << 4 # RedAgent = 1 << 5 BlueAgent = 1 << 6 GreenAgent = 1 << 7 OrangeAgent = 1 << 8 PurpleAgent = 1 << 9 # Effects Punish = 1 << 20 # Num...
class Blocktype: empty = 1 << 0 out_bound = 1 << 1 red_apple = 1 << 2 blue_apple = 1 << 3 self = 1 << 4 blue_agent = 1 << 6 green_agent = 1 << 7 orange_agent = 1 << 8 purple_agent = 1 << 9 punish = 1 << 20
class UserController(object): def getUser(self): return "GET user" def postUser(self): return "POST user"
class Usercontroller(object): def get_user(self): return 'GET user' def post_user(self): return 'POST user'
""" Iterables vs Iterator - Iterables is an object implements the iterable protocol + __iter__ => return the iterator - Iterator is an object implements the iterator protocol + __iter__ => return itself + __next__ => return next item or StopIteration - This solves the exhaustion problem """ class Cities: ...
""" Iterables vs Iterator - Iterables is an object implements the iterable protocol + __iter__ => return the iterator - Iterator is an object implements the iterator protocol + __iter__ => return itself + __next__ => return next item or StopIteration - This solves the exhaustion problem """ class Cities: ...
class AtlasData: texture_dict = None border = 1 width = 0 height = 0 color_mode = "" file_type = "" name = "" def __init__(self, name, width=512, height=512, border=1, color_mode="RGBA", file_type="tga"): self.texture_dict = {} self.name = name self.border = bord...
class Atlasdata: texture_dict = None border = 1 width = 0 height = 0 color_mode = '' file_type = '' name = '' def __init__(self, name, width=512, height=512, border=1, color_mode='RGBA', file_type='tga'): self.texture_dict = {} self.name = name self.border = bord...
# Armstrong Number - Burak Karabey def armstrong(x): input_number = list(str(x)) i = 0 u = 0 while i < len(input_number): u = u + (int(input_number[i]) ** len(input_number)) i += 1 u = str(u) armstrong_number = [] for n in range(0, len(u)): armstrong_number.append(u[n...
def armstrong(x): input_number = list(str(x)) i = 0 u = 0 while i < len(input_number): u = u + int(input_number[i]) ** len(input_number) i += 1 u = str(u) armstrong_number = [] for n in range(0, len(u)): armstrong_number.append(u[n]) if input_number == armstrong_n...
class Solution: def swapNodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: # Find kth node from left l = r = head for _ in range(k-1): l = l.next # Find kth node from right # by finding tail node tail = l while tail.next: ...
class Solution: def swap_nodes(self, head: Optional[ListNode], k: int) -> Optional[ListNode]: l = r = head for _ in range(k - 1): l = l.next tail = l while tail.next: (r, tail) = (r.next, tail.next) (l.val, r.val) = (r.val, l.val) return head
#!/usr/bin/env python NAME = 'Sabre Firewall (Sabre)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return _, responsepage = r if any(i in responsepage for i in (b'dxsupport@sabre.com', b'<title>Application Firewall Error</title>', ...
name = 'Sabre Firewall (Sabre)' def is_waf(self): for attack in self.attacks: r = attack(self) if r is None: return (_, responsepage) = r if any((i in responsepage for i in (b'dxsupport@sabre.com', b'<title>Application Firewall Error</title>', b'email link will automatic...
""" Views for statusapp. Views are divided into views that dynamically draw graphs, views that create .csv files, and views that render a webpage to response. """
""" Views for statusapp. Views are divided into views that dynamically draw graphs, views that create .csv files, and views that render a webpage to response. """
''' this module contains functions needed to access flood risks''' # this function checks if current water level is over the threshold def stations_level_over_threshold(stations, tol): list_of_stations= [] for station in stations: water_level= station.relative_water_level() if water_level != None...
""" this module contains functions needed to access flood risks""" def stations_level_over_threshold(stations, tol): list_of_stations = [] for station in stations: water_level = station.relative_water_level() if water_level != None: if water_level >= tol: s = (statio...
#!/usr/bin/env python3 def main(): with open("./inputs/day2.txt") as file: raw_input = file.read() instructions = parse_intcode_into_instructions(raw_input) mutated_instructions = run_instructions(instructions) print(get_answer(mutated_instructions)) def parse_intcode_into_instructions(raw_b...
def main(): with open('./inputs/day2.txt') as file: raw_input = file.read() instructions = parse_intcode_into_instructions(raw_input) mutated_instructions = run_instructions(instructions) print(get_answer(mutated_instructions)) def parse_intcode_into_instructions(raw_body): body = restore_s...
def binary_search(nums,l,r,val)->int: if nums[0] > val: return 0 elif nums[r] < val: return r+1 elif r>=l: mid = l+ (r-l)//2 if nums[mid] == val: return mid elif nums[mid] > val: return binary_search(nums,l,mid-1,val) else: ...
def binary_search(nums, l, r, val) -> int: if nums[0] > val: return 0 elif nums[r] < val: return r + 1 elif r >= l: mid = l + (r - l) // 2 if nums[mid] == val: return mid elif nums[mid] > val: return binary_search(nums, l, mid - 1, val) ...
def main(): a = {1, 2, 3, 4} b = {4, 5, 6} b.add(7) print(a.union(b)) print(a.intersection(b)) print(a.difference(b)) print(a.symmetric_difference(b)) print(a.issubset(b)) print(a.issuperset(b)) if __name__ == '__main__': main()
def main(): a = {1, 2, 3, 4} b = {4, 5, 6} b.add(7) print(a.union(b)) print(a.intersection(b)) print(a.difference(b)) print(a.symmetric_difference(b)) print(a.issubset(b)) print(a.issuperset(b)) if __name__ == '__main__': main()
# vim: expandtab:tabstop=4:shiftwidth=4 # pylint: skip-file # pylint: disable=too-many-instance-attributes class OCLabel(OpenShiftCLI): ''' Class to wrap the oc command line tools ''' # pylint allows 5 # pylint: disable=too-many-arguments def __init__(self, name, name...
class Oclabel(OpenShiftCLI): """ Class to wrap the oc command line tools """ def __init__(self, name, namespace, kind, kubeconfig, labels=None, selector=None, verbose=False): """ Constructor for OCLabel """ super(OCLabel, self).__init__(namespace, kubeconfig) self.name = name se...
""" @file msg.py @author Bowen Zheng @University of California Riverside @date 2016-10-27 This file defines messages for intersection management """ class Message(object): """The base calss for all messages""" def __init__(self, sender, sendTime, resource, time_range, send_type): se...
""" @file msg.py @author Bowen Zheng @University of California Riverside @date 2016-10-27 This file defines messages for intersection management """ class Message(object): """The base calss for all messages""" def __init__(self, sender, sendTime, resource, time_range, send_type): self.sender =...
name = "opensubdiv" version = "3.2.0" build_requires = [ 'glfw-3' ] requires = [ 'tbb-4' ] variants = [ ["platform-linux", "arch-x86_64", "os-CentOS-7"] ] tools = [ 'far_perf' 'far_regression' 'hbr_baseline' 'hbr_regression' 'stringify' 'tutorials' ] uuid = "opensubdiv" def c...
name = 'opensubdiv' version = '3.2.0' build_requires = ['glfw-3'] requires = ['tbb-4'] variants = [['platform-linux', 'arch-x86_64', 'os-CentOS-7']] tools = ['far_perffar_regressionhbr_baselinehbr_regressionstringifytutorials'] uuid = 'opensubdiv' def commands(): env.PATH.append('{root}/bin') env.LD_LIBRARY_PA...