content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: def newInteger(self, n): base9 = "" while n: base9 += str(n % 9) n //= 9 return int(base9[::-1])
class Solution: def new_integer(self, n): base9 = '' while n: base9 += str(n % 9) n //= 9 return int(base9[::-1])
#!/usr/bin/env python class Dog: def identify(self): return "jims dog"
class Dog: def identify(self): return 'jims dog'
# Time: O(n^2) # Space: O(n) class Solution(object): def largestDivisibleSubset(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] nums.sort() dp = [1] * len(nums) prev = [-1] * len(nums) largest_...
class Solution(object): def largest_divisible_subset(self, nums): """ :type nums: List[int] :rtype: List[int] """ if not nums: return [] nums.sort() dp = [1] * len(nums) prev = [-1] * len(nums) largest_idx = 0 for i in rang...
# # https://rosettacode.org/wiki/Topological_sort#Python # ############### # # https://codeforces.com/blog/entry/16823 # ############### # https://www.python.org/doc/essays/graphs/ graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], ...
graph = {'A': ['B', 'C'], 'B': ['C', 'D'], 'C': ['D'], 'D': ['C'], 'E': ['F'], 'F': ['C']} graph = {'C': ['D', 'B', 'A'], 'E': ['C'], 'D': ['B'], 'B': ['A'], 'A': []} def find_path(graph, start, end, path=None): if path is None: path = [] path += [start] if start == end: return path if ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def maxPathSum(self, root): """ :type root: TreeNode :rtype: int """ ans = float('-inf') ...
class Solution: def max_path_sum(self, root): """ :type root: TreeNode :rtype: int """ ans = float('-inf') def helper(node): nonlocal ans if not node: return 0 l = helper(node.left) r = helper(node.righ...
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. https://stackoverflow.com/a/11326230 """ return "/".join(map(lambda x: str(x).strip('/').rstrip('/'), args))
def urljoin(*args): """ Joins given arguments into a url. Trailing but not leading slashes are stripped for each argument. https://stackoverflow.com/a/11326230 """ return '/'.join(map(lambda x: str(x).strip('/').rstrip('/'), args))
a + b c - d e * f g / h i % j k // l m ** n o | p q & r s ^ t u << v w >> x
a + b c - d e * f g / h i % j k // l m ** n o | p q & r s ^ t u << v w >> x
def _1(): for row in range(7): for col in range(7): if (col==3 or row==6) or (row<3 and row+col==2): print("*",end="") else: print(end=" ") print()
def _1(): for row in range(7): for col in range(7): if (col == 3 or row == 6) or (row < 3 and row + col == 2): print('*', end='') else: print(end=' ') print()
CACHEDOPS = "cachedoperations" SLICEBUILDERS = "slicebuilders" GENERIC = "slicebuilder" SUBPOPULATION = "subpopulation" ATTACK = "attack" AUGMENTATION = "augmentation" TRANSFORMATION = "transformation" CURATION = "curated"
cachedops = 'cachedoperations' slicebuilders = 'slicebuilders' generic = 'slicebuilder' subpopulation = 'subpopulation' attack = 'attack' augmentation = 'augmentation' transformation = 'transformation' curation = 'curated'
BINANCE_SUPPORTED_QUOTE_ASSET = { 'BTC', 'ETH', 'USDT', 'BNB' } class SupportedQuoteAsset: @staticmethod def getQuoteAsset(symbol, supportedAssetMap): for val in supportedAssetMap: if symbol.endswith(val): return val return None
binance_supported_quote_asset = {'BTC', 'ETH', 'USDT', 'BNB'} class Supportedquoteasset: @staticmethod def get_quote_asset(symbol, supportedAssetMap): for val in supportedAssetMap: if symbol.endswith(val): return val return None
names:{ "000000": "Black", "000080": "Navy Blue", "0000C8": "Dark Blue", "0000FF": "Blue", "000741": "Stratos", "001B1C": "Swamp", "002387": "Resolution Blue", "002900": "Deep Fir", "002E20": "Burnham", "002FA7": "International Klein Blue", "003153": "Prussian Blue", "003366": "Midnight Blue", "003399": "Smalt", "00353...
names: {'000000': 'Black', '000080': 'Navy Blue', '0000C8': 'Dark Blue', '0000FF': 'Blue', '000741': 'Stratos', '001B1C': 'Swamp', '002387': 'Resolution Blue', '002900': 'Deep Fir', '002E20': 'Burnham', '002FA7': 'International Klein Blue', '003153': 'Prussian Blue', '003366': 'Midnight Blue', '003399': 'Smalt', '00353...
class RenderTargetType: """ This stores the possible types of targets beeing able to be attached to a RenderTarget. Python does not support enums (yet) so this is a class. """ Color = "color" Depth = "depth" Aux0 = "aux0" Aux1 = "aux1" Aux2 = "aux2" Aux3 = "aux3" All = ["dep...
class Rendertargettype: """ This stores the possible types of targets beeing able to be attached to a RenderTarget. Python does not support enums (yet) so this is a class. """ color = 'color' depth = 'depth' aux0 = 'aux0' aux1 = 'aux1' aux2 = 'aux2' aux3 = 'aux3' all = ['depth', ...
""" Subarray Sum Equals K Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 Constraints: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000...
""" Subarray Sum Equals K Given an array of integers nums and an integer k, return the total number of continuous subarrays whose sum equals to k. Example 1: Input: nums = [1,1,1], k = 2 Output: 2 Example 2: Input: nums = [1,2,3], k = 3 Output: 2 Constraints: 1 <= nums.length <= 2 * 104 -1000 <= nums[i] <= 1000...
###### Config for test ###: Variables ggtrace_cpu = [ "data/formatted/", # pd.readfilepath [1], # usecols trong pd False, # multi_output None, # output_idx "cpu/", # path_save_result ] ggtrace_ram = [ "data/formatted/",...
ggtrace_cpu = ['data/formatted/', [1], False, None, 'cpu/'] ggtrace_ram = ['data/formatted/', [2], False, None, 'ram/'] ggtrace_multi_cpu = ['data/formatted/', [1, 2], False, 0, 'multi_cpu/'] ggtrace_multi_ram = ['data/formatted/', [1, 2], False, 1, 'multi_ram/'] giang1 = ['data/formatted/giang/', [3], False, None, 'gi...
# pylint: disable-msg=R0903 """check use of super""" __revision__ = None class Aaaa: """old style""" def hop(self): """hop""" super(Aaaa, self).hop() def __init__(self): super(Aaaa, self).__init__() class NewAaaa(object): """old style""" def hop(self): """hop""" ...
"""check use of super""" __revision__ = None class Aaaa: """old style""" def hop(self): """hop""" super(Aaaa, self).hop() def __init__(self): super(Aaaa, self).__init__() class Newaaaa(object): """old style""" def hop(self): """hop""" super(NewAaaa, self)...
competitor1 = int(input()) competitor2 = int(input()) competitor3 = int(input()) sum_sec = competitor1 + competitor2 + competitor3 minutes = sum_sec // 60 sec = sum_sec % 60 if sec < 10: print(f"{minutes}:0{sec}") else: print(f"{minutes}:{sec}")
competitor1 = int(input()) competitor2 = int(input()) competitor3 = int(input()) sum_sec = competitor1 + competitor2 + competitor3 minutes = sum_sec // 60 sec = sum_sec % 60 if sec < 10: print(f'{minutes}:0{sec}') else: print(f'{minutes}:{sec}')
def extractUntunedTranslation(item): """ """ title = item['title'].replace(' III(', ' vol 3 (').replace(' III:', ' vol 3:').replace(' II:', ' vol 2:').replace(' I:', ' vol 1:').replace(' IV:', ' vol 4:').replace( ' V:', ' vol 5:') vol, chp, frag, postfix = extractVolChapterFragmentPostfix(title) if not (chp ...
def extract_untuned_translation(item): """ """ title = item['title'].replace(' III(', ' vol 3 (').replace(' III:', ' vol 3:').replace(' II:', ' vol 2:').replace(' I:', ' vol 1:').replace(' IV:', ' vol 4:').replace(' V:', ' vol 5:') (vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(title) ...
class Solution: def toLowerCase(self, string): return string.lower()
class Solution: def to_lower_case(self, string): return string.lower()
# Rouge Highlighter token test - Generic Traceback def test(): print(unknown_test_var) test()
def test(): print(unknown_test_var) test()
# -*- coding: utf-8 -*- """ Created on Mon Dec 9 16:12:01 2019 @author: NOTEBOOK """ def main(): purchase = float(input("Enter the total amount of purchase: ")) tax(purchase) def tax(pur): sales_tax = pur * 0.04 county_tax = pur * 0.02 total_tax = sales_tax + county_tax total = pur +...
""" Created on Mon Dec 9 16:12:01 2019 @author: NOTEBOOK """ def main(): purchase = float(input('Enter the total amount of purchase: ')) tax(purchase) def tax(pur): sales_tax = pur * 0.04 county_tax = pur * 0.02 total_tax = sales_tax + county_tax total = pur + total_tax print('Purchase =...
# -*- coding: utf-8 -*- """ 1466. Reorder Routes to Make All Paths Lead to the City Zero There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one dir...
""" 1466. Reorder Routes to Make All Paths Lead to the City Zero There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are ...
# err_raise.py def foo(s): n = int(s) if n == 0: raise ValueError('invalid value: %s' % s) return 10 / n def bar(): try: foo('0') except ValueError as e: print('ValueError!') bar()
def foo(s): n = int(s) if n == 0: raise value_error('invalid value: %s' % s) return 10 / n def bar(): try: foo('0') except ValueError as e: print('ValueError!') bar()
# Search in Rotated Sorted Array II 81 # ttungl@gmail.com class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ # use binary search # tricky part is to increase the left until left=mid and nums[mid...
class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: bool """ (left, right) = (0, len(nums) - 1) while left <= right: mid = left + (right - left) / 2 if nums[mid] == target: ...
# -*- coding: utf-8 -*- # @Time: 2020/4/13 18:49 # @Author: GraceKoo # @File: 96_unique-binary-search-trees.py # @Desc: https://leetcode-cn.com/problems/unique-binary-search-trees/ class Solution: def numTrees(self, n: int) -> int: if n < 0: return 0 dp = [0 for _ in range(n + 1)] ...
class Solution: def num_trees(self, n: int) -> int: if n < 0: return 0 dp = [0 for _ in range(n + 1)] dp[0] = 1 dp[1] = 1 for i in range(2, n + 1): for j in range(i): dp[i] += dp[j] * dp[i - j - 1] return dp[-1] so = solution()...
class Load: elapsedTime = 0 powerUsage = 0.0 csvName = "" id = 0 isBackgroundLoad = None def __init__(self, elapsed_time, power_usage, csv_path): self.elapsedTime = int(elapsed_time) self.powerUsage = float(power_usage) self.csvName = csv_path.split("\\")[-1] # csvNa...
class Load: elapsed_time = 0 power_usage = 0.0 csv_name = '' id = 0 is_background_load = None def __init__(self, elapsed_time, power_usage, csv_path): self.elapsedTime = int(elapsed_time) self.powerUsage = float(power_usage) self.csvName = csv_path.split('\\')[-1] ...
# -*- coding: utf-8 -*- # Copyright (c) 2014-2019 Dontnod Entertainment # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use,...
""" Nimp subcommands declarations """ __all__ = ['build', 'check', 'commandlet', 'dev', 'download_fileset', 'fileset', 'p4', 'package', 'run', 'symbol_server', 'update_symbol_server', 'upload', 'upload_fileset']
def count1(x): count = 0 for i in range(len(x)): if x[i:i + 2] == 'ba': count += 1 return count def main(): print(count1('baba')) print(count1('aba')) print(count1('baaabab')) print(count1('abc')) print(count1('goodbye')) print(count1('a')) print(count1('ba'...
def count1(x): count = 0 for i in range(len(x)): if x[i:i + 2] == 'ba': count += 1 return count def main(): print(count1('baba')) print(count1('aba')) print(count1('baaabab')) print(count1('abc')) print(count1('goodbye')) print(count1('a')) print(count1('ba')...
def name_match(name, strict=True): """ Perform a GBIF name matching using the species and genus names Parameters ---------- species_name: str name of the species to request more information genus_name: str name of the genus of the species strict: boolean define i...
def name_match(name, strict=True): """ Perform a GBIF name matching using the species and genus names Parameters ---------- species_name: str name of the species to request more information genus_name: str name of the genus of the species strict: boolean define i...
_SERVICES = ["xcube_gen", "xcube_serve", "xcube_geodb"] def get_services(): return _SERVICES
_services = ['xcube_gen', 'xcube_serve', 'xcube_geodb'] def get_services(): return _SERVICES
def min_fee(print_page_list): sum_ = 0 prev = 0 for i in sorted(print_page_list): sum_ += (prev + i) prev += i return sum_ if __name__ == "__main__": print(min_fee([6, 11, 4, 1])) print(min_fee([3, 2, 1])) print(min_fee([3, 1, 4, 3, 2])) print(min_fee([8, 4, 2, 3, 9, 23...
def min_fee(print_page_list): sum_ = 0 prev = 0 for i in sorted(print_page_list): sum_ += prev + i prev += i return sum_ if __name__ == '__main__': print(min_fee([6, 11, 4, 1])) print(min_fee([3, 2, 1])) print(min_fee([3, 1, 4, 3, 2])) print(min_fee([8, 4, 2, 3, 9, 23, 6,...
SCREEN_WIDTH = 640 SCREEN_HEIGHT = 480 NUMBER_OF_POINTS = 4 POINT_WIDTH = 4.0 CIRCLE_BORDER_WIDTH = 1 SWEEP_LINE_OFFSET = 0.001
screen_width = 640 screen_height = 480 number_of_points = 4 point_width = 4.0 circle_border_width = 1 sweep_line_offset = 0.001
""" Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). Example For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". """ def alphabeticShift(inputString): ...
""" Given a string, your task is to replace each of its characters by the next one in the English alphabet; i.e. replace a with b, replace b with c, etc (z would be replaced by a). Example For inputString = "crazy", the output should be alphabeticShift(inputString) = "dsbaz". """ def alphabetic_shift(inputString): ...
''' The array-form of an integer num is an array representing its digits in left to right order. For example, for num = 1321, the array form is [1,3,2,1]. Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. Example 1: Input: num = [1,2,0,0], k = 34 Output: [1,2...
""" The array-form of an integer num is an array representing its digits in left to right order. For example, for num = 1321, the array form is [1,3,2,1]. Given num, the array-form of an integer, and an integer k, return the array-form of the integer num + k. Example 1: Input: num = [1,2,0,0], k = 34 Output: [1,2...
""" Put a list of postgres supported functions """ pgf = ( "round", "min", )
""" Put a list of postgres supported functions """ pgf = ('round', 'min')
""" Simple DXF Export by Simon Greenwold. Press the 'R' key to export a DXF file. """ add_library('dxf') # import processing.dxf.* record = False def setup(): size(400, 400, P3D) noStroke() sphereDetail(12) def draw(): global record if record: beginRaw(DXF, "output.dxf") # Start record...
""" Simple DXF Export by Simon Greenwold. Press the 'R' key to export a DXF file. """ add_library('dxf') record = False def setup(): size(400, 400, P3D) no_stroke() sphere_detail(12) def draw(): global record if record: begin_raw(DXF, 'output.dxf') lights() background(0) trans...
def convert_sample_to_shot_coQA(sample, with_knowledge=None): prefix = f"{sample['meta']}\n" for turn in sample["dialogue"]: prefix += f"Q: {turn[0]}" +"\n" if turn[1] == "": prefix += f"A:" return prefix else: prefix += f"A: {turn[1]}" +"\n" re...
def convert_sample_to_shot_co_qa(sample, with_knowledge=None): prefix = f"{sample['meta']}\n" for turn in sample['dialogue']: prefix += f'Q: {turn[0]}' + '\n' if turn[1] == '': prefix += f'A:' return prefix else: prefix += f'A: {turn[1]}' + '\n' re...
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def bstFromPreorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ if...
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def bst_from_preorder(self, preorder): """ :type preorder: List[int] :rtype: TreeNode """ if not preorder: return ...
def ensureUtf(s, encoding='utf8'): """Converts input to unicode if necessary. If `s` is bytes, it will be decoded using the `encoding` parameters. This function is used for preprocessing /source/ and /filename/ arguments to the builtin function `compile`. """ # In Python2, str == bytes. # In...
def ensure_utf(s, encoding='utf8'): """Converts input to unicode if necessary. If `s` is bytes, it will be decoded using the `encoding` parameters. This function is used for preprocessing /source/ and /filename/ arguments to the builtin function `compile`. """ if type(s) == bytes: return...
#!/usr/bin/python # encoding: utf-8 """ @author: liaozhicheng.cn@163.com @date: 2016/7/24 """
""" @author: liaozhicheng.cn@163.com @date: 2016/7/24 """
class File: def criar(nomeArquivo): nomeArquivo = input('NOME DO ARQUIVO= ') arquivo = open(nomeArquivo,'x') arquivo.close def escrever(texto): nomeArquivo = input('NOME DO ARQUIVO= ') arquivo = open(nomeArquivo,'w') file = File() file.criar() file.escrever(input())
class File: def criar(nomeArquivo): nome_arquivo = input('NOME DO ARQUIVO= ') arquivo = open(nomeArquivo, 'x') arquivo.close def escrever(texto): nome_arquivo = input('NOME DO ARQUIVO= ') arquivo = open(nomeArquivo, 'w') file = file() file.criar() file.escrever(input())
# -*- coding: utf-8 -*- """ Created on Tue Apr 14 14:44:48 2020 @author: marcu """
""" Created on Tue Apr 14 14:44:48 2020 @author: marcu """
#--------------------------------------------------------------- # QUEUE (V2) #--------------------------------------------------------------- # V0 class Queue(object): def __init__(self, limit = 10): self.queue = [] self.front = None self.rear = None self.limit = limit self...
class Queue(object): def __init__(self, limit=10): self.queue = [] self.front = None self.rear = None self.limit = limit self.size = 0 def __str__(self): return ' '.join([str(i) for i in self.queue]) def is_empty(self): return self.size <= 0 de...
def count_sevens(*args): return args.count(7) nums = [90,1,35,67,89,20,3,1,2,3,4,5,6,9,34,46,57,68,79,12,23,34,55,1,90,54,34,76,8,23,34,45,56,67,78,12,23,34,45,56,67,768,23,4,5,6,7,8,9,12,34,14,15,16,17,11,7,11,8,4,6,2,5,8,7,10,12,13,14,15,7,8,7,7,345,23,34,45,56,67,1,7,3,6,7,2,3,4,5,6,7,8,9,8,7,6,5,4,2,1,2,3,4,5,...
def count_sevens(*args): return args.count(7) nums = [90, 1, 35, 67, 89, 20, 3, 1, 2, 3, 4, 5, 6, 9, 34, 46, 57, 68, 79, 12, 23, 34, 55, 1, 90, 54, 34, 76, 8, 23, 34, 45, 56, 67, 78, 12, 23, 34, 45, 56, 67, 768, 23, 4, 5, 6, 7, 8, 9, 12, 34, 14, 15, 16, 17, 11, 7, 11, 8, 4, 6, 2, 5, 8, 7, 10, 12, 13, 14, 15, 7, 8, ...
class WebSocketDefine: # Uri = "wss://dstream.binance.com/ws" # testnet Uri = "wss://dstream.binancefuture.com/ws" # testnet new spec # Uri = "wss://sdstream.binancefuture.com/ws" class RestApiDefine: # Url = "https://dapi.binance.com" # testnet Url = "https://testnet.binanc...
class Websocketdefine: uri = 'wss://dstream.binancefuture.com/ws' class Restapidefine: url = 'https://testnet.binancefuture.com'
""" CLI tool to introspect flake8 plugins and their codes. """ __version__ = '0.1.1'
""" CLI tool to introspect flake8 plugins and their codes. """ __version__ = '0.1.1'
class NullLogger: level_name = None def remove(self, handler_id=None): # pragma: no cover pass def add(self, sink, **kwargs): # pragma: no cover pass def disable(self, name): # pragma: no cover pass def enable(self, name): # pragma: no cover pass def crit...
class Nulllogger: level_name = None def remove(self, handler_id=None): pass def add(self, sink, **kwargs): pass def disable(self, name): pass def enable(self, name): pass def critical(self, __message, *args, **kwargs): pass def debug(self, __mess...
"""Custom exceptions.""" class MFilesException(Exception): """M-Files base exception."""
"""Custom exceptions.""" class Mfilesexception(Exception): """M-Files base exception."""
class SomeCls(): """ class SomeCls """ def __init__(self): pass def returns_true(self): """ returns_true """ return True
class Somecls: """ class SomeCls """ def __init__(self): pass def returns_true(self): """ returns_true """ return True
# ------------------------------------------------------------------------------ # CONFIG (Change propriately) # ------------------------------------------------------------------------------ # Required token = "please input" post_channel_id = "please input" target_days = 1 # The target range is ...
token = 'please input' post_channel_id = 'please input' target_days = 1 target_hours = 0 target_minutes = 0 tz_hours = +9 tz_name = 'JST' exclude_channel_id = ['if needed, please input'] exclude_users_id = ['if needed, please input'] exclude_message_subtype = ['if needed, please input']
def facto(a): fact=1 while(a>0): fact*=a a-=1 return fact
def facto(a): fact = 1 while a > 0: fact *= a a -= 1 return fact
def is_prime(n: int) -> bool: if n < 2: return False elif n == 2: return True for i in range(2, n): if n % i == 0: return False return True if __name__ == '__main__': m = int(input()) n = int(input()) prime_sum = 0 prime_min = None for i in rang...
def is_prime(n: int) -> bool: if n < 2: return False elif n == 2: return True for i in range(2, n): if n % i == 0: return False return True if __name__ == '__main__': m = int(input()) n = int(input()) prime_sum = 0 prime_min = None for i in range(m...
# pyOCD debugger # Copyright (c) 2018-2020 Arm Limited # SPDX-License-Identifier: Apache-2.0 # # 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...
class Error(RuntimeError): """@brief Parent of all errors pyOCD can raise""" pass class Internalerror(Error): """@brief Internal consistency or logic error. This error indicates that something has happened that shouldn't be possible. """ pass class Timeouterror(Error): """@brief Any sort ...
"""TRUTH TABLE GENERATOR by ANTHONY CURTIS ADLER""" left_mark = '(' right_mark = ')' def contains (phrase,chars): """Returns TRUE if <phrase> contains ANY one of <chars>""" for x in chars: if x in phrase: return True return False def bracketed (phrase): ...
"""TRUTH TABLE GENERATOR by ANTHONY CURTIS ADLER""" left_mark = '(' right_mark = ')' def contains(phrase, chars): """Returns TRUE if <phrase> contains ANY one of <chars>""" for x in chars: if x in phrase: return True return False def bracketed(phrase): """Returns TRUE if <phrase> ...
def get_cityscapes_palette(num_cls=19): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ palette = [0] * (num_cls * 3) palette[0:3] = (128, 64, 128) # 0: 'road' palette[3:6] = (244, 35,232) ...
def get_cityscapes_palette(num_cls=19): """ Returns the color map for visualizing the segmentation mask. Args: num_cls: Number of classes Returns: The color map """ palette = [0] * (num_cls * 3) palette[0:3] = (128, 64, 128) palette[3:6] = (244, 35, 232) palette[6:9] = (7...
# Define variables a and b. Read values a and b from console and calculate: # a + b # a - b # a * b # a / b # a**b. # Output obtained results. a = int(input("Enter the first number : ")) b = int(input("Enter the second number : ")) print(a + b) print(a - b) print(a * b) print(a / b) print(a**b) print(a%b) print(a...
a = int(input('Enter the first number : ')) b = int(input('Enter the second number : ')) print(a + b) print(a - b) print(a * b) print(a / b) print(a ** b) print(a % b) print(a // b) print(a ** b ** a)
""" Initialize amr_kdtree """
""" Initialize amr_kdtree """
def validate_pin(pin): if pin.isdigit() and (len(str(pin)) == 4 or len(str(pin)) == 6): return True else: return False;
def validate_pin(pin): if pin.isdigit() and (len(str(pin)) == 4 or len(str(pin)) == 6): return True else: return False
class FizzBuzz(): fizz, buzz = 'Fizz', 'Buzz' @staticmethod def is_mod_three_true(number): return number % 3 == 0 @staticmethod def is_mod_five_true(number): return number % 5 == 0 def is_mod_three_and_five_true(self, number): return self.is_mod_five_true(number) and s...
class Fizzbuzz: (fizz, buzz) = ('Fizz', 'Buzz') @staticmethod def is_mod_three_true(number): return number % 3 == 0 @staticmethod def is_mod_five_true(number): return number % 5 == 0 def is_mod_three_and_five_true(self, number): return self.is_mod_five_true(number) and...
# https://leetcode.com/problems/find-pivot-index class Solution: def pivotIndex(self, nums): if not nums: return -1 l_sum = 0 r_sum = sum(nums) - nums[0] if l_sum == r_sum: return 0 for i in range(1, len(nums)): r_sum -= nums[i] ...
class Solution: def pivot_index(self, nums): if not nums: return -1 l_sum = 0 r_sum = sum(nums) - nums[0] if l_sum == r_sum: return 0 for i in range(1, len(nums)): r_sum -= nums[i] l_sum += nums[i - 1] if r_sum == l...
DATABASE_ENGINE = 'sqlite3' INSTALLED_APPS = 'yui_loader', MIDDLEWARE_CLASSES = 'yui_loader.middleware.YUIIncludeMiddleware', ROOT_URLCONF = 'yui_loader.tests.urls' YUI_INCLUDE_BASE = '/js/yui/'
database_engine = 'sqlite3' installed_apps = ('yui_loader',) middleware_classes = ('yui_loader.middleware.YUIIncludeMiddleware',) root_urlconf = 'yui_loader.tests.urls' yui_include_base = '/js/yui/'
params = { # Train "n_epochs": 200, "learning_rate": 1e-4, "adam_beta_1": 0.9, "adam_beta_2": 0.999, "adam_epsilon": 1e-8, "clip_grad_value": 5.0, "evaluate_span": 50, "checkpoint_span": 50, # Early-stopping "no_improve_epochs": 50, # Model "model": "model-mod-8", ...
params = {'n_epochs': 200, 'learning_rate': 0.0001, 'adam_beta_1': 0.9, 'adam_beta_2': 0.999, 'adam_epsilon': 1e-08, 'clip_grad_value': 5.0, 'evaluate_span': 50, 'checkpoint_span': 50, 'no_improve_epochs': 50, 'model': 'model-mod-8', 'n_rnn_layers': 1, 'n_rnn_units': 128, 'sampling_rate': 100.0, 'input_size': 3000, 'n_...
name = "ping" def ping(): print("pong!")
name = 'ping' def ping(): print('pong!')
''' Problem Statement : Lapindromes Link : https://www.codechef.com/LRNDSA01/problems/LAPIN score : accepted ''' for _ in range(int(input())): string = input() mid = len(string)//2 first_half = None second_half = None if len(string)%2==0: first_half = string[:mid] second_...
""" Problem Statement : Lapindromes Link : https://www.codechef.com/LRNDSA01/problems/LAPIN score : accepted """ for _ in range(int(input())): string = input() mid = len(string) // 2 first_half = None second_half = None if len(string) % 2 == 0: first_half = string[:mid] s...
pid_yaw = rm_ctrl.PIDCtrl() pid_pitch = rm_ctrl.PIDCtrl() person_info = None def start(): global person_info global pid_yaw global pid_pitch global pit_chassis robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow) # Enable person detection vision_ctrl.enable_detection(rm_define.vision_d...
pid_yaw = rm_ctrl.PIDCtrl() pid_pitch = rm_ctrl.PIDCtrl() person_info = None def start(): global person_info global pid_yaw global pid_pitch global pit_chassis robot_ctrl.set_mode(rm_define.robot_mode_chassis_follow) vision_ctrl.enable_detection(rm_define.vision_detection_people) chassis_ct...
"""Possible average samples.""" AVERAGE_1 = 0 """Average of 1 sample.""" AVERAGE_2 = 1 """Average of 2 samples.""" AVERAGE_4 = 2 """Average of 4 samples.""" AVERAGE_8 = 3 """Average of 8 samples."""
"""Possible average samples.""" average_1 = 0 'Average of 1 sample.' average_2 = 1 'Average of 2 samples.' average_4 = 2 'Average of 4 samples.' average_8 = 3 'Average of 8 samples.'
n, x, y = map(int, input().split()) a = list(map(int, input().split())) for d, ad in enumerate(a): inf = ad + 1 l = max(0, d - x) l_min = min(a[l:d]) if l < d else inf r = min(n - 1, d + y) r_min = min(a[d + 1: r + 1]) if d < r else inf if ad < min(l_min, r_min): print(d + 1) ...
(n, x, y) = map(int, input().split()) a = list(map(int, input().split())) for (d, ad) in enumerate(a): inf = ad + 1 l = max(0, d - x) l_min = min(a[l:d]) if l < d else inf r = min(n - 1, d + y) r_min = min(a[d + 1:r + 1]) if d < r else inf if ad < min(l_min, r_min): print(d + 1) ...
"""Main module.""" def main(): print('package')
"""Main module.""" def main(): print('package')
PATH_DATA = "data/" URI_CSV = f"{PATH_DATA}Dades_meteorol_giques_de_la_XEMA.csv" URI_DELTA = f"{PATH_DATA}weather_data.delta" URI_DELTA_PART = f"{PATH_DATA}weather_data_partition.delta" URI_STATIONS = f"{PATH_DATA}Metadades_estacions_meteorol_giques_autom_tiques.csv" URI_VARS = f"{PATH_DATA}Metadades_variables_meteo...
path_data = 'data/' uri_csv = f'{PATH_DATA}Dades_meteorol_giques_de_la_XEMA.csv' uri_delta = f'{PATH_DATA}weather_data.delta' uri_delta_part = f'{PATH_DATA}weather_data_partition.delta' uri_stations = f'{PATH_DATA}Metadades_estacions_meteorol_giques_autom_tiques.csv' uri_vars = f'{PATH_DATA}Metadades_variables_meteorol...
MAX_DEPTH = 40 def gcd(a, b): while b != 0: t = b b = a % b a = t return a def play(a, b, turn_a, depth): if depth == 0 or (a == 1 or b == 1): if a == 1 and b == 1: return 0 else: if a == 1: r = 2 elif b == 1: ...
max_depth = 40 def gcd(a, b): while b != 0: t = b b = a % b a = t return a def play(a, b, turn_a, depth): if depth == 0 or (a == 1 or b == 1): if a == 1 and b == 1: return 0 else: if a == 1: r = 2 elif b == 1: ...
#SQL Server details SQL_HOST = 'localhost' SQL_USERNAME = 'root' SQL_PASSWORD = '' #Mongo Server details MONGO_HOST = 'localhost' #Cache details - whether to call a URL once an ingestion script is finished RESET_CACHE = False RESET_CACHE_URL = 'http://example.com/visualization_reload/' #Fab - configuration for deployin...
sql_host = 'localhost' sql_username = 'root' sql_password = '' mongo_host = 'localhost' reset_cache = False reset_cache_url = 'http://example.com/visualization_reload/' fab_hosts = [] fab_github_url = 'https://github.com/UQ-UQx/optimus_ingestor.git' fab_remote_path = '/file/to/your/deployment/location' ignore_services ...
def info(): print("Library By : Nishant Singh\n") def show(): print("Hello Guys !!\n Its a sample fun() for Suprath Technologies.\n")
def info(): print('Library By : Nishant Singh\n') def show(): print('Hello Guys !!\n Its a sample fun() for Suprath Technologies.\n')
def interpret(instruction_set, max_iterations=500): """ Runs the instruction set in a virtual machine. Returns the printed path. """ def make_dir(from_byte): if from_byte < 64: return 'U' elif from_byte < 128: return 'R' elif from_byte < 192: return '...
def interpret(instruction_set, max_iterations=500): """ Runs the instruction set in a virtual machine. Returns the printed path. """ def make_dir(from_byte): if from_byte < 64: return 'U' elif from_byte < 128: return 'R' elif from_byte < 192: return '...
#!/usr/bin/python # -*- coding: utf-8 -*- def getlist(): liststr = """ 115img.com 2mdn.net 360doc.com 360buyimg.com 51buy.com acfun.com acfun.tv acg.tv acgvideo.com adnxs.com adroll.com adsame.com adsonar.com adtechus.com alipayobjects.com appgame.com atdmt.com betrad.com bilibili.com bilibili.tv bluekai.com cctv....
def getlist(): liststr = '\n115img.com\n2mdn.net\n360doc.com\n360buyimg.com\n51buy.com\nacfun.com\nacfun.tv\nacg.tv\nacgvideo.com\nadnxs.com\nadroll.com\nadsame.com\nadsonar.com\nadtechus.com\nalipayobjects.com\nappgame.com\natdmt.com\nbetrad.com\nbilibili.com\nbilibili.tv\nbluekai.com\ncctv.com\ncnbeta.com\ncompet...
MYSQL_SERVER="" MYSQL_USER="" MYSQL_PASS="" MYSQL_DB="" UPLOAD_REQUEST_URL=""
mysql_server = '' mysql_user = '' mysql_pass = '' mysql_db = '' upload_request_url = ''
"""Module to provider installer interface. .. moduleauthor:: Xiaodong Wang <xiaodongwang@huawei.com> """ class Installer(object): """Interface for installer.""" NAME = 'installer' def __init__(self): raise NotImplementedError( '%s is not implemented' % self.__class__.__name__) ...
"""Module to provider installer interface. .. moduleauthor:: Xiaodong Wang <xiaodongwang@huawei.com> """ class Installer(object): """Interface for installer.""" name = 'installer' def __init__(self): raise not_implemented_error('%s is not implemented' % self.__class__.__name__) def __repr...
# -*- coding: utf-8 -*- __author__ = 'Erik Castro' __email__ = 'erik@erikcastro.net' __version__ = '0.1.0'
__author__ = 'Erik Castro' __email__ = 'erik@erikcastro.net' __version__ = '0.1.0'
"""Connect to Robin Hood Print Message""" #statment 1 connect_to_RobinHood_statment = "Hello, {fname} as of date {profile_time} account {profile_acct} has {profile_cash} in settled cash to trade. Algo Bot is engaging and connecting. Please monitor the system from time to time and message Michael Carrier at 815-355-73...
"""Connect to Robin Hood Print Message""" connect_to__robin_hood_statment = 'Hello, {fname} as of date {profile_time} account {profile_acct} has {profile_cash} in settled cash to trade. Algo Bot is engaging and connecting. Please monitor the system from time to time and message Michael Carrier at 815-355-7345 for any...
numbers = [12, 4, 9, 10, 7] total = 0 for num in numbers: total = total + num print("total: {}".format(total)) avg = total / len(numbers) print("average: {}".format(avg))
numbers = [12, 4, 9, 10, 7] total = 0 for num in numbers: total = total + num print('total: {}'.format(total)) avg = total / len(numbers) print('average: {}'.format(avg))
# 029 - Write a Python program to print out a set containing all the colors from color_list_1 which are not present in color_list_2. colorInfo_1 = { "White", "Black", "Red", } colorInfo_2 = { "Red", "Green", } print(colorInfo_1 - colorInfo_2)
color_info_1 = {'White', 'Black', 'Red'} color_info_2 = {'Red', 'Green'} print(colorInfo_1 - colorInfo_2)
class Tag(object): def __init__(self, name, action): self.name = name self.action = action
class Tag(object): def __init__(self, name, action): self.name = name self.action = action
class Conta(): def __init__(self,name,id,balance): self.name = name self.id = id self.balance = balance self.extract_list = [] def trasnfer(self, value): self.balance-=value self.extract_list.append(['trasnfer', value]) def deposit(self,value): self...
class Conta: def __init__(self, name, id, balance): self.name = name self.id = id self.balance = balance self.extract_list = [] def trasnfer(self, value): self.balance -= value self.extract_list.append(['trasnfer', value]) def deposit(self, value): ...
def get_IoU(confusion_matrix, label): assert ( label > 0 and label < 7 ), f"The given label {label} has to be between 1 and 6." if confusion_matrix[label - 1, :].sum() == 0: return None # There are -1 everywhere since "Unclassified" is not counted. return confusion_matrix[label - 1...
def get__io_u(confusion_matrix, label): assert label > 0 and label < 7, f'The given label {label} has to be between 1 and 6.' if confusion_matrix[label - 1, :].sum() == 0: return None return confusion_matrix[label - 1, label - 1] / (confusion_matrix[label - 1, :].sum() + confusion_matrix[:, label - ...
set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} set3 = set1.union(set2) print(set3) # set3 = {70, 40, 10, 50, 20, 60, 30} # set1 y set2 se mantienen igual
set1 = {10, 20, 30, 40, 50} set2 = {30, 40, 50, 60, 70} set3 = set1.union(set2) print(set3)
def oriNumb(ori): if(ori=='r'): return 0 elif(ori=='d'): return 1 elif(ori=='l'): return 2 elif(ori=='u'): return 3 def numbOri(numb): if(numb==0): return 'r' elif(numb==1): return 'd' elif(numb==2): return 'l' elif(numb=...
def ori_numb(ori): if ori == 'r': return 0 elif ori == 'd': return 1 elif ori == 'l': return 2 elif ori == 'u': return 3 def numb_ori(numb): if numb == 0: return 'r' elif numb == 1: return 'd' elif numb == 2: return 'l' elif numb =...
mult_dict = {} pow_dict = {} def solution(n, m): mult_dict[(m, m)] = 1 for i in range(1, m+1): mult_dict[(m, m-i)] = mult_dict[(m, m-i+1)] * (m-i+1) % 1000000007 for i in range(m+1, 2*n-m+1): mult_dict[(i, m)] = mult_dict[(i-1, m)] * i % 1000000007 mult_dict[(2*n-m, 2*n-m)] = 1 for...
mult_dict = {} pow_dict = {} def solution(n, m): mult_dict[m, m] = 1 for i in range(1, m + 1): mult_dict[m, m - i] = mult_dict[m, m - i + 1] * (m - i + 1) % 1000000007 for i in range(m + 1, 2 * n - m + 1): mult_dict[i, m] = mult_dict[i - 1, m] * i % 1000000007 mult_dict[2 * n - m, 2 * n...
def odd_or_even(number: int): if (number % 2) == 0: return "Even" else: return "Odd" if __name__ == "__main__": while True: number = int(input("Number: ")) print(odd_or_even(number))
def odd_or_even(number: int): if number % 2 == 0: return 'Even' else: return 'Odd' if __name__ == '__main__': while True: number = int(input('Number: ')) print(odd_or_even(number))
# # PySNMP MIB module HH3C-L2ISOLATE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-L2ISOLATE-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:27:40 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, ...
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) ...
class Solution: # @param {integer} numRows # @return {integer[][]} def getRow(self, numRows): return self.generateResult(numRows+1) def generateResult(self, numRows): if numRows == 0: return [] if numRows == 1: return [1] ...
class Solution: def get_row(self, numRows): return self.generateResult(numRows + 1) def generate_result(self, numRows): if numRows == 0: return [] if numRows == 1: return [1] elif numRows == 2: return [1, 1] else: result =...
## print("Hello Kimbo!")
print('Hello Kimbo!')
# The "real" article entry point # Maybe this has external (AWS) dependencies) class Article: def __init__(self): pass def get_article(self, idx): return { "id": idx, "title": "The real title" }
class Article: def __init__(self): pass def get_article(self, idx): return {'id': idx, 'title': 'The real title'}
def test_passwd_file(host): passwd = host.file("/etc/passwd") assert passwd.contains("root") assert passwd.user == "root" assert passwd.group == "root" assert passwd.mode == 0o644 def test_nginx_config_file(host): nginx = host.run("sudo nginx -t") assert nginx.succeedd
def test_passwd_file(host): passwd = host.file('/etc/passwd') assert passwd.contains('root') assert passwd.user == 'root' assert passwd.group == 'root' assert passwd.mode == 420 def test_nginx_config_file(host): nginx = host.run('sudo nginx -t') assert nginx.succeedd
# coding: utf8 def maze_twisty_trampolines_v1(s): """A Maze of Twisty Trampolines, All Alike ---.""" steps = 0 cursor = 0 maze = s[:] l = len(maze) while True: if cursor < 0 or cursor >= l: break instruction = maze[cursor] maze[cursor] += 1 cursor +...
def maze_twisty_trampolines_v1(s): """A Maze of Twisty Trampolines, All Alike ---.""" steps = 0 cursor = 0 maze = s[:] l = len(maze) while True: if cursor < 0 or cursor >= l: break instruction = maze[cursor] maze[cursor] += 1 cursor += instruction ...
#!/user/bin/python # coding: utf8 class Larvae(Ant): """docstring for Larvae""" def __init__(self, arg): super().__init__(arg) self.arg = arg
class Larvae(Ant): """docstring for Larvae""" def __init__(self, arg): super().__init__(arg) self.arg = arg
def summation(num): if num == 0: return 0 return num + summation(num - 1) def summation1(num): return sum(range(num + 1)) # Name (time in ns) Min Max Mean StdDev Median IQR Outliers OPS (Mops/s) ...
def summation(num): if num == 0: return 0 return num + summation(num - 1) def summation1(num): return sum(range(num + 1))
# Autogenerated file for Dot Matrix # Add missing from ... import const _JD_SERVICE_CLASS_DOT_MATRIX = const(0x110d154b) _JD_DOT_MATRIX_VARIANT_LED = const(0x1) _JD_DOT_MATRIX_VARIANT_BRAILLE = const(0x2) _JD_DOT_MATRIX_REG_DOTS = const(JD_REG_VALUE) _JD_DOT_MATRIX_REG_BRIGHTNESS = const(JD_REG_INTENSITY) _JD_DOT_MATRI...
_jd_service_class_dot_matrix = const(286070091) _jd_dot_matrix_variant_led = const(1) _jd_dot_matrix_variant_braille = const(2) _jd_dot_matrix_reg_dots = const(JD_REG_VALUE) _jd_dot_matrix_reg_brightness = const(JD_REG_INTENSITY) _jd_dot_matrix_reg_rows = const(385) _jd_dot_matrix_reg_columns = const(386) _jd_dot_matri...
''' File name: p3_utils.py Author: Date: '''
""" File name: p3_utils.py Author: Date: """
# Generate the Fibonacci list, stopping at given value def maxFibonacciValue(n): fib = [1, 2] for i in range(2, int(n)): if(fib[i-1] + fib[i-2] > int(n)): break else: fib.append(fib[i-1] + fib[i-2]) return fib # Calculate even-valued sum def evenFibonacciNumbers(n): ...
def max_fibonacci_value(n): fib = [1, 2] for i in range(2, int(n)): if fib[i - 1] + fib[i - 2] > int(n): break else: fib.append(fib[i - 1] + fib[i - 2]) return fib def even_fibonacci_numbers(n): sum = 0 for value in max_fibonacci_value(n): if value % ...
S = ["nwc10_hallway", "nwc1003b_danino", "nwc10", "nwc10m", "nwc8", "nwc7", "nwc4", "outOfLab", "nwc1008", "nwc1006", "nwc1007", "nwc1009", "nwc1010", "nwc1003g", "nwc1003g_a", "nwc1003g_b", "nwc1003g_c", "nwc1003b_a", "nwc1003b_b", "nwc1003b_c", "nwc1003b_t", "nwc1003a", "nwc1003b", "nwc1001l", "nwc1000m_a1", "n...
s = ['nwc10_hallway', 'nwc1003b_danino', 'nwc10', 'nwc10m', 'nwc8', 'nwc7', 'nwc4', 'outOfLab', 'nwc1008', 'nwc1006', 'nwc1007', 'nwc1009', 'nwc1010', 'nwc1003g', 'nwc1003g_a', 'nwc1003g_b', 'nwc1003g_c', 'nwc1003b_a', 'nwc1003b_b', 'nwc1003b_c', 'nwc1003b_t', 'nwc1003a', 'nwc1003b', 'nwc1001l', 'nwc1000m_a1', 'nwc1000...
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ # we need the best profit and its range in prices (the 1st transaction) profit1, l, r = self.maxProfit_1(prices) # then we consider other cases where we c...
class Solution(object): def max_profit(self, prices): """ :type prices: List[int] :rtype: int """ (profit1, l, r) = self.maxProfit_1(prices) profits = [] profits.append(self.maxProfit_1(prices[r:])) profits.append(self.maxProfit_1(prices[:l])) ...
class Support(Object): def __init__(self, name, ux = 1, uy = 1, uz = 1, rx = 1, ry = 1, rz = 1): self.name = name self.ux = ux self.uy = uy self.uz = uz self.rx = rx self.ry = ry self.rz = rz
class Support(Object): def __init__(self, name, ux=1, uy=1, uz=1, rx=1, ry=1, rz=1): self.name = name self.ux = ux self.uy = uy self.uz = uz self.rx = rx self.ry = ry self.rz = rz