content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# This module is from mx/DateTime/LazyModule.py and is # distributed under the terms of the eGenix.com Public License Agreement # https://www.egenix.com/products/eGenix.com-Public-License-1.1.0.pdf """ Helper to enable simple lazy module import. 'Lazy' means the actual import is deferred until an attribute is requested from the module's namespace. This has the advantage of allowing all imports to be done at the top of a script (in a prominent and visible place) without having a great impact on startup time. Copyright (c) 1999-2005, Marc-Andre Lemburg; mailto:mal@lemburg.com See the documentation for further information on copyrights, or contact the author. All Rights Reserved. """ ### Constants _debug = 0 ### class LazyModule: """Lazy module class. Lazy modules are imported into the given namespaces whenever a non-special attribute (there are some attributes like __doc__ that class instances handle without calling __getattr__) is requested. The module is then registered under the given name in locals usually replacing the import wrapper instance. The import itself is done using globals as global namespace. Example of creating a lazy load module: ISO = LazyModule('ISO',locals(),globals()) Later, requesting an attribute from ISO will load the module automatically into the locals() namespace, overriding the LazyModule instance: t = ISO.Week(1998,1,1) """ # Flag which indicates whether the LazyModule is initialized or not __lazymodule_init = 0 # Name of the module to load __lazymodule_name = "" # Flag which indicates whether the module was loaded or not __lazymodule_loaded = 0 # Locals dictionary where to register the module __lazymodule_locals = None # Globals dictionary to use for the module import __lazymodule_globals = None def __init__(self, name, locals, globals=None): """Create a LazyModule instance wrapping module name. The module will later on be registered in locals under the given module name. globals is optional and defaults to locals. """ self.__lazymodule_locals = locals if globals is None: globals = locals self.__lazymodule_globals = globals mainname = globals.get("__name__", "") if mainname: self.__name__ = mainname + "." + name self.__lazymodule_name = name else: self.__name__ = self.__lazymodule_name = name self.__lazymodule_init = 1 def __lazymodule_import(self): """Import the module now.""" # Load and register module name = self.__lazymodule_name if self.__lazymodule_loaded: return self.__lazymodule_locals[name] if _debug: print("LazyModule: Loading module %r" % name) self.__lazymodule_locals[name] = module = __import__( name, self.__lazymodule_locals, self.__lazymodule_globals, "*" ) # Fill namespace with all symbols from original module to # provide faster access. self.__dict__.update(module.__dict__) # Set import flag self.__dict__["__lazymodule_loaded"] = 1 if _debug: print("LazyModule: Module %r loaded" % name) return module def __getattr__(self, name): """Import the module on demand and get the attribute.""" if self.__lazymodule_loaded: raise AttributeError(name) if _debug: print( "LazyModule: " "Module load triggered by attribute %r read access" % name ) module = self.__lazymodule_import() return getattr(module, name) def __setattr__(self, name, value): """Import the module on demand and set the attribute.""" if not self.__lazymodule_init: self.__dict__[name] = value return if self.__lazymodule_loaded: self.__lazymodule_locals[self.__lazymodule_name] = value self.__dict__[name] = value return if _debug: print( "LazyModule: " "Module load triggered by attribute %r write access" % name ) module = self.__lazymodule_import() setattr(module, name, value) def __repr__(self): return "<LazyModule '%s'>" % self.__name__
""" Helper to enable simple lazy module import. 'Lazy' means the actual import is deferred until an attribute is requested from the module's namespace. This has the advantage of allowing all imports to be done at the top of a script (in a prominent and visible place) without having a great impact on startup time. Copyright (c) 1999-2005, Marc-Andre Lemburg; mailto:mal@lemburg.com See the documentation for further information on copyrights, or contact the author. All Rights Reserved. """ _debug = 0 class Lazymodule: """Lazy module class. Lazy modules are imported into the given namespaces whenever a non-special attribute (there are some attributes like __doc__ that class instances handle without calling __getattr__) is requested. The module is then registered under the given name in locals usually replacing the import wrapper instance. The import itself is done using globals as global namespace. Example of creating a lazy load module: ISO = LazyModule('ISO',locals(),globals()) Later, requesting an attribute from ISO will load the module automatically into the locals() namespace, overriding the LazyModule instance: t = ISO.Week(1998,1,1) """ __lazymodule_init = 0 __lazymodule_name = '' __lazymodule_loaded = 0 __lazymodule_locals = None __lazymodule_globals = None def __init__(self, name, locals, globals=None): """Create a LazyModule instance wrapping module name. The module will later on be registered in locals under the given module name. globals is optional and defaults to locals. """ self.__lazymodule_locals = locals if globals is None: globals = locals self.__lazymodule_globals = globals mainname = globals.get('__name__', '') if mainname: self.__name__ = mainname + '.' + name self.__lazymodule_name = name else: self.__name__ = self.__lazymodule_name = name self.__lazymodule_init = 1 def __lazymodule_import(self): """Import the module now.""" name = self.__lazymodule_name if self.__lazymodule_loaded: return self.__lazymodule_locals[name] if _debug: print('LazyModule: Loading module %r' % name) self.__lazymodule_locals[name] = module = __import__(name, self.__lazymodule_locals, self.__lazymodule_globals, '*') self.__dict__.update(module.__dict__) self.__dict__['__lazymodule_loaded'] = 1 if _debug: print('LazyModule: Module %r loaded' % name) return module def __getattr__(self, name): """Import the module on demand and get the attribute.""" if self.__lazymodule_loaded: raise attribute_error(name) if _debug: print('LazyModule: Module load triggered by attribute %r read access' % name) module = self.__lazymodule_import() return getattr(module, name) def __setattr__(self, name, value): """Import the module on demand and set the attribute.""" if not self.__lazymodule_init: self.__dict__[name] = value return if self.__lazymodule_loaded: self.__lazymodule_locals[self.__lazymodule_name] = value self.__dict__[name] = value return if _debug: print('LazyModule: Module load triggered by attribute %r write access' % name) module = self.__lazymodule_import() setattr(module, name, value) def __repr__(self): return "<LazyModule '%s'>" % self.__name__
stack = [] stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) print('\nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are poped:') print(stack)
stack = [] stack.append('a') stack.append('b') stack.append('c') print('Initial stack') print(stack) print('\nElements poped from stack:') print(stack.pop()) print(stack.pop()) print(stack.pop()) print('\nStack after elements are poped:') print(stack)
"""Static values for one way import.""" SUPPORTED_FORMATS = (".svg", ".jpeg", ".jpg", ".png", ".tiff", ".tif") HTML_LINK = '<link rel="{rel}" type="{type}" href="{href}" />' ICON_TYPES = ( {"image_fmt": "ico", "rel": None, "dimensions": (64, 64), "prefix": "favicon"}, {"image_fmt": "png", "rel": "icon", "dimensions": (16, 16), "prefix": "favicon"}, {"image_fmt": "png", "rel": "icon", "dimensions": (32, 32), "prefix": "favicon"}, {"image_fmt": "png", "rel": "icon", "dimensions": (64, 64), "prefix": "favicon"}, {"image_fmt": "png", "rel": "icon", "dimensions": (96, 96), "prefix": "favicon"}, {"image_fmt": "png", "rel": "icon", "dimensions": (180, 180), "prefix": "favicon"}, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (57, 57), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (60, 60), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (72, 72), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (76, 76), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (114, 114), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (120, 120), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (144, 144), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (152, 152), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (167, 167), "prefix": "apple-touch-icon", }, { "image_fmt": "png", "rel": "apple-touch-icon", "dimensions": (180, 180), "prefix": "apple-touch-icon", }, {"image_fmt": "png", "rel": None, "dimensions": (70, 70), "prefix": "mstile"}, {"image_fmt": "png", "rel": None, "dimensions": (270, 270), "prefix": "mstile"}, {"image_fmt": "png", "rel": None, "dimensions": (310, 310), "prefix": "mstile"}, {"image_fmt": "png", "rel": None, "dimensions": (310, 150), "prefix": "mstile"}, {"image_fmt": "png", "rel": "shortcut icon", "dimensions": (196, 196), "prefix": "favicon"}, )
"""Static values for one way import.""" supported_formats = ('.svg', '.jpeg', '.jpg', '.png', '.tiff', '.tif') html_link = '<link rel="{rel}" type="{type}" href="{href}" />' icon_types = ({'image_fmt': 'ico', 'rel': None, 'dimensions': (64, 64), 'prefix': 'favicon'}, {'image_fmt': 'png', 'rel': 'icon', 'dimensions': (16, 16), 'prefix': 'favicon'}, {'image_fmt': 'png', 'rel': 'icon', 'dimensions': (32, 32), 'prefix': 'favicon'}, {'image_fmt': 'png', 'rel': 'icon', 'dimensions': (64, 64), 'prefix': 'favicon'}, {'image_fmt': 'png', 'rel': 'icon', 'dimensions': (96, 96), 'prefix': 'favicon'}, {'image_fmt': 'png', 'rel': 'icon', 'dimensions': (180, 180), 'prefix': 'favicon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (57, 57), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (60, 60), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (72, 72), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (76, 76), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (114, 114), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (120, 120), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (144, 144), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (152, 152), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (167, 167), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': 'apple-touch-icon', 'dimensions': (180, 180), 'prefix': 'apple-touch-icon'}, {'image_fmt': 'png', 'rel': None, 'dimensions': (70, 70), 'prefix': 'mstile'}, {'image_fmt': 'png', 'rel': None, 'dimensions': (270, 270), 'prefix': 'mstile'}, {'image_fmt': 'png', 'rel': None, 'dimensions': (310, 310), 'prefix': 'mstile'}, {'image_fmt': 'png', 'rel': None, 'dimensions': (310, 150), 'prefix': 'mstile'}, {'image_fmt': 'png', 'rel': 'shortcut icon', 'dimensions': (196, 196), 'prefix': 'favicon'})
def findLongestSubSeq(str): n = len(str) dp = [[0 for k in range(n+1)] for l in range(n+1)] for i in range(1, n+1): for j in range(1, n+1): # If characters match and indices are not same if (str[i-1] == str[j-1] and i != j): dp[i][j] = 1 + dp[i-1][j-1] # If characters do not match else: dp[i][j] = max(dp[i][j-1], dp[i-1][j]) return dp[n][n]
def find_longest_sub_seq(str): n = len(str) dp = [[0 for k in range(n + 1)] for l in range(n + 1)] for i in range(1, n + 1): for j in range(1, n + 1): if str[i - 1] == str[j - 1] and i != j: dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = max(dp[i][j - 1], dp[i - 1][j]) return dp[n][n]
""" [8/8/2012] Challenge #86 [easy] (run-length encoding) https://www.reddit.com/r/dailyprogrammer/comments/xxbbo/882012_challenge_86_easy_runlength_encoding/ Run-Length encoding is a simple form of compression that detects 'runs' of repeated instances of a symbol in a string and compresses them to a list of pairs of 'symbol' 'length'. For example, the string "Heeeeelllllooooo nurse!" Could be compressed using run-length encoding to the list of pairs [(1,'H'),(5,'e'),(5,'l'),(5,'o'),(1,'n'),(1,'u'),(1,'r'),(1,'s'),(1,'e')] Which seems to not be compressed, but if you represent it as an array of 18bytes (each pair is 2 bytes), then we save 5 bytes of space compressing this string. Write a function that takes in a string and returns a run-length-encoding of that string. (either as a list of pairs or as a 2-byte-per pair array) BONUS: Write a decompression function that takes in the RLE representation and returns the original string """ def main(): pass if __name__ == "__main__": main()
""" [8/8/2012] Challenge #86 [easy] (run-length encoding) https://www.reddit.com/r/dailyprogrammer/comments/xxbbo/882012_challenge_86_easy_runlength_encoding/ Run-Length encoding is a simple form of compression that detects 'runs' of repeated instances of a symbol in a string and compresses them to a list of pairs of 'symbol' 'length'. For example, the string "Heeeeelllllooooo nurse!" Could be compressed using run-length encoding to the list of pairs [(1,'H'),(5,'e'),(5,'l'),(5,'o'),(1,'n'),(1,'u'),(1,'r'),(1,'s'),(1,'e')] Which seems to not be compressed, but if you represent it as an array of 18bytes (each pair is 2 bytes), then we save 5 bytes of space compressing this string. Write a function that takes in a string and returns a run-length-encoding of that string. (either as a list of pairs or as a 2-byte-per pair array) BONUS: Write a decompression function that takes in the RLE representation and returns the original string """ def main(): pass if __name__ == '__main__': main()
@singleton class Database: def __init__(self): print('Loading database')
@singleton class Database: def __init__(self): print('Loading database')
#!/usr/bin/env python3 def get_case_data(): return [int(i) for i in input().split()] # Using recursive implementation def get_gcd(a, b): return get_gcd(b, a % b) if b != 0 else a def print_number_or_ok_if_equals(number, guess): print("OK" if number == guess else number) number_of_cases = int(input()) for case in range(number_of_cases): first_integer, second_integer, proposed_gcd = get_case_data() real_gcd = get_gcd(first_integer, second_integer) print_number_or_ok_if_equals(real_gcd, proposed_gcd)
def get_case_data(): return [int(i) for i in input().split()] def get_gcd(a, b): return get_gcd(b, a % b) if b != 0 else a def print_number_or_ok_if_equals(number, guess): print('OK' if number == guess else number) number_of_cases = int(input()) for case in range(number_of_cases): (first_integer, second_integer, proposed_gcd) = get_case_data() real_gcd = get_gcd(first_integer, second_integer) print_number_or_ok_if_equals(real_gcd, proposed_gcd)
# 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 verticalTraversal(self, root: TreeNode) -> List[List[int]]: res = defaultdict(list) q = [(root, 0)] min_col = max_col = 0 while q: q.sort(key=lambda x: (x[1], x[0].val)) min_col = min(min_col, q[0][1]) max_col = max(max_col, q[-1][1]) prev_q, q = q, [] for node, col in prev_q: res[col].append(node.val) if node.left: q.append((node.left, col - 1)) if node.right: q.append((node.right, col + 1)) return [res[col] for col in range(min_col, max_col+1)]
class Solution: def vertical_traversal(self, root: TreeNode) -> List[List[int]]: res = defaultdict(list) q = [(root, 0)] min_col = max_col = 0 while q: q.sort(key=lambda x: (x[1], x[0].val)) min_col = min(min_col, q[0][1]) max_col = max(max_col, q[-1][1]) (prev_q, q) = (q, []) for (node, col) in prev_q: res[col].append(node.val) if node.left: q.append((node.left, col - 1)) if node.right: q.append((node.right, col + 1)) return [res[col] for col in range(min_col, max_col + 1)]
# -*- coding: utf-8 -*- def main(): s = input() mod = '' for i in range(3): if s[i] == '1': mod += '9' elif s[i] == '9': mod += '1' print(mod) if __name__ == '__main__': main()
def main(): s = input() mod = '' for i in range(3): if s[i] == '1': mod += '9' elif s[i] == '9': mod += '1' print(mod) if __name__ == '__main__': main()
class Node: def __init__(self,data): self.data=data self.next=None arr=[5,8,20] brr=[4,11,15] #inserting elements in first list list1=Node(arr[0]) root1=list1 for i in arr[1::]: temp=Node(i) list1.next=temp list1=list1.next #inserting elements in second list list2=Node(brr[0]) root2=list2 for i in brr[1::]: temp=Node(i) list2.next=temp list2=list2.next newlist=[] while(root1!=None and root2!=None): if(root1.data<root2.data): newlist.append(root1.data) root1=root1.next else: newlist.append(root2.data) root2=root2.next if(root1==None): if(root2==None): print(newlist) else: while(root2!=None): newlist.append(root2.data) root2=root2.next elif(root2==None): if(root1==None): print(newlist) else: while(root1!=None): newlist.append(root1.data) root1=root1.next print(newlist)
class Node: def __init__(self, data): self.data = data self.next = None arr = [5, 8, 20] brr = [4, 11, 15] list1 = node(arr[0]) root1 = list1 for i in arr[1:]: temp = node(i) list1.next = temp list1 = list1.next list2 = node(brr[0]) root2 = list2 for i in brr[1:]: temp = node(i) list2.next = temp list2 = list2.next newlist = [] while root1 != None and root2 != None: if root1.data < root2.data: newlist.append(root1.data) root1 = root1.next else: newlist.append(root2.data) root2 = root2.next if root1 == None: if root2 == None: print(newlist) else: while root2 != None: newlist.append(root2.data) root2 = root2.next elif root2 == None: if root1 == None: print(newlist) else: while root1 != None: newlist.append(root1.data) root1 = root1.next print(newlist)
# Write your solution for 1.4 here! def is_prime(x): if x > 1: for i in range(2,x): if (x % i) == 0: print(x,"is not a prime number") print(i,"times",x//i,"is",x) else: print(x,"is not a prime number") is_prime(5)
def is_prime(x): if x > 1: for i in range(2, x): if x % i == 0: print(x, 'is not a prime number') print(i, 'times', x // i, 'is', x) else: print(x, 'is not a prime number') is_prime(5)
class PluginMount(type): """Generic plugin mount point (= entry point) for pydifact plugins. .. note:: Plugins that have an **__omitted__** attriute are not added to the list! """ # thanks to Marty Alchin! def __init__(cls, name, bases, attrs): if not hasattr(cls, "plugins"): cls.plugins = [] else: if not getattr(cls, "__omitted__", False): cls.plugins.append(cls) class EDISyntaxError(SyntaxError): """A Syntax error within the parsed EDIFACT file was found."""
class Pluginmount(type): """Generic plugin mount point (= entry point) for pydifact plugins. .. note:: Plugins that have an **__omitted__** attriute are not added to the list! """ def __init__(cls, name, bases, attrs): if not hasattr(cls, 'plugins'): cls.plugins = [] elif not getattr(cls, '__omitted__', False): cls.plugins.append(cls) class Edisyntaxerror(SyntaxError): """A Syntax error within the parsed EDIFACT file was found."""
if __name__ == "__main__": print((lambda x,r : [r:=r+1 for i in x.split('\n\n') if all(map(lambda x : x in i,['byr','iyr','eyr','hgt','hcl','ecl','pid']))][-1])(open("i").read(),0)) def main_debug(inp): # 204 inp = inp.split('\n\n') rep = 0 for i in inp: if all(map(lambda x : x in i,['byr','iyr','eyr','hgt','hcl','ecl','pid'])): rep += 1 return rep
if __name__ == '__main__': print((lambda x, r: [(r := (r + 1)) for i in x.split('\n\n') if all(map(lambda x: x in i, ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid']))][-1])(open('i').read(), 0)) def main_debug(inp): inp = inp.split('\n\n') rep = 0 for i in inp: if all(map(lambda x: x in i, ['byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'])): rep += 1 return rep
def flatten(iterable, result=None): if result == None: result = [] for it in iterable: if type(it) in (list, set, tuple): flatten(it, result) else: result.append(it) return [i for i in result if i is not None]
def flatten(iterable, result=None): if result == None: result = [] for it in iterable: if type(it) in (list, set, tuple): flatten(it, result) else: result.append(it) return [i for i in result if i is not None]
def palindromo(palavra: str) -> bool: if len(palavra) <= 1: return True primeira_letra = palavra[0] ultima_letra = palavra[-1] if primeira_letra != ultima_letra: return False return palindromo(palavra[1:-1]) nome_do_arquivo = input('Digite o nome do entrada de entrada: ') with open(nome_do_arquivo, 'r', encoding='utf8') as arquivo: for linha in arquivo: linha = linha.strip() palavras = linha.split() for palavra in palavras: if palindromo(palavra): print(palavra) # print(eh_primo('ama')) # print(eh_primo('socorrammesubinoonibusemmarroco'))
def palindromo(palavra: str) -> bool: if len(palavra) <= 1: return True primeira_letra = palavra[0] ultima_letra = palavra[-1] if primeira_letra != ultima_letra: return False return palindromo(palavra[1:-1]) nome_do_arquivo = input('Digite o nome do entrada de entrada: ') with open(nome_do_arquivo, 'r', encoding='utf8') as arquivo: for linha in arquivo: linha = linha.strip() palavras = linha.split() for palavra in palavras: if palindromo(palavra): print(palavra)
def main(): isNumber = False while not isNumber: try: size = int(input('Height: ')) if size > 0 and size <= 8: isNumber = True break except ValueError: isNumber = False build(size, size) def build(size, counter): spaces = size - 1 if size == 0: return 1 else: print(' ' * spaces, end='') print('#' * (counter - spaces), end=' ') print('#' * (counter - spaces), end='\n') return build(size - 1, counter) main()
def main(): is_number = False while not isNumber: try: size = int(input('Height: ')) if size > 0 and size <= 8: is_number = True break except ValueError: is_number = False build(size, size) def build(size, counter): spaces = size - 1 if size == 0: return 1 else: print(' ' * spaces, end='') print('#' * (counter - spaces), end=' ') print('#' * (counter - spaces), end='\n') return build(size - 1, counter) main()
#URLs ROOTURL = 'https://www.reuters.com/companies/' FXRATESURL = 'https://www.reuters.com/markets/currencies' #ADDURLs INCSTAT_ANN_URL = '/financials/income-statement-annual/' INCSTAT_QRT_URL = '/financials/income-statement-quarterly/' BS_ANN_URL = '/financials/balance-sheet-annual/' BS_QRT_URL = '/financials/balance-sheet-quarterly/' KEYMETRICS_URL = '/key-metrics/' #TABLENAMES STOCKDATA = 'stockdata' FXRATES = 'fxrates' INCSTAT_ANN = 'incstat_ann' INCSTAT_QRT = 'incstat_qrt' BS_ANN = 'bs_ann' BS_QRT = 'bs_qrt' KEYMETRICS = 'km' #TIMES YEARS = ['2015', '2016', '2017', '2018', '2019'] QRTS = ['2019Q2', '2019Q3', '2019Q4', '2020Q1', '2020Q2'] #DICTIONARIES ADDURLS_TO_TABLENAMES = { INCSTAT_ANN_URL: INCSTAT_ANN,\ INCSTAT_QRT_URL:INCSTAT_QRT,\ BS_ANN_URL: BS_ANN,\ BS_QRT_URL: BS_QRT, \ KEYMETRICS_URL: KEYMETRICS} TABLENAMES_TO_DATA = { INCSTAT_ANN: { 'Total Revenue' :[0, 'int64'],\ 'Net Income' : [0, 'int64']},\ INCSTAT_QRT:{ 'Total Revenue': [0, 'int64'],\ 'Net Income': [0, 'int64']},\ BS_ANN: { 'Total Equity' : [0, 'int64'],\ 'Total Liabilities' : [0, 'int64']},\ BS_QRT: { 'Total Equity' : [0, 'int64'],\ 'Total Liabilities' : [0, 'int64']}, \ KEYMETRICS: { 'Dividend (Per Share Annual)' : [0, 'float64' ],\ 'Free Cash Flow (Per Share TTM)' : [0, 'float64'],\ 'Current Ratio (Annual)' : [0, 'float64']} } FACTORS = { 'Mil': 1000000, 'Thousands': 1000} COLUMNHEADERSDICT_ANN = { "Unnamed: 0":"Item", \ "Unnamed: 1":YEARS[-1],\ "Unnamed: 2":YEARS[-2],\ "Unnamed: 3":YEARS[-3],\ "Unnamed: 4":YEARS[-4],\ "Unnamed: 5":YEARS[-5], \ 0:"Item", \ 1: YEARS[-1]} # Unnamed for financials - 0,1 for non-financials COLUMNHEADERSDICT_QRT = { "Unnamed: 0":"Item", \ "Unnamed: 1":QRTS[-1],\ "Unnamed: 2":QRTS[-2],\ "Unnamed: 3":QRTS[-3],\ "Unnamed: 4":QRTS[-4],\ "Unnamed: 5":QRTS[-5], \ 0:"Item", \ 1: YEARS[-1]} # Unnamed for financials - 0,1 for non-financials ISIN_TO_COUNTRIES = { 'US' : 'USA', 'DE' : 'Germany', 'GB' : 'UK', 'NL' : 'Netherlands', 'IE' : 'Ireland', 'FR' : 'France', 'CA' : 'Canada', 'CH' : 'Switzerland' } #PATHS RICSCSVPATH = "..\\data\\01_raw\\reuters-shorts.csv" RAWDATAPATH = "..\\data\\01_raw\\rawdatadb.db" INTDATAPATH = "..\\data\\02_intermediate\\intdatadb.db" PROCDATAPATH = '..\\data\\03_processed\\processeddata.feather' PROCDATAPATHCSV = '..\\data\\03_processed\\processeddata.csv' CURRENCIES = ['USD', 'EUR', 'GBP','CHF', 'INR']
rooturl = 'https://www.reuters.com/companies/' fxratesurl = 'https://www.reuters.com/markets/currencies' incstat_ann_url = '/financials/income-statement-annual/' incstat_qrt_url = '/financials/income-statement-quarterly/' bs_ann_url = '/financials/balance-sheet-annual/' bs_qrt_url = '/financials/balance-sheet-quarterly/' keymetrics_url = '/key-metrics/' stockdata = 'stockdata' fxrates = 'fxrates' incstat_ann = 'incstat_ann' incstat_qrt = 'incstat_qrt' bs_ann = 'bs_ann' bs_qrt = 'bs_qrt' keymetrics = 'km' years = ['2015', '2016', '2017', '2018', '2019'] qrts = ['2019Q2', '2019Q3', '2019Q4', '2020Q1', '2020Q2'] addurls_to_tablenames = {INCSTAT_ANN_URL: INCSTAT_ANN, INCSTAT_QRT_URL: INCSTAT_QRT, BS_ANN_URL: BS_ANN, BS_QRT_URL: BS_QRT, KEYMETRICS_URL: KEYMETRICS} tablenames_to_data = {INCSTAT_ANN: {'Total Revenue': [0, 'int64'], 'Net Income': [0, 'int64']}, INCSTAT_QRT: {'Total Revenue': [0, 'int64'], 'Net Income': [0, 'int64']}, BS_ANN: {'Total Equity': [0, 'int64'], 'Total Liabilities': [0, 'int64']}, BS_QRT: {'Total Equity': [0, 'int64'], 'Total Liabilities': [0, 'int64']}, KEYMETRICS: {'Dividend (Per Share Annual)': [0, 'float64'], 'Free Cash Flow (Per Share TTM)': [0, 'float64'], 'Current Ratio (Annual)': [0, 'float64']}} factors = {'Mil': 1000000, 'Thousands': 1000} columnheadersdict_ann = {'Unnamed: 0': 'Item', 'Unnamed: 1': YEARS[-1], 'Unnamed: 2': YEARS[-2], 'Unnamed: 3': YEARS[-3], 'Unnamed: 4': YEARS[-4], 'Unnamed: 5': YEARS[-5], 0: 'Item', 1: YEARS[-1]} columnheadersdict_qrt = {'Unnamed: 0': 'Item', 'Unnamed: 1': QRTS[-1], 'Unnamed: 2': QRTS[-2], 'Unnamed: 3': QRTS[-3], 'Unnamed: 4': QRTS[-4], 'Unnamed: 5': QRTS[-5], 0: 'Item', 1: YEARS[-1]} isin_to_countries = {'US': 'USA', 'DE': 'Germany', 'GB': 'UK', 'NL': 'Netherlands', 'IE': 'Ireland', 'FR': 'France', 'CA': 'Canada', 'CH': 'Switzerland'} ricscsvpath = '..\\data\\01_raw\\reuters-shorts.csv' rawdatapath = '..\\data\\01_raw\\rawdatadb.db' intdatapath = '..\\data\\02_intermediate\\intdatadb.db' procdatapath = '..\\data\\03_processed\\processeddata.feather' procdatapathcsv = '..\\data\\03_processed\\processeddata.csv' currencies = ['USD', 'EUR', 'GBP', 'CHF', 'INR']
DEFAULT_PORT = 9000 DEFAULT_SECURE_PORT = 9440 DBMS_MIN_REVISION_WITH_TEMPORARY_TABLES = 50264 DBMS_MIN_REVISION_WITH_TOTAL_ROWS_IN_PROGRESS = 51554 DBMS_MIN_REVISION_WITH_BLOCK_INFO = 51903 # Legacy above. DBMS_MIN_REVISION_WITH_CLIENT_INFO = 54032 DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE = 54058 DBMS_MIN_REVISION_WITH_QUOTA_KEY_IN_CLIENT_INFO = 54060 DBMS_MIN_REVISION_WITH_SERVER_DISPLAY_NAME = 54372 DBMS_MIN_REVISION_WITH_VERSION_PATCH = 54401 DBMS_MIN_REVISION_WITH_SERVER_LOGS = 54406 DBMS_MIN_REVISION_WITH_COLUMN_DEFAULTS_METADATA = 54410 DBMS_MIN_REVISION_WITH_CLIENT_WRITE_INFO = 54420 DBMS_MIN_REVISION_WITH_SETTINGS_SERIALIZED_AS_STRINGS = 54429 # Timeouts DBMS_DEFAULT_CONNECT_TIMEOUT_SEC = 10 DBMS_DEFAULT_TIMEOUT_SEC = 300 DBMS_DEFAULT_SYNC_REQUEST_TIMEOUT_SEC = 5 DEFAULT_COMPRESS_BLOCK_SIZE = 1048576 DEFAULT_INSERT_BLOCK_SIZE = 1048576 DBMS_NAME = 'ClickHouse' CLIENT_NAME = 'python-driver' CLIENT_VERSION_MAJOR = 18 CLIENT_VERSION_MINOR = 10 CLIENT_VERSION_PATCH = 3 CLIENT_REVISION = 54429 BUFFER_SIZE = 1048576 STRINGS_ENCODING = 'utf-8'
default_port = 9000 default_secure_port = 9440 dbms_min_revision_with_temporary_tables = 50264 dbms_min_revision_with_total_rows_in_progress = 51554 dbms_min_revision_with_block_info = 51903 dbms_min_revision_with_client_info = 54032 dbms_min_revision_with_server_timezone = 54058 dbms_min_revision_with_quota_key_in_client_info = 54060 dbms_min_revision_with_server_display_name = 54372 dbms_min_revision_with_version_patch = 54401 dbms_min_revision_with_server_logs = 54406 dbms_min_revision_with_column_defaults_metadata = 54410 dbms_min_revision_with_client_write_info = 54420 dbms_min_revision_with_settings_serialized_as_strings = 54429 dbms_default_connect_timeout_sec = 10 dbms_default_timeout_sec = 300 dbms_default_sync_request_timeout_sec = 5 default_compress_block_size = 1048576 default_insert_block_size = 1048576 dbms_name = 'ClickHouse' client_name = 'python-driver' client_version_major = 18 client_version_minor = 10 client_version_patch = 3 client_revision = 54429 buffer_size = 1048576 strings_encoding = 'utf-8'
class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ res=0 prev=None for x in prices: res += x-prev if prev!=None and prev<x else 0 prev = x return res
class Solution(object): def max_profit(self, prices): """ :type prices: List[int] :rtype: int """ res = 0 prev = None for x in prices: res += x - prev if prev != None and prev < x else 0 prev = x return res
input_file = open("input.txt", "r") entriesArray = input_file.read().split("\n") depth_measure_increase = 0 for i in range(3, len(entriesArray), 1): first_window = int(entriesArray[i-1]) + int(entriesArray[i-2]) + int(entriesArray[i-3]) second_window = int(entriesArray[i]) + int(entriesArray[i-1]) + int(entriesArray[i-2]) if second_window > first_window: depth_measure_increase += 1 print(f'{depth_measure_increase=}')
input_file = open('input.txt', 'r') entries_array = input_file.read().split('\n') depth_measure_increase = 0 for i in range(3, len(entriesArray), 1): first_window = int(entriesArray[i - 1]) + int(entriesArray[i - 2]) + int(entriesArray[i - 3]) second_window = int(entriesArray[i]) + int(entriesArray[i - 1]) + int(entriesArray[i - 2]) if second_window > first_window: depth_measure_increase += 1 print(f'depth_measure_increase={depth_measure_increase!r}')
class Solution: def reverseString(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ l , r = 0 , len(s)-1 while l<r: s[l] , s[r] = s[r] , s[l] l +=1 r -=1 return s
class Solution: def reverse_string(self, s: List[str]) -> None: """ Do not return anything, modify s in-place instead. """ (l, r) = (0, len(s) - 1) while l < r: (s[l], s[r]) = (s[r], s[l]) l += 1 r -= 1 return s
def multiplicationTable(size): return [[j*i for j in range(1, size+1)] for i in range(1, size+1)] x = multiplicationTable(5) print(x) print() for i in x: print(i)
def multiplication_table(size): return [[j * i for j in range(1, size + 1)] for i in range(1, size + 1)] x = multiplication_table(5) print(x) print() for i in x: print(i)
def getFrequencyDictForText(sentence): fullTermsDict = multidict.MultiDict() tmpDict = {} # making dictionary for counting word frequencies for text in sentence.split(" "): # remove irrelevant words if re.match("a|the|an|the|to|in|for|of|or|by|with|is|on|that|but|from|than|be", text): continue val = tmpDict.get(text, 0) tmpDict[text.lower()] = val + 1 for key in tmpDict: fullTermsDict.add(key, tmpDict[key]) return fullTermsDict def makeImage(text): wc = WordCloud(width = 3000, height = 1080, background_color="white", colormap = 'Dark2', max_words=200) # generate word cloud wc.generate_from_frequencies(text) # save plt.imshow(wc) plt.axis("off") datestring = date.today().strftime("%b-%d-%Y") plt.text(860, -50, 'Date Generated: ' + datestring) filename = datestring + '.png' plt.savefig(os.path.join(os.getcwd(), '..', './static', filename), dpi = 400, bbox_inches='tight') # get text from existing word file tifile = open(os.path.join(os.getcwd(), '..','words.txt'), 'r') text = tifile.read() makeImage(getFrequencyDictForText(text)) tifile.close()
def get_frequency_dict_for_text(sentence): full_terms_dict = multidict.MultiDict() tmp_dict = {} for text in sentence.split(' '): if re.match('a|the|an|the|to|in|for|of|or|by|with|is|on|that|but|from|than|be', text): continue val = tmpDict.get(text, 0) tmpDict[text.lower()] = val + 1 for key in tmpDict: fullTermsDict.add(key, tmpDict[key]) return fullTermsDict def make_image(text): wc = word_cloud(width=3000, height=1080, background_color='white', colormap='Dark2', max_words=200) wc.generate_from_frequencies(text) plt.imshow(wc) plt.axis('off') datestring = date.today().strftime('%b-%d-%Y') plt.text(860, -50, 'Date Generated: ' + datestring) filename = datestring + '.png' plt.savefig(os.path.join(os.getcwd(), '..', './static', filename), dpi=400, bbox_inches='tight') tifile = open(os.path.join(os.getcwd(), '..', 'words.txt'), 'r') text = tifile.read() make_image(get_frequency_dict_for_text(text)) tifile.close()
class BoxaugError(Exception): pass
class Boxaugerror(Exception): pass
# short hand if a=23 b=4 if a > b: print("a is greater than b") # short hand if print("a is greater ") if a > b else print("b is greater ") #pass statements b=300 if b > a: pass
a = 23 b = 4 if a > b: print('a is greater than b') print('a is greater ') if a > b else print('b is greater ') b = 300 if b > a: pass
if args.algo in ['a2c', 'acktr']: values, action_log_probs, dist_entropy, conv_list = actor_critic.evaluate_actions(Variable(rollouts.states[:-1].view(-1, *obs_shape)), Variable(rollouts.actions.view(-1, action_shape))) # pre-process values = values.view(args.num_steps, num_processes_total, 1) action_log_probs = action_log_probs.view(args.num_steps, num_processes_total, 1) # compute afs loss afs_per_m_temp, afs_loss = actor_critic.get_afs_per_m( action_log_probs=action_log_probs, conv_list=conv_list, ) if len(afs_per_m_temp)>0: afs_per_m += [afs_per_m_temp] if (afs_loss is not None) and (afs_loss.data.cpu().numpy()[0]!=0.0): afs_loss.backward(mone, retain_graph=True) afs_loss_list += [afs_loss.data.cpu().numpy()[0]] advantages = Variable(rollouts.returns[:-1]) - values value_loss = advantages.pow(2).mean() action_loss = -(Variable(advantages.data) * action_log_probs).mean() final_loss_basic = value_loss * args.value_loss_coef + action_loss - dist_entropy * args.entropy_coef ewc_loss = None if j != 0: if ewc == 1: ewc_loss = actor_critic.get_ewc_loss(lam=ewc_lambda) if ewc_loss is None: final_loss = final_loss_basic else: final_loss = final_loss_basic + ewc_loss basic_loss_list += [final_loss_basic.data.cpu().numpy()[0]] final_loss.backward() if args.algo == 'a2c': nn.utils.clip_grad_norm(actor_critic.parameters(), args.max_grad_norm) optimizer.step() elif args.algo == 'ppo': advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1] advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-5) old_model.load_state_dict(actor_critic.state_dict()) if hasattr(actor_critic, 'obs_filter'): old_model.obs_filter = actor_critic.obs_filter for _ in range(args.ppo_epoch): sampler = BatchSampler(SubsetRandomSampler(range(num_processes_total * args.num_steps)), args.batch_size * num_processes_total, drop_last=False) for indices in sampler: indices = torch.LongTensor(indices) if args.cuda: indices = indices.cuda() states_batch = rollouts.states[:-1].view(-1, *obs_shape)[indices] actions_batch = rollouts.actions.view(-1, action_shape)[indices] return_batch = rollouts.returns[:-1].view(-1, 1)[indices] # Reshape to do in a single forward pass for all steps values, action_log_probs, dist_entropy, conv_list = actor_critic.evaluate_actions(Variable(states_batch), Variable(actions_batch)) _, old_action_log_probs, _, old_conv_list= old_model.evaluate_actions(Variable(states_batch, volatile=True), Variable(actions_batch, volatile=True)) ratio = torch.exp(action_log_probs - Variable(old_action_log_probs.data)) adv_targ = Variable(advantages.view(-1, 1)[indices]) surr1 = ratio * adv_targ surr2 = torch.clamp(ratio, 1.0 - args.clip_param, 1.0 + args.clip_param) * adv_targ action_loss = -torch.min(surr1, surr2).mean() # PPO's pessimistic surrogate (L^CLIP) value_loss = (Variable(return_batch) - values).pow(2).mean() optimizer.zero_grad() (value_loss + action_loss - dist_entropy * args.entropy_coef).backward() optimizer.step()
if args.algo in ['a2c', 'acktr']: (values, action_log_probs, dist_entropy, conv_list) = actor_critic.evaluate_actions(variable(rollouts.states[:-1].view(-1, *obs_shape)), variable(rollouts.actions.view(-1, action_shape))) values = values.view(args.num_steps, num_processes_total, 1) action_log_probs = action_log_probs.view(args.num_steps, num_processes_total, 1) (afs_per_m_temp, afs_loss) = actor_critic.get_afs_per_m(action_log_probs=action_log_probs, conv_list=conv_list) if len(afs_per_m_temp) > 0: afs_per_m += [afs_per_m_temp] if afs_loss is not None and afs_loss.data.cpu().numpy()[0] != 0.0: afs_loss.backward(mone, retain_graph=True) afs_loss_list += [afs_loss.data.cpu().numpy()[0]] advantages = variable(rollouts.returns[:-1]) - values value_loss = advantages.pow(2).mean() action_loss = -(variable(advantages.data) * action_log_probs).mean() final_loss_basic = value_loss * args.value_loss_coef + action_loss - dist_entropy * args.entropy_coef ewc_loss = None if j != 0: if ewc == 1: ewc_loss = actor_critic.get_ewc_loss(lam=ewc_lambda) if ewc_loss is None: final_loss = final_loss_basic else: final_loss = final_loss_basic + ewc_loss basic_loss_list += [final_loss_basic.data.cpu().numpy()[0]] final_loss.backward() if args.algo == 'a2c': nn.utils.clip_grad_norm(actor_critic.parameters(), args.max_grad_norm) optimizer.step() elif args.algo == 'ppo': advantages = rollouts.returns[:-1] - rollouts.value_preds[:-1] advantages = (advantages - advantages.mean()) / (advantages.std() + 1e-05) old_model.load_state_dict(actor_critic.state_dict()) if hasattr(actor_critic, 'obs_filter'): old_model.obs_filter = actor_critic.obs_filter for _ in range(args.ppo_epoch): sampler = batch_sampler(subset_random_sampler(range(num_processes_total * args.num_steps)), args.batch_size * num_processes_total, drop_last=False) for indices in sampler: indices = torch.LongTensor(indices) if args.cuda: indices = indices.cuda() states_batch = rollouts.states[:-1].view(-1, *obs_shape)[indices] actions_batch = rollouts.actions.view(-1, action_shape)[indices] return_batch = rollouts.returns[:-1].view(-1, 1)[indices] (values, action_log_probs, dist_entropy, conv_list) = actor_critic.evaluate_actions(variable(states_batch), variable(actions_batch)) (_, old_action_log_probs, _, old_conv_list) = old_model.evaluate_actions(variable(states_batch, volatile=True), variable(actions_batch, volatile=True)) ratio = torch.exp(action_log_probs - variable(old_action_log_probs.data)) adv_targ = variable(advantages.view(-1, 1)[indices]) surr1 = ratio * adv_targ surr2 = torch.clamp(ratio, 1.0 - args.clip_param, 1.0 + args.clip_param) * adv_targ action_loss = -torch.min(surr1, surr2).mean() value_loss = (variable(return_batch) - values).pow(2).mean() optimizer.zero_grad() (value_loss + action_loss - dist_entropy * args.entropy_coef).backward() optimizer.step()
''' Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. Example 1: Input: [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 Note: The length of the given array won't exceed 1000. The integers in the given array are in the range of [0, 1000]. ''' class Solution: def triangleNumber(self, nums: List[int]) -> int: nums.sort() res = 0 for i in reversed(range(len(nums))): j = 0 k = i - 1 while j < k: if nums[j] + nums[k] > nums[i]: res += k - j k -= 1 else: j += 1 return res
""" Given an array consists of non-negative integers, your task is to count the number of triplets chosen from the array that can make triangles if we take them as side lengths of a triangle. Example 1: Input: [2,2,3,4] Output: 3 Explanation: Valid combinations are: 2,3,4 (using the first 2) 2,3,4 (using the second 2) 2,2,3 Note: The length of the given array won't exceed 1000. The integers in the given array are in the range of [0, 1000]. """ class Solution: def triangle_number(self, nums: List[int]) -> int: nums.sort() res = 0 for i in reversed(range(len(nums))): j = 0 k = i - 1 while j < k: if nums[j] + nums[k] > nums[i]: res += k - j k -= 1 else: j += 1 return res
a = [0x77, 0x60, 0x76, 0x66, 0x72, 0x77, 0x7D, 0x73, 0x60, 0x3D, 0x64, 0x60, 0x39, 0x52, 0x66, 0x3B, 0x73, 0x7A, 0x23, 0x7D, 0x73, 0x4A, 0x70, 0x78, 0x6A, 0x46, 0x69, 0x2B, 0x76, 0x68, 0x41, 0x77, 0x41, 0x42, 0x49, 0x4A, 0x4A, 0x42, 0x40, 0x48, 0x5A, 0x5A, 0x45, 0x41, 0x59, 0x03, 0x5A, 0x4A, 0x51, 0x5C, 0x4F] flag = '' for i in range(len(a)): flag += chr(a[i]^i) print(flag) # watevr{th4nk5_h4ck1ng_for_s0ju_hackingforsoju.team}
a = [119, 96, 118, 102, 114, 119, 125, 115, 96, 61, 100, 96, 57, 82, 102, 59, 115, 122, 35, 125, 115, 74, 112, 120, 106, 70, 105, 43, 118, 104, 65, 119, 65, 66, 73, 74, 74, 66, 64, 72, 90, 90, 69, 65, 89, 3, 90, 74, 81, 92, 79] flag = '' for i in range(len(a)): flag += chr(a[i] ^ i) print(flag)
""" Datos de entrada: Nombre --> str --> A Compra --> float --> B Datos de salida: Total --> float --> C Nombre --> str --> A Compra --> float --> B Descuento --> float --> D """ # Entrada A = str(input("\nDigite tu nombre ")) B = float(input("Digite el valor de tu compra ")) # Caja negra if B < 50000: D = 0 elif 50000 <= B < 100000: D = .05 elif 100000 <= B < 700000: D = .11 elif 700000 <= B < 1500000: D = .18 else: D = .25 C = B - B * D # Salida print(f"\nHola {A}\nPara la compra: {B}\nEl valor a pagar es: {C}\nCon un descuento de: {B*D}\n")
""" Datos de entrada: Nombre --> str --> A Compra --> float --> B Datos de salida: Total --> float --> C Nombre --> str --> A Compra --> float --> B Descuento --> float --> D """ a = str(input('\nDigite tu nombre ')) b = float(input('Digite el valor de tu compra ')) if B < 50000: d = 0 elif 50000 <= B < 100000: d = 0.05 elif 100000 <= B < 700000: d = 0.11 elif 700000 <= B < 1500000: d = 0.18 else: d = 0.25 c = B - B * D print(f'\nHola {A}\nPara la compra: {B}\nEl valor a pagar es: {C}\nCon un descuento de: {B * D}\n')
# This code is provoded by MDS DSCI 531/532 def mds_special(): font = "Arial" axisColor = "#000000" gridColor = "#DEDDDD" return { "config": { "title": { "fontSize": 24, "font": font, "anchor": "start", # equivalent of left-aligned. "fontColor": "#000000" }, 'view': { "height": 300, "width": 400 }, "axisX": { "domain": True, #"domainColor": axisColor, "gridColor": gridColor, "domainWidth": 1, "grid": False, "labelFont": font, "labelFontSize": 12, "labelAngle": 0, "tickColor": axisColor, "tickSize": 5, # default, including it just to show you can change it "titleFont": font, "titleFontSize": 16, "titlePadding": 10, # guessing, not specified in styleguide "title": "X Axis Title (units)", }, "axisY": { "domain": False, "grid": True, "gridColor": gridColor, "gridWidth": 1, "labelFont": font, "labelFontSize": 14, "labelAngle": 0, #"ticks": False, # even if you don't have a "domain" you need to turn these off. "titleFont": font, "titleFontSize": 16, "titlePadding": 10, # guessing, not specified in styleguide "title": "Y Axis Title (units)", # titles are by default vertical left of axis so we need to hack this #"titleAngle": 0, # horizontal #"titleY": -10, # move it up #"titleX": 18, # move it to the right so it aligns with the labels }, } }
def mds_special(): font = 'Arial' axis_color = '#000000' grid_color = '#DEDDDD' return {'config': {'title': {'fontSize': 24, 'font': font, 'anchor': 'start', 'fontColor': '#000000'}, 'view': {'height': 300, 'width': 400}, 'axisX': {'domain': True, 'gridColor': gridColor, 'domainWidth': 1, 'grid': False, 'labelFont': font, 'labelFontSize': 12, 'labelAngle': 0, 'tickColor': axisColor, 'tickSize': 5, 'titleFont': font, 'titleFontSize': 16, 'titlePadding': 10, 'title': 'X Axis Title (units)'}, 'axisY': {'domain': False, 'grid': True, 'gridColor': gridColor, 'gridWidth': 1, 'labelFont': font, 'labelFontSize': 14, 'labelAngle': 0, 'titleFont': font, 'titleFontSize': 16, 'titlePadding': 10, 'title': 'Y Axis Title (units)'}}}
# Writing a method class Shape: def __init__(self, name, sides, colour=None): self.name = name self.sides = sides self.colour = colour def get_info(self): return '{} {} with {} sides'.format(self.colour, self.name, self.sides) s = Shape('square', 4, 'green') print(s.get_info()) # example of classmethod and staticmethod class Shape: def __init__(self, name, sides, colour=None): self.name = name self.sides = sides self.colour = colour @classmethod def green_shape(cls, name, sides): print(cls) return cls(name, sides, 'green') @staticmethod def trapezium_area(a, b, height): # area of trapezium = 0.5(a + b)h return 0.5 * (a + b) * height green = Shape.green_shape('rectangle', 4) print('{} {} with {} sides'.format(green.colour, green.name, green.sides)) print(Shape.trapezium_area(5, 7, 4)) # demonstrating differences when calling regular methods, classmethods # and staticmethods class Shape: def dummy_method(self, *args): print('self:', self) print('args:', *args) @classmethod def dummy_classmethod(cls, *args): print('cls :', cls) print('args:', *args) @staticmethod def dummy_staticmethod(*args): print('args:', *args) square = Shape() # calling regular method from instance square.dummy_method('arg') print(repr(square.dummy_method) + '\n') # calling regular method from class Shape.dummy_method('arg') print(repr(Shape.dummy_method) + '\n') # calling classmethod from instance square.dummy_classmethod('arg') print(repr(square.dummy_classmethod) + '\n') # calling classmethod from class Shape.dummy_classmethod('arg') print(repr(Shape.dummy_classmethod) + '\n') # calling staticmethod from instance square.dummy_staticmethod('arg') print(repr(square.dummy_staticmethod) + '\n') # calling staticmethod from class Shape.dummy_staticmethod('arg') print(repr(Shape.dummy_staticmethod) + '\n')
class Shape: def __init__(self, name, sides, colour=None): self.name = name self.sides = sides self.colour = colour def get_info(self): return '{} {} with {} sides'.format(self.colour, self.name, self.sides) s = shape('square', 4, 'green') print(s.get_info()) class Shape: def __init__(self, name, sides, colour=None): self.name = name self.sides = sides self.colour = colour @classmethod def green_shape(cls, name, sides): print(cls) return cls(name, sides, 'green') @staticmethod def trapezium_area(a, b, height): return 0.5 * (a + b) * height green = Shape.green_shape('rectangle', 4) print('{} {} with {} sides'.format(green.colour, green.name, green.sides)) print(Shape.trapezium_area(5, 7, 4)) class Shape: def dummy_method(self, *args): print('self:', self) print('args:', *args) @classmethod def dummy_classmethod(cls, *args): print('cls :', cls) print('args:', *args) @staticmethod def dummy_staticmethod(*args): print('args:', *args) square = shape() square.dummy_method('arg') print(repr(square.dummy_method) + '\n') Shape.dummy_method('arg') print(repr(Shape.dummy_method) + '\n') square.dummy_classmethod('arg') print(repr(square.dummy_classmethod) + '\n') Shape.dummy_classmethod('arg') print(repr(Shape.dummy_classmethod) + '\n') square.dummy_staticmethod('arg') print(repr(square.dummy_staticmethod) + '\n') Shape.dummy_staticmethod('arg') print(repr(Shape.dummy_staticmethod) + '\n')
""" A very simple class to make running tests a bit simpler. There are much stronger frameworks possible; this is a KISS framework. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, and their colleagues. """ class SimpleTestCase(object): """ A SimpleTestCase is a test to run. It has: -- The function to test, -- its argument(s), and -- its correct returned value. """ def __init__(self, function, arguments, correct_returned_value): """ The arguments are: -- The function to test -- The arguments to use in the test, as a sequence -- The correct returned value. For example, if the intended test is: foo(blah1, blah2, blah3) with correct returned value True, then its SimpleTestCase would be construced by: SimpleTestCase(foo, [blah1, blah2, blah3], True) Note that the arguments must be a SEQUENCE even if there is only a single argument and an EMPTY sequence if there are no arguments. For example: foo(blah) with correct returned value 88 would be constructed by: SimpleTestCase(foo, [blah], 88) """ self.function_to_test = function self.arguments_to_use = arguments self.correct_returned_value = correct_returned_value def run_test(self): """ Runs this test, printing appropriate messages. Returns True if your code passed the test, else False. Does not attempt to catch Exceptions. """ your_answer = self.function_to_test(*(self.arguments_to_use)) if your_answer == self.correct_returned_value: result = 'PASSED' else: result = 'FAILED' print() print('Your code {:6} this test'.format(result)) if len(self.arguments_to_use) == 0: format_string = ' ( )' else: f_beginning = ' {}( {} ' f_args = ', {}' * (len(self.arguments_to_use) - 1) format_string = f_beginning + f_args + ' )' print(format_string.format(self.function_to_test.__name__, *(self.arguments_to_use))) print(' The correct returned value is:', self.correct_returned_value) print(' Your code returned ..........:', your_answer) return (your_answer == self.correct_returned_value) @staticmethod def run_tests(function_name, tests): print() print('--------------------------------------------------') print('Testing the {} function:'.format(function_name)) print('--------------------------------------------------') failures = 0 for k in range(len(tests)): result = tests[k].run_test() if result is False: failures = failures + 1 if failures > 0: print() print('************************************') print('*** YOUR CODE FAILED SOME TESTS. ***') print('************************************')
""" A very simple class to make running tests a bit simpler. There are much stronger frameworks possible; this is a KISS framework. Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder, and their colleagues. """ class Simpletestcase(object): """ A SimpleTestCase is a test to run. It has: -- The function to test, -- its argument(s), and -- its correct returned value. """ def __init__(self, function, arguments, correct_returned_value): """ The arguments are: -- The function to test -- The arguments to use in the test, as a sequence -- The correct returned value. For example, if the intended test is: foo(blah1, blah2, blah3) with correct returned value True, then its SimpleTestCase would be construced by: SimpleTestCase(foo, [blah1, blah2, blah3], True) Note that the arguments must be a SEQUENCE even if there is only a single argument and an EMPTY sequence if there are no arguments. For example: foo(blah) with correct returned value 88 would be constructed by: SimpleTestCase(foo, [blah], 88) """ self.function_to_test = function self.arguments_to_use = arguments self.correct_returned_value = correct_returned_value def run_test(self): """ Runs this test, printing appropriate messages. Returns True if your code passed the test, else False. Does not attempt to catch Exceptions. """ your_answer = self.function_to_test(*self.arguments_to_use) if your_answer == self.correct_returned_value: result = 'PASSED' else: result = 'FAILED' print() print('Your code {:6} this test'.format(result)) if len(self.arguments_to_use) == 0: format_string = ' ( )' else: f_beginning = ' {}( {} ' f_args = ', {}' * (len(self.arguments_to_use) - 1) format_string = f_beginning + f_args + ' )' print(format_string.format(self.function_to_test.__name__, *self.arguments_to_use)) print(' The correct returned value is:', self.correct_returned_value) print(' Your code returned ..........:', your_answer) return your_answer == self.correct_returned_value @staticmethod def run_tests(function_name, tests): print() print('--------------------------------------------------') print('Testing the {} function:'.format(function_name)) print('--------------------------------------------------') failures = 0 for k in range(len(tests)): result = tests[k].run_test() if result is False: failures = failures + 1 if failures > 0: print() print('************************************') print('*** YOUR CODE FAILED SOME TESTS. ***') print('************************************')
class Solution: def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]: degree = [0] * n for u, v in edges: degree[v] = 1 return [i for i, d in enumerate(degree) if d == 0]
class Solution: def find_smallest_set_of_vertices(self, n: int, edges: List[List[int]]) -> List[int]: degree = [0] * n for (u, v) in edges: degree[v] = 1 return [i for (i, d) in enumerate(degree) if d == 0]
#!/usr/bin/env python DEBUG = True SECRET_KEY = 'super-ultra-secret-key' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:', } } INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'django_tables2', 'django_tables2_column_shifter', 'django_tables2_column_shifter.tests', ] ROOT_URLCONF = 'django_tables2_column_shifter.tests.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] LANGUAGE_CODE = 'en-us' MEDIA_URL = '/media/' STATIC_URL = '/static/' MIDDLEWARE = []
debug = True secret_key = 'super-ultra-secret-key' databases = {'default': {'ENGINE': 'django.db.backends.sqlite3', 'NAME': ':memory:'}} installed_apps = ['django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.staticfiles', 'django_tables2', 'django_tables2_column_shifter', 'django_tables2_column_shifter.tests'] root_urlconf = 'django_tables2_column_shifter.tests.urls' templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': {'context_processors': ['django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages']}}] language_code = 'en-us' media_url = '/media/' static_url = '/static/' middleware = []
# classical (x, y) position vectors class Pos: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return(Pos(self.x + other.x, self.y + other.y)) def __eq__(self, other): return( (self.x == other.x) and (self.y == other.y)) def __mul__(self, factor): return(Pos(factor * self.x, factor * self.y)) def __ne__(self, other): return(not(self == other)) def __str__(self): return("(" + str(self.x) + ", " + str(self.y) + ")") def __sub__(self, subtrahend): return(self + (subtrahend * -1))
class Pos: def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): return pos(self.x + other.x, self.y + other.y) def __eq__(self, other): return self.x == other.x and self.y == other.y def __mul__(self, factor): return pos(factor * self.x, factor * self.y) def __ne__(self, other): return not self == other def __str__(self): return '(' + str(self.x) + ', ' + str(self.y) + ')' def __sub__(self, subtrahend): return self + subtrahend * -1
# model settings model = dict( type='Recognizer3D', backbone=dict( type='C3D', # pretrained= # noqa: E251 # 'https://download.openmmlab.com/mmaction/recognition/c3d/c3d_sports1m_pretrain_20201016-dcc47ddc.pth', # noqa: E501 pretrained= # noqa: E251 './work_dirs/fatigue_c3d/c3d_sports1m_pretrain_20201016-dcc47ddc.pth', # noqa: E501 style='pytorch', conv_cfg=dict(type='Conv3d'), norm_cfg=None, act_cfg=dict(type='ReLU'), dropout_ratio=0.5, init_std=0.005), cls_head=dict( type='I3DHead', num_classes=2, in_channels=4096, spatial_type=None, dropout_ratio=0.5, init_std=0.01), # model training and testing settings train_cfg=None, test_cfg=dict(average_clips='score')) # dataset settings dataset_type = 'FatigueCleanDataset' data_root = '/zhourui/workspace/pro/fatigue/data/rawframes/new_clean/fatigue_clips' data_root_val = '/zhourui/workspace/pro/fatigue/data/rawframes/new_clean/fatigue_clips' facerect_data_prefix = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_info_from_yolov5' ann_file_train = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json' ann_file_val = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json' ann_file_test = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json' test_save_results_path = 'work_dirs/fatigue_c3d/valid_results_testone.npy' test_save_label_path = 'work_dirs/fatigue_c3d/valid_label_testone.npy' img_norm_cfg = dict(mean=[104, 117, 128], std=[1, 1, 1], to_bgr=False) # support clip len 16 only!!! clip_len = 16 train_pipeline = [ dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(112, 112), keep_ratio=False), #dict(type='RandomCrop', size=112), dict(type='Flip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label']) ] val_pipeline = [ dict( type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, test_mode=True, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(112, 112), keep_ratio=False), #dict(type='CenterCrop', crop_size=112), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] test_pipeline = [ dict( type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, test_mode=True, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(112, 112), keep_ratio=False), #dict(type='CenterCrop', crop_size=112), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs']) ] data = dict( videos_per_gpu=40, workers_per_gpu=4, pin_memory=False, train=dict( type=dataset_type, ann_file=ann_file_train, video_data_prefix=data_root, facerect_data_prefix=facerect_data_prefix, data_phase='train', test_mode=False, pipeline=train_pipeline, min_frames_before_fatigue=clip_len), val=dict( type=dataset_type, ann_file=ann_file_val, video_data_prefix=data_root_val, facerect_data_prefix=facerect_data_prefix, data_phase='valid', test_mode=True, test_all=False, pipeline=val_pipeline, min_frames_before_fatigue=clip_len), test=dict( type=dataset_type, ann_file=ann_file_test, video_data_prefix=data_root_val, facerect_data_prefix=facerect_data_prefix, data_phase='valid', test_mode=True, test_all=False, test_save_label_path=test_save_label_path, test_save_results_path=test_save_results_path, pipeline=test_pipeline, min_frames_before_fatigue=clip_len)) evaluation = dict( interval=5, metrics=['top_k_classes']) # optimizer optimizer = dict( type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005) # this lr is used for 8 gpus optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) # learning policy lr_config = dict(policy='step', step=[20, 40]) total_epochs = 45 checkpoint_config = dict(interval=1) log_config = dict( interval=20, hooks=[ dict(type='TextLoggerHook'), # dict(type='TensorboardLoggerHook'), ]) # runtime settings dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = f'./work_dirs/fatigue_c3d/' load_from = None resume_from = None workflow = [('train', 1)]
model = dict(type='Recognizer3D', backbone=dict(type='C3D', pretrained='./work_dirs/fatigue_c3d/c3d_sports1m_pretrain_20201016-dcc47ddc.pth', style='pytorch', conv_cfg=dict(type='Conv3d'), norm_cfg=None, act_cfg=dict(type='ReLU'), dropout_ratio=0.5, init_std=0.005), cls_head=dict(type='I3DHead', num_classes=2, in_channels=4096, spatial_type=None, dropout_ratio=0.5, init_std=0.01), train_cfg=None, test_cfg=dict(average_clips='score')) dataset_type = 'FatigueCleanDataset' data_root = '/zhourui/workspace/pro/fatigue/data/rawframes/new_clean/fatigue_clips' data_root_val = '/zhourui/workspace/pro/fatigue/data/rawframes/new_clean/fatigue_clips' facerect_data_prefix = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_info_from_yolov5' ann_file_train = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json' ann_file_val = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json' ann_file_test = '/zhourui/workspace/pro/fatigue/data/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json' test_save_results_path = 'work_dirs/fatigue_c3d/valid_results_testone.npy' test_save_label_path = 'work_dirs/fatigue_c3d/valid_label_testone.npy' img_norm_cfg = dict(mean=[104, 117, 128], std=[1, 1, 1], to_bgr=False) clip_len = 16 train_pipeline = [dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(112, 112), keep_ratio=False), dict(type='Flip', flip_ratio=0.5), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs', 'label'])] val_pipeline = [dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, test_mode=True, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(112, 112), keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])] test_pipeline = [dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, test_mode=True, out_of_bound_opt='repeat_last'), dict(type='FatigueRawFrameDecode'), dict(type='Resize', scale=(112, 112), keep_ratio=False), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])] data = dict(videos_per_gpu=40, workers_per_gpu=4, pin_memory=False, train=dict(type=dataset_type, ann_file=ann_file_train, video_data_prefix=data_root, facerect_data_prefix=facerect_data_prefix, data_phase='train', test_mode=False, pipeline=train_pipeline, min_frames_before_fatigue=clip_len), val=dict(type=dataset_type, ann_file=ann_file_val, video_data_prefix=data_root_val, facerect_data_prefix=facerect_data_prefix, data_phase='valid', test_mode=True, test_all=False, pipeline=val_pipeline, min_frames_before_fatigue=clip_len), test=dict(type=dataset_type, ann_file=ann_file_test, video_data_prefix=data_root_val, facerect_data_prefix=facerect_data_prefix, data_phase='valid', test_mode=True, test_all=False, test_save_label_path=test_save_label_path, test_save_results_path=test_save_results_path, pipeline=test_pipeline, min_frames_before_fatigue=clip_len)) evaluation = dict(interval=5, metrics=['top_k_classes']) optimizer = dict(type='SGD', lr=0.001, momentum=0.9, weight_decay=0.0005) optimizer_config = dict(grad_clip=dict(max_norm=40, norm_type=2)) lr_config = dict(policy='step', step=[20, 40]) total_epochs = 45 checkpoint_config = dict(interval=1) log_config = dict(interval=20, hooks=[dict(type='TextLoggerHook')]) dist_params = dict(backend='nccl') log_level = 'INFO' work_dir = f'./work_dirs/fatigue_c3d/' load_from = None resume_from = None workflow = [('train', 1)]
# # @lc app=leetcode id=55 lang=python # # [55] Jump Game # # https://leetcode.com/problems/jump-game/description/ # # algorithms # Medium (31.35%) # Total Accepted: 241.1K # Total Submissions: 767.2K # Testcase Example: '[2,3,1,1,4]' # # Given an array of non-negative integers, you are initially positioned at the # first index of the array. # # Each element in the array represents your maximum jump length at that # position. # # Determine if you are able to reach the last index. # # Example 1: # # # Input: [2,3,1,1,4] # Output: true # Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. # # # Example 2: # # # Input: [3,2,1,0,4] # Output: false # Explanation: You will always arrive at index 3 no matter what. Its # maximum # jump length is 0, which makes it impossible to reach the last index. # # # ''' class Solution(object): def solver(self, nums, start_pos, stop_pos): if start_pos == len(nums)-1: return True for i in range(start_pos, stop_pos+1): res = self.solver(nums, i, min(len(nums)-1, start_pos+nums[start_pos])) if res: return res return False def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ return self.solver(nums, 0, len(nums)-1) def canJump(self, nums): m = 0 for i, n in enumerate(nums): if i > m: return False m = max(m, i+n) return True ''' class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ goal = len(nums)-1 for i in range(len(nums))[::-1]: if i + nums[i] >= goal: goal = i return not goal
''' class Solution(object): def solver(self, nums, start_pos, stop_pos): if start_pos == len(nums)-1: return True for i in range(start_pos, stop_pos+1): res = self.solver(nums, i, min(len(nums)-1, start_pos+nums[start_pos])) if res: return res return False def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ return self.solver(nums, 0, len(nums)-1) def canJump(self, nums): m = 0 for i, n in enumerate(nums): if i > m: return False m = max(m, i+n) return True ''' class Solution(object): def can_jump(self, nums): """ :type nums: List[int] :rtype: bool """ goal = len(nums) - 1 for i in range(len(nums))[::-1]: if i + nums[i] >= goal: goal = i return not goal
class HelperProcessRequest: """ This class allows agents to express their need for a helper process that may be shared with other agents. """ def __init__(self, python_file_path: str, key: str, executable: str = None): """ :param python_file_path: The file that should be loaded and inspected for a subclass of BotHelperProcess. :param key: A key used to control the mapping of helper processes to bots. For example, you could set :param executable: A path to an executable that should be run as a separate process something like 'myBotType-team1' in order to get one shared helper process per team. """ self.python_file_path = python_file_path self.key = key self.executable = executable
class Helperprocessrequest: """ This class allows agents to express their need for a helper process that may be shared with other agents. """ def __init__(self, python_file_path: str, key: str, executable: str=None): """ :param python_file_path: The file that should be loaded and inspected for a subclass of BotHelperProcess. :param key: A key used to control the mapping of helper processes to bots. For example, you could set :param executable: A path to an executable that should be run as a separate process something like 'myBotType-team1' in order to get one shared helper process per team. """ self.python_file_path = python_file_path self.key = key self.executable = executable
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root is None: return None stack = deque([root,]) parent = {root: None} while stack: node = stack.pop() if node.left: parent[node.left] = node stack.append(node.left) if node.right: parent[node.right] = node stack.append(node.right) ancestors = set() while p: ancestors.add(p) p = parent[p] while q not in ancestors: q = parent[q] return q
class Solution: def lowest_common_ancestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': if root is None: return None stack = deque([root]) parent = {root: None} while stack: node = stack.pop() if node.left: parent[node.left] = node stack.append(node.left) if node.right: parent[node.right] = node stack.append(node.right) ancestors = set() while p: ancestors.add(p) p = parent[p] while q not in ancestors: q = parent[q] return q
def variance_of_sample_proportion(a,b,c,d,e,f,g,h,j,k): try: a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) j = int(j) k = int(k) sample = [a,b,c,d,e,f,g,h,j,k] # Count how many people are over the age 80 i = 0 occurrence = 0 while i < len(sample): if (sample[i])> 80: occurrence = occurrence + 1 else: i = i + 1 i = i + 1 # n is population size n = len(sample) # p is probability p = float(occurrence/n) var_samp_propor = float((p * (1-p))/n) print("variance_of_sample_proportion:",var_samp_propor ) return var_samp_propor except ZeroDivisionError: print("Error: Dividing by Zero is not valid!!") except ValueError: print ("Error: Only Numeric Values are valid!!")
def variance_of_sample_proportion(a, b, c, d, e, f, g, h, j, k): try: a = int(a) b = int(b) c = int(c) d = int(d) e = int(e) f = int(f) g = int(g) h = int(h) j = int(j) k = int(k) sample = [a, b, c, d, e, f, g, h, j, k] i = 0 occurrence = 0 while i < len(sample): if sample[i] > 80: occurrence = occurrence + 1 else: i = i + 1 i = i + 1 n = len(sample) p = float(occurrence / n) var_samp_propor = float(p * (1 - p) / n) print('variance_of_sample_proportion:', var_samp_propor) return var_samp_propor except ZeroDivisionError: print('Error: Dividing by Zero is not valid!!') except ValueError: print('Error: Only Numeric Values are valid!!')
class FlatList(list): """ This class inherits from list and has the same interface as a list-type. However, there is a 'data'-attribute introduced, that is required for the encoding of the list! The fields of the encoding-Schema must match the fields of the Object to be encoded! """ @property def data(self): return list(self) def __repr__(self): return '<{}: {}>'.format(self.__class__.__name__, list(self)) class ChannelList(FlatList): pass class TokensList(FlatList): pass class AddressList(FlatList): pass class PartnersPerTokenList(FlatList): pass class EventsList(FlatList): pass class Address(object): def __init__(self, token_address): self.address = token_address class PartnersPerToken(object): def __init__(self, partner_address, channel): self.partner_address = partner_address self.channel = channel class Channel(object): def __init__( self, channel_address, token_address, partner_address, settle_timeout, reveal_timeout, balance, state): self.channel_address = channel_address self.token_address = token_address self.partner_address = partner_address self.settle_timeout = settle_timeout self.reveal_timeout = reveal_timeout self.balance = balance self.state = state class ChannelNew(object): def __init__(self, netting_channel_address, participant1, participant2, settle_timeout): self.netting_channel_address = netting_channel_address self.participant1 = participant1 self.participant2 = participant2 self.settle_timeout = settle_timeout class ChannelNewBalance(object): def __init__( self, netting_channel_address, token_address, participant_address, new_balance, block_number): self.netting_channel_address = netting_channel_address self.token_address = token_address self.participant_address = participant_address self.new_balance = new_balance self.block_number = block_number class ChannelClosed(object): def __init__(self, netting_channel_address, closing_address, block_number): self.netting_channel_address = netting_channel_address self.closing_address = closing_address self.block_number = block_number class ChannelSettled(object): def __init__(self, netting_channel_address, block_number): self.netting_channel_address = netting_channel_address self.block_number = block_number class ChannelSecretRevealed(object): def __init__(self, netting_channel_address, secret): self.netting_channel_address = netting_channel_address self.secret = secret
class Flatlist(list): """ This class inherits from list and has the same interface as a list-type. However, there is a 'data'-attribute introduced, that is required for the encoding of the list! The fields of the encoding-Schema must match the fields of the Object to be encoded! """ @property def data(self): return list(self) def __repr__(self): return '<{}: {}>'.format(self.__class__.__name__, list(self)) class Channellist(FlatList): pass class Tokenslist(FlatList): pass class Addresslist(FlatList): pass class Partnerspertokenlist(FlatList): pass class Eventslist(FlatList): pass class Address(object): def __init__(self, token_address): self.address = token_address class Partnerspertoken(object): def __init__(self, partner_address, channel): self.partner_address = partner_address self.channel = channel class Channel(object): def __init__(self, channel_address, token_address, partner_address, settle_timeout, reveal_timeout, balance, state): self.channel_address = channel_address self.token_address = token_address self.partner_address = partner_address self.settle_timeout = settle_timeout self.reveal_timeout = reveal_timeout self.balance = balance self.state = state class Channelnew(object): def __init__(self, netting_channel_address, participant1, participant2, settle_timeout): self.netting_channel_address = netting_channel_address self.participant1 = participant1 self.participant2 = participant2 self.settle_timeout = settle_timeout class Channelnewbalance(object): def __init__(self, netting_channel_address, token_address, participant_address, new_balance, block_number): self.netting_channel_address = netting_channel_address self.token_address = token_address self.participant_address = participant_address self.new_balance = new_balance self.block_number = block_number class Channelclosed(object): def __init__(self, netting_channel_address, closing_address, block_number): self.netting_channel_address = netting_channel_address self.closing_address = closing_address self.block_number = block_number class Channelsettled(object): def __init__(self, netting_channel_address, block_number): self.netting_channel_address = netting_channel_address self.block_number = block_number class Channelsecretrevealed(object): def __init__(self, netting_channel_address, secret): self.netting_channel_address = netting_channel_address self.secret = secret
class ITypeHintingFactory(object): def make_param_provider(self): """ :rtype: rope.base.oi.type_hinting.providers.interfaces.IParamProvider """ raise NotImplementedError def make_return_provider(self): """ :rtype: rope.base.oi.type_hinting.providers.interfaces.IReturnProvider """ raise NotImplementedError def make_assignment_provider(self): """ :rtype: rope.base.oi.type_hinting.providers.interfaces.IAssignmentProvider """ raise NotImplementedError def make_resolver(self): """ :rtype: rope.base.oi.type_hinting.resolvers.interfaces.IResolver """ raise NotImplementedError
class Itypehintingfactory(object): def make_param_provider(self): """ :rtype: rope.base.oi.type_hinting.providers.interfaces.IParamProvider """ raise NotImplementedError def make_return_provider(self): """ :rtype: rope.base.oi.type_hinting.providers.interfaces.IReturnProvider """ raise NotImplementedError def make_assignment_provider(self): """ :rtype: rope.base.oi.type_hinting.providers.interfaces.IAssignmentProvider """ raise NotImplementedError def make_resolver(self): """ :rtype: rope.base.oi.type_hinting.resolvers.interfaces.IResolver """ raise NotImplementedError
class Stack: def __init__(self): self.stack = [] self.current_minimum = float('inf') def push(self, item): if not self.stack: self.stack.append(item) self.current_minimum = item else: if item >= self.current_minimum: self.stack.append(item) else: self.stack.append(2 * item - self.current_minimum) self.current_minimum = item def pop(self): if not self.stack: raise IndexError else: item = self.stack.pop() if item >= self.current_minimum: return item else: answer = self.current_minimum self.current_minimum = 2 * self.current_minimum - item return answer def peek(self): if not self.stack: raise IndexError else: item = self.stack[-1] if item >= self.current_minimum: return item else: return self.current_minimum def find_min(self): if not self.stack: return IndexError return self.current_minimum def __len__(self): return len(self.stack)
class Stack: def __init__(self): self.stack = [] self.current_minimum = float('inf') def push(self, item): if not self.stack: self.stack.append(item) self.current_minimum = item elif item >= self.current_minimum: self.stack.append(item) else: self.stack.append(2 * item - self.current_minimum) self.current_minimum = item def pop(self): if not self.stack: raise IndexError else: item = self.stack.pop() if item >= self.current_minimum: return item else: answer = self.current_minimum self.current_minimum = 2 * self.current_minimum - item return answer def peek(self): if not self.stack: raise IndexError else: item = self.stack[-1] if item >= self.current_minimum: return item else: return self.current_minimum def find_min(self): if not self.stack: return IndexError return self.current_minimum def __len__(self): return len(self.stack)
# -*- coding: utf-8 -*- # Return the contents of a file def load_file(filename): with open(filename, "r") as f: return f.read() # Write contents to a file def write_file(filename, content): with open(filename, "w+") as f: f.write(content) # Append contents to a file def append_file(filename, content): with open(filename, "a+") as f: f.write(content)
def load_file(filename): with open(filename, 'r') as f: return f.read() def write_file(filename, content): with open(filename, 'w+') as f: f.write(content) def append_file(filename, content): with open(filename, 'a+') as f: f.write(content)
def main(): t: tuple[i32, str] t = (1, 2) main()
def main(): t: tuple[i32, str] t = (1, 2) main()
# Config SIZES = { 'basic': 299 } NUM_CHANNELS = 3 NUM_CLASSES = 2 GENERATOR_BATCH_SIZE = 32 TOTAL_EPOCHS = 50 STEPS_PER_EPOCH = 100 VALIDATION_STEPS = 50 BASE_DIR = 'C:\\Users\\guilo\\mba-tcc\\data\\'
sizes = {'basic': 299} num_channels = 3 num_classes = 2 generator_batch_size = 32 total_epochs = 50 steps_per_epoch = 100 validation_steps = 50 base_dir = 'C:\\Users\\guilo\\mba-tcc\\data\\'
def test_split(): assert split(10) == 2 def test_string(): city = "String" assert type(city) == str def test_float(): price = 3.45 assert type(price) == float def test_int(): high_score = 1 assert type(high_score) == int def test_boolean(): is_having_fun = True assert type(is_having_fun) == bool def split(cash): bounty = cash / 5 print(bounty) return bounty
def test_split(): assert split(10) == 2 def test_string(): city = 'String' assert type(city) == str def test_float(): price = 3.45 assert type(price) == float def test_int(): high_score = 1 assert type(high_score) == int def test_boolean(): is_having_fun = True assert type(is_having_fun) == bool def split(cash): bounty = cash / 5 print(bounty) return bounty
""" ID: tony_hu1 PROG: milk2 LANG: PYTHON3 """ def read_in(infile): a = [] with open(infile) as filename: for line in filename: a.append(line.rstrip()) return a def milk_cows_main(flines): total = [] num_cows = int(flines[0]) for i in range(num_cows): b = flines[i+1].split(' ') total.append([int(b[0]),int(b[1])]) arrange(total) def arrange(total): total.sort() time= [[0,0]] for i in range(len(total)): a = total[i][0] b =time[len(time)-1][0] c =time[len(time)-1][1] judgement = (a >= b )and (a <= c) if judgement: period = [time[len(time)-1][0],max(total[i][1],time[len(time)-1][1])] time[len(time)-1] = period else: time.append(total[i]) if time[0]==[0,0]: del time[0] result(time) def result(total): no_cows = 0 for i in range(len(total)-1): x = total[i+1][0] - total[i][1] no_cows = max(no_cows,x) cows = 0 for i in range(len(total)): x = total[i][1] - total[i][0] cows = max(cows,x) fout = open ('milk2.out', 'w') a = str(cows) + ' ' + str(no_cows)+'\n' fout.write(a) flines = read_in("milk2.in") milk_cows_main(flines)
""" ID: tony_hu1 PROG: milk2 LANG: PYTHON3 """ def read_in(infile): a = [] with open(infile) as filename: for line in filename: a.append(line.rstrip()) return a def milk_cows_main(flines): total = [] num_cows = int(flines[0]) for i in range(num_cows): b = flines[i + 1].split(' ') total.append([int(b[0]), int(b[1])]) arrange(total) def arrange(total): total.sort() time = [[0, 0]] for i in range(len(total)): a = total[i][0] b = time[len(time) - 1][0] c = time[len(time) - 1][1] judgement = a >= b and a <= c if judgement: period = [time[len(time) - 1][0], max(total[i][1], time[len(time) - 1][1])] time[len(time) - 1] = period else: time.append(total[i]) if time[0] == [0, 0]: del time[0] result(time) def result(total): no_cows = 0 for i in range(len(total) - 1): x = total[i + 1][0] - total[i][1] no_cows = max(no_cows, x) cows = 0 for i in range(len(total)): x = total[i][1] - total[i][0] cows = max(cows, x) fout = open('milk2.out', 'w') a = str(cows) + ' ' + str(no_cows) + '\n' fout.write(a) flines = read_in('milk2.in') milk_cows_main(flines)
A = 'A' B = 'B' RULE_ACTION = { 1: 'Suck', 2: 'Right', 3: 'Left', 4: 'NoOp' } rules = { (A, 'Dirty'): 1, (B, 'Dirty'): 1, (A, 'Clean'): 2, (B, 'Clean'): 3, (A, B, 'Clean'): 4 } # Ex. rule (if location == A && Dirty then 1) Environment = { A: 'Dirty', B: 'Dirty', 'Current': A } def INTERPRET_INPUT(input): # No interpretation return input def RULE_MATCH(state, rules): # Match rule for a given state rule = rules.get(tuple(state)) return rule def SIMPLE_REFLEX_AGENT(percept): # Determine action state = INTERPRET_INPUT(percept) rule = RULE_MATCH(state, rules) action = RULE_ACTION[rule] return action def Sensors(): # Sense Environment location = Environment['Current'] return (location, Environment[location]) def Actuators(action): # Modify Environment location = Environment['Current'] if action == 'Suck': Environment[location] = 'Clean' elif action == 'Right' and location == A: Environment['Current'] = B elif action == 'Left' and location == B: Environment['Current'] = A def run(n): # run the agent through n steps print(' Current New') print('location status action location status') for i in range(1, n): (location, status) = Sensors() # Sense Environment before action print("{:12s}{:8s}".format(location, status), end='') action = SIMPLE_REFLEX_AGENT(Sensors()) Actuators(action) (location, status) = Sensors() # Sense Environment after action print("{:8s}{:12s}{:8s}".format(action, location, status)) if __name__ == '__main__': run(10)
a = 'A' b = 'B' rule_action = {1: 'Suck', 2: 'Right', 3: 'Left', 4: 'NoOp'} rules = {(A, 'Dirty'): 1, (B, 'Dirty'): 1, (A, 'Clean'): 2, (B, 'Clean'): 3, (A, B, 'Clean'): 4} environment = {A: 'Dirty', B: 'Dirty', 'Current': A} def interpret_input(input): return input def rule_match(state, rules): rule = rules.get(tuple(state)) return rule def simple_reflex_agent(percept): state = interpret_input(percept) rule = rule_match(state, rules) action = RULE_ACTION[rule] return action def sensors(): location = Environment['Current'] return (location, Environment[location]) def actuators(action): location = Environment['Current'] if action == 'Suck': Environment[location] = 'Clean' elif action == 'Right' and location == A: Environment['Current'] = B elif action == 'Left' and location == B: Environment['Current'] = A def run(n): print(' Current New') print('location status action location status') for i in range(1, n): (location, status) = sensors() print('{:12s}{:8s}'.format(location, status), end='') action = simple_reflex_agent(sensors()) actuators(action) (location, status) = sensors() print('{:8s}{:12s}{:8s}'.format(action, location, status)) if __name__ == '__main__': run(10)
def convert(s): s_split = s.split(' ') return s_split def niceprint(s): for i, elm in enumerate(s): print('Element #', i + 1, ' = ', elm, sep='') return None c1 = 10 c2 = 's'
def convert(s): s_split = s.split(' ') return s_split def niceprint(s): for (i, elm) in enumerate(s): print('Element #', i + 1, ' = ', elm, sep='') return None c1 = 10 c2 = 's'
# Source : https://leetcode.com/problems/reverse-string-ii/#/description # Author : Han Zichi # Date : 2017-04-23 class Solution(object): def reverseStr(self, s, k): """ :type s: str :type k: int :rtype: str """ l = len(s) tmp = [] for i in range(0, l, k * 2): tmp.append(s[i:i+k*2]) ans = '' for item in tmp: if k <= len(item) <= k * 2: ans += item[0:k][::-1] + item[k:min(k*2, len(item))] else: ans += item[::-1] return ans
class Solution(object): def reverse_str(self, s, k): """ :type s: str :type k: int :rtype: str """ l = len(s) tmp = [] for i in range(0, l, k * 2): tmp.append(s[i:i + k * 2]) ans = '' for item in tmp: if k <= len(item) <= k * 2: ans += item[0:k][::-1] + item[k:min(k * 2, len(item))] else: ans += item[::-1] return ans
# 1. def print_greeting(name, age_in_years, address): age_in_days = age_in_years * 365 age_in_years_1000_days_ago = (age_in_days - 1000) / 365 print("My name is " + name + " and I am " + str(age_in_years) + " years old (that's " + str(age_in_days) + " days). 1000 days ago, I was " + str(age_in_years_1000_days_ago) + " years old. My address is: " + address) address = """WeWork, 38 Chancery Lane, London, WC2A 1EN""" print_greeting("Tim Rogers", 25, address) # 2. def square(number=2): return number * number print("Two squared is " + str(square())) print("Four squared is " + str(square(4))) # 3. def powers(number=2): squared = number * number cubed = number * number * number return squared, cubed five_squared, five_cubed = powers(5) print( "Five squared is " + str(five_squared) + " and five cubed is " + str(five_cubed))
def print_greeting(name, age_in_years, address): age_in_days = age_in_years * 365 age_in_years_1000_days_ago = (age_in_days - 1000) / 365 print('My name is ' + name + ' and I am ' + str(age_in_years) + " years old (that's " + str(age_in_days) + ' days). 1000 days ago, I was ' + str(age_in_years_1000_days_ago) + ' years old. My address is: ' + address) address = 'WeWork,\n38 Chancery Lane,\nLondon,\nWC2A 1EN' print_greeting('Tim Rogers', 25, address) def square(number=2): return number * number print('Two squared is ' + str(square())) print('Four squared is ' + str(square(4))) def powers(number=2): squared = number * number cubed = number * number * number return (squared, cubed) (five_squared, five_cubed) = powers(5) print('Five squared is ' + str(five_squared) + ' and five cubed is ' + str(five_cubed))
# # PySNMP MIB module ASCEND-MIBIPSECSPD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ASCEND-MIBIPSECSPD-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:11:32 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # configuration, = mibBuilder.importSymbols("ASCEND-MIB", "configuration") OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Gauge32, Bits, Counter32, iso, IpAddress, Integer32, ModuleIdentity, Unsigned32, Counter64, ObjectIdentity, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Bits", "Counter32", "iso", "IpAddress", "Integer32", "ModuleIdentity", "Unsigned32", "Counter64", "ObjectIdentity", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "NotificationType") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class DisplayString(OctetString): pass mibmibProfIpsecSpd = MibIdentifier((1, 3, 6, 1, 4, 1, 529, 23, 168)) mibmibProfIpsecSpdTable = MibTable((1, 3, 6, 1, 4, 1, 529, 23, 168, 1), ) if mibBuilder.loadTexts: mibmibProfIpsecSpdTable.setStatus('mandatory') mibmibProfIpsecSpdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1), ).setIndexNames((0, "ASCEND-MIBIPSECSPD-MIB", "mibProfIpsecSpd-SpdName")) if mibBuilder.loadTexts: mibmibProfIpsecSpdEntry.setStatus('mandatory') mibProfIpsecSpd_SpdName = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 1), DisplayString()).setLabel("mibProfIpsecSpd-SpdName").setMaxAccess("readonly") if mibBuilder.loadTexts: mibProfIpsecSpd_SpdName.setStatus('mandatory') mibProfIpsecSpd_DefaultFilter = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 2), DisplayString()).setLabel("mibProfIpsecSpd-DefaultFilter").setMaxAccess("readwrite") if mibBuilder.loadTexts: mibProfIpsecSpd_DefaultFilter.setStatus('mandatory') mibProfIpsecSpd_Action_o = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noAction", 1), ("createProfile", 2), ("deleteProfile", 3)))).setLabel("mibProfIpsecSpd-Action-o").setMaxAccess("readwrite") if mibBuilder.loadTexts: mibProfIpsecSpd_Action_o.setStatus('mandatory') mibmibProfIpsecSpd_PolicyTable = MibTable((1, 3, 6, 1, 4, 1, 529, 23, 168, 2), ).setLabel("mibmibProfIpsecSpd-PolicyTable") if mibBuilder.loadTexts: mibmibProfIpsecSpd_PolicyTable.setStatus('mandatory') mibmibProfIpsecSpd_PolicyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1), ).setLabel("mibmibProfIpsecSpd-PolicyEntry").setIndexNames((0, "ASCEND-MIBIPSECSPD-MIB", "mibProfIpsecSpd-Policy-SpdName"), (0, "ASCEND-MIBIPSECSPD-MIB", "mibProfIpsecSpd-Policy-Index-o")) if mibBuilder.loadTexts: mibmibProfIpsecSpd_PolicyEntry.setStatus('mandatory') mibProfIpsecSpd_Policy_SpdName = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 1), DisplayString()).setLabel("mibProfIpsecSpd-Policy-SpdName").setMaxAccess("readonly") if mibBuilder.loadTexts: mibProfIpsecSpd_Policy_SpdName.setStatus('mandatory') mibProfIpsecSpd_Policy_Index_o = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 2), Integer32()).setLabel("mibProfIpsecSpd-Policy-Index-o").setMaxAccess("readonly") if mibBuilder.loadTexts: mibProfIpsecSpd_Policy_Index_o.setStatus('mandatory') mibProfIpsecSpd_Policy = MibScalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 3), DisplayString()).setLabel("mibProfIpsecSpd-Policy").setMaxAccess("readwrite") if mibBuilder.loadTexts: mibProfIpsecSpd_Policy.setStatus('mandatory') mibBuilder.exportSymbols("ASCEND-MIBIPSECSPD-MIB", mibmibProfIpsecSpdTable=mibmibProfIpsecSpdTable, mibProfIpsecSpd_SpdName=mibProfIpsecSpd_SpdName, mibmibProfIpsecSpd=mibmibProfIpsecSpd, mibProfIpsecSpd_Policy=mibProfIpsecSpd_Policy, mibmibProfIpsecSpd_PolicyEntry=mibmibProfIpsecSpd_PolicyEntry, mibProfIpsecSpd_Policy_Index_o=mibProfIpsecSpd_Policy_Index_o, mibmibProfIpsecSpdEntry=mibmibProfIpsecSpdEntry, mibProfIpsecSpd_Policy_SpdName=mibProfIpsecSpd_Policy_SpdName, mibmibProfIpsecSpd_PolicyTable=mibmibProfIpsecSpd_PolicyTable, mibProfIpsecSpd_Action_o=mibProfIpsecSpd_Action_o, DisplayString=DisplayString, mibProfIpsecSpd_DefaultFilter=mibProfIpsecSpd_DefaultFilter)
(configuration,) = mibBuilder.importSymbols('ASCEND-MIB', 'configuration') (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, single_value_constraint, constraints_union, value_range_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (gauge32, bits, counter32, iso, ip_address, integer32, module_identity, unsigned32, counter64, object_identity, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Bits', 'Counter32', 'iso', 'IpAddress', 'Integer32', 'ModuleIdentity', 'Unsigned32', 'Counter64', 'ObjectIdentity', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'NotificationType') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') class Displaystring(OctetString): pass mibmib_prof_ipsec_spd = mib_identifier((1, 3, 6, 1, 4, 1, 529, 23, 168)) mibmib_prof_ipsec_spd_table = mib_table((1, 3, 6, 1, 4, 1, 529, 23, 168, 1)) if mibBuilder.loadTexts: mibmibProfIpsecSpdTable.setStatus('mandatory') mibmib_prof_ipsec_spd_entry = mib_table_row((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1)).setIndexNames((0, 'ASCEND-MIBIPSECSPD-MIB', 'mibProfIpsecSpd-SpdName')) if mibBuilder.loadTexts: mibmibProfIpsecSpdEntry.setStatus('mandatory') mib_prof_ipsec_spd__spd_name = mib_scalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 1), display_string()).setLabel('mibProfIpsecSpd-SpdName').setMaxAccess('readonly') if mibBuilder.loadTexts: mibProfIpsecSpd_SpdName.setStatus('mandatory') mib_prof_ipsec_spd__default_filter = mib_scalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 2), display_string()).setLabel('mibProfIpsecSpd-DefaultFilter').setMaxAccess('readwrite') if mibBuilder.loadTexts: mibProfIpsecSpd_DefaultFilter.setStatus('mandatory') mib_prof_ipsec_spd__action_o = mib_scalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('noAction', 1), ('createProfile', 2), ('deleteProfile', 3)))).setLabel('mibProfIpsecSpd-Action-o').setMaxAccess('readwrite') if mibBuilder.loadTexts: mibProfIpsecSpd_Action_o.setStatus('mandatory') mibmib_prof_ipsec_spd__policy_table = mib_table((1, 3, 6, 1, 4, 1, 529, 23, 168, 2)).setLabel('mibmibProfIpsecSpd-PolicyTable') if mibBuilder.loadTexts: mibmibProfIpsecSpd_PolicyTable.setStatus('mandatory') mibmib_prof_ipsec_spd__policy_entry = mib_table_row((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1)).setLabel('mibmibProfIpsecSpd-PolicyEntry').setIndexNames((0, 'ASCEND-MIBIPSECSPD-MIB', 'mibProfIpsecSpd-Policy-SpdName'), (0, 'ASCEND-MIBIPSECSPD-MIB', 'mibProfIpsecSpd-Policy-Index-o')) if mibBuilder.loadTexts: mibmibProfIpsecSpd_PolicyEntry.setStatus('mandatory') mib_prof_ipsec_spd__policy__spd_name = mib_scalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 1), display_string()).setLabel('mibProfIpsecSpd-Policy-SpdName').setMaxAccess('readonly') if mibBuilder.loadTexts: mibProfIpsecSpd_Policy_SpdName.setStatus('mandatory') mib_prof_ipsec_spd__policy__index_o = mib_scalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 2), integer32()).setLabel('mibProfIpsecSpd-Policy-Index-o').setMaxAccess('readonly') if mibBuilder.loadTexts: mibProfIpsecSpd_Policy_Index_o.setStatus('mandatory') mib_prof_ipsec_spd__policy = mib_scalar((1, 3, 6, 1, 4, 1, 529, 23, 168, 2, 1, 3), display_string()).setLabel('mibProfIpsecSpd-Policy').setMaxAccess('readwrite') if mibBuilder.loadTexts: mibProfIpsecSpd_Policy.setStatus('mandatory') mibBuilder.exportSymbols('ASCEND-MIBIPSECSPD-MIB', mibmibProfIpsecSpdTable=mibmibProfIpsecSpdTable, mibProfIpsecSpd_SpdName=mibProfIpsecSpd_SpdName, mibmibProfIpsecSpd=mibmibProfIpsecSpd, mibProfIpsecSpd_Policy=mibProfIpsecSpd_Policy, mibmibProfIpsecSpd_PolicyEntry=mibmibProfIpsecSpd_PolicyEntry, mibProfIpsecSpd_Policy_Index_o=mibProfIpsecSpd_Policy_Index_o, mibmibProfIpsecSpdEntry=mibmibProfIpsecSpdEntry, mibProfIpsecSpd_Policy_SpdName=mibProfIpsecSpd_Policy_SpdName, mibmibProfIpsecSpd_PolicyTable=mibmibProfIpsecSpd_PolicyTable, mibProfIpsecSpd_Action_o=mibProfIpsecSpd_Action_o, DisplayString=DisplayString, mibProfIpsecSpd_DefaultFilter=mibProfIpsecSpd_DefaultFilter)
#!/usr/bin/env python # coding: utf-8 # In[2]: def utopianTree(cycles): h=1 for cyc_no in range(cycles): if (cyc_no%2==0): h=h*2 elif (cyc_no): h+=1 return h if __name__=='__main__': n=int(input()) for itr in range(n): cycles=int(input()) print(utopianTree(cycles)) # In[ ]:
def utopian_tree(cycles): h = 1 for cyc_no in range(cycles): if cyc_no % 2 == 0: h = h * 2 elif cyc_no: h += 1 return h if __name__ == '__main__': n = int(input()) for itr in range(n): cycles = int(input()) print(utopian_tree(cycles))
# Copyright 2020 InterDigital Communications, Inc. # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def rename_key(key): """Rename state_dict key.""" # ResidualBlockWithStride: 'downsample' -> 'skip' if ".downsample.bias" in key or ".downsample.weight" in key: return key.replace("downsample", "skip") return key def load_pretrained(state_dict): """Convert state_dict keys.""" state_dict = {rename_key(k): v for k, v in state_dict.items()} return state_dict
def rename_key(key): """Rename state_dict key.""" if '.downsample.bias' in key or '.downsample.weight' in key: return key.replace('downsample', 'skip') return key def load_pretrained(state_dict): """Convert state_dict keys.""" state_dict = {rename_key(k): v for (k, v) in state_dict.items()} return state_dict
def divisors(integer): aux = [i for i in range(2, integer) if integer % i == 0] if len(aux) == 0: return "{} is prime".format(integer) else: return aux
def divisors(integer): aux = [i for i in range(2, integer) if integer % i == 0] if len(aux) == 0: return '{} is prime'.format(integer) else: return aux
# coding: utf-8 pyslim_version = '0.700' slim_file_version = '0.7' # other file versions that require no modification compatible_slim_file_versions = ['0.7']
pyslim_version = '0.700' slim_file_version = '0.7' compatible_slim_file_versions = ['0.7']
""" Created on Sat Aug 27 12:52:52 2021 AI and deep learnin with Python Data types and operators Quiz Zip and Enumerate """ # Problem 1: """Use zip to write a for loop that creates a string specifying the label and coordinates of each point and appends it to the list points. Each string should be formatted as label: x, y, z. For example, the string for the first coordinate should be F: 23, 677, 4. """ x_coord = [23, 53, 2, -12, 95, 103, 14, -5] y_coord = [677, 233, 405, 433, 905, 376, 432, 445] z_coord = [4, 16, -6, -42, 3, -6, 23, -1] labels = ["F", "J", "A", "Q", "Y", "B", "W", "X"] points = [] for point in zip (labels, x_coord, y_coord, z_coord): points.append("{}: {}, {}, {}".format(*point)) for point in points: print(point) # Problem 2 """ Use zip to create a dictionary cast that uses names as keys and heights as values. """ cast_names = ["Barney", "Robin", "Ted", "Lily", "Marshall"] cast_heights = [72, 68, 72, 66, 76] cast = dict(zip(cast_names, cast_heights)) print(cast) # Problem 3 """ Unzip the cast tuple into two names and heights tuples. """ cast_details = {'Barney': 72, 'Robin': 68, 'Ted': 72, 'Lily': 66, 'Marshall': 76} cast_name, cast_height = zip(*cast_details.items()) print(cast_name, cast_height, end='\n') # Problem 4 """ Quiz: Transpose with Zip Use zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix. """ data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)) data_transpose = tuple(zip(*data))# replace with your code print(data_transpose) # Problem 5 """ Quiz: Enumerate Use enumerate to modify the cast list so that each element contains the name followed by the character's corresponding height. For example, the first element of cast should change from "Barney Stinson" to "Barney Stinson 72". """ cast = ["Barney Stinson", "Robin Scherbatsky", "Ted Mosby", "Lily Aldrin", "Marshall Eriksen"] heights = [72, 68, 72, 66, 76] for i, character in enumerate(cast): cast[i] = character + " " + str(heights[i]) print(cast)
""" Created on Sat Aug 27 12:52:52 2021 AI and deep learnin with Python Data types and operators Quiz Zip and Enumerate """ 'Use zip to write a for loop that creates a string specifying the label \nand coordinates of each point and appends it to the list points. \nEach string should be formatted as label: x, y, z. For example, the string \nfor the first coordinate should be F: 23, 677, 4. ' x_coord = [23, 53, 2, -12, 95, 103, 14, -5] y_coord = [677, 233, 405, 433, 905, 376, 432, 445] z_coord = [4, 16, -6, -42, 3, -6, 23, -1] labels = ['F', 'J', 'A', 'Q', 'Y', 'B', 'W', 'X'] points = [] for point in zip(labels, x_coord, y_coord, z_coord): points.append('{}: {}, {}, {}'.format(*point)) for point in points: print(point) '\nUse zip to create a dictionary cast that uses names as keys and \nheights as values.\n' cast_names = ['Barney', 'Robin', 'Ted', 'Lily', 'Marshall'] cast_heights = [72, 68, 72, 66, 76] cast = dict(zip(cast_names, cast_heights)) print(cast) '\nUnzip the cast tuple into two names and heights tuples.\n' cast_details = {'Barney': 72, 'Robin': 68, 'Ted': 72, 'Lily': 66, 'Marshall': 76} (cast_name, cast_height) = zip(*cast_details.items()) print(cast_name, cast_height, end='\n') '\nQuiz: Transpose with Zip\nUse zip to transpose data from a 4-by-3 matrix to a 3-by-4 matrix. \n' data = ((0, 1, 2), (3, 4, 5), (6, 7, 8), (9, 10, 11)) data_transpose = tuple(zip(*data)) print(data_transpose) ' \nQuiz: Enumerate\nUse enumerate to modify the cast list so that each element contains the name \nfollowed by the character\'s corresponding height. For example, the first \nelement of cast should change from "Barney Stinson" to "Barney Stinson 72".\n' cast = ['Barney Stinson', 'Robin Scherbatsky', 'Ted Mosby', 'Lily Aldrin', 'Marshall Eriksen'] heights = [72, 68, 72, 66, 76] for (i, character) in enumerate(cast): cast[i] = character + ' ' + str(heights[i]) print(cast)
def format_as_vsys(amount): abs_amount = abs(amount) whole = int(abs_amount / 100000000) fraction = abs_amount % 100000000 if amount < 0: whole *= -1 return f'{whole}.{str(fraction).rjust(8, "0")}'
def format_as_vsys(amount): abs_amount = abs(amount) whole = int(abs_amount / 100000000) fraction = abs_amount % 100000000 if amount < 0: whole *= -1 return f"{whole}.{str(fraction).rjust(8, '0')}"
class Solution: def canVisitAllRooms(self, rooms): stack = [0] visited = set(stack) while stack: curr = stack.pop() for room in rooms[curr]: if room not in visited: stack.append(room) visited.add(room) if len(visited) == len(rooms): return True return len(visited) == len(rooms)
class Solution: def can_visit_all_rooms(self, rooms): stack = [0] visited = set(stack) while stack: curr = stack.pop() for room in rooms[curr]: if room not in visited: stack.append(room) visited.add(room) if len(visited) == len(rooms): return True return len(visited) == len(rooms)
__author__ = 'spersinger' class Configuration: @staticmethod def run(): Configuration.enforce_ttl = True Configuration.ttl = 60 Configuration.run()
__author__ = 'spersinger' class Configuration: @staticmethod def run(): Configuration.enforce_ttl = True Configuration.ttl = 60 Configuration.run()
##### # https://github.com/sushiswap/sushiswap-subgraph # https://dev.sushi.com/api/overview # https://github.com/sushiswap/sushiswap-analytics/blob/c6919d56523b4418d174224a6b8964982f2a7948/src/core/api/index.js # CP_API_TOKEN = os.environ.get("cp_api_token") #"https://gateway.thegraph.com/api/c8eae2e5ac9d2e9d5d5459c33fe7b1eb/subgraphs/id/0x4bb4c1b0745ef7b4642feeccd0740dec417ca0a0-0" # "https://thegraph.com/legacy-explorer/subgraph/sushiswap/exchange" ##### url = { "sushiexchange" : "https://api.thegraph.com/subgraphs/name/sushiswap/exchange", "sushibar" : "https://api.thegraph.com/subgraphs/name/matthewlilley/bar", "aave" : "https://api.thegraph.com/subgraphs/name/aave/protocol-v2" }
url = {'sushiexchange': 'https://api.thegraph.com/subgraphs/name/sushiswap/exchange', 'sushibar': 'https://api.thegraph.com/subgraphs/name/matthewlilley/bar', 'aave': 'https://api.thegraph.com/subgraphs/name/aave/protocol-v2'}
""" Telemac-Mascaret exceptions """ class TelemacException(Exception): """ Generic exception class for all of Telemac-Mascaret Exceptions """ pass class MascaretException(TelemacException): """ Generic exception class for all of Telemac-Mascaret Exceptions """ pass
""" Telemac-Mascaret exceptions """ class Telemacexception(Exception): """ Generic exception class for all of Telemac-Mascaret Exceptions """ pass class Mascaretexception(TelemacException): """ Generic exception class for all of Telemac-Mascaret Exceptions """ pass
# -*- coding: utf-8 -*- commands = { 'start_AfterAuthorized': u'Welcome to remoteSsh_bot\n\n' u'If you known password - use /on\n' u'else - connect to admin', 'start_BeforeAuthorized': u'Hello!\n' u'If you want information about this bot - use /information\n' u'If you want command list - use /help', 'help_AfterAuthorized': u'If you known password - use /on\n' u'else - connect to admin', 'help_BeforeAuthorized': u'Command:\n' u'/off - disconnect from bot\n' u'/setsshUser - Set ssh user and ssh password\n' u'/setsshHost - Set host(IP) for ssh connection\n' u'/information - Show information, about ssh-connection\n' u'/aboutBot - Information about bot and author\n', 'aboutBot': 'Author GitHub - https://github.com/vzemtsov\n' u'Please write wishes to improve this bot', }
commands = {'start_AfterAuthorized': u'Welcome to remoteSsh_bot\n\nIf you known password - use /on\nelse - connect to admin', 'start_BeforeAuthorized': u'Hello!\nIf you want information about this bot - use /information\nIf you want command list - use /help', 'help_AfterAuthorized': u'If you known password - use /on\nelse - connect to admin', 'help_BeforeAuthorized': u'Command:\n/off - disconnect from bot\n/setsshUser - Set ssh user and ssh password\n/setsshHost - Set host(IP) for ssh connection\n/information - Show information, about ssh-connection\n/aboutBot - Information about bot and author\n', 'aboutBot': 'Author GitHub - https://github.com/vzemtsov\nPlease write wishes to improve this bot'}
# -*- coding: utf-8 -*- """ Created on Mon Feb 5 14:31:36 2018 @author: User """ # part 1-e def multlist(m1, m2): lenof = len(m1) newl = [] for i in range(lenof): newl.append( m1[i]* m2[i]) print(None) m1=[1, 2, 23, 104] m2=[-3, 2, 0, 6] multlist(m1, m2) # part 1-a #def createodds(n): # lofodds = [] # for i in range(1,n, 2): # lofodds.append(i) # print(lofodds) #createodds(0) # part 1-b #def spllist(n): # newlist = [] # for i in range(1,n): # smallist = list(range(1,i)) # newlist += [smallist] # print(newlist[1:]) #spllist(6) # part 1-c #def divisibles(n): # lol = [] # for i in range(1, int(n/2)+1): ## print(i) # if n%i == 0: # lol.append(i) # print(lol) # #divisibles(19) # part 1-d #def update(l, a, b): # count = 0 # newl = l # for i in range(len(l )): ## print(l[i]) # if l[i] == a: # newl[i] = b # count += 1 # s = ('newlist is {0}, and {1} was replaced {2} times') # print(s.format(newl, a, count)) # #nl = [3, 10, 5, 10, -4] #update(nl, 10, 7) #def afn(los): # join various elements of a list recursively # news = los[0:] # if los == []: # return # else: ## print(los[1:]) # news = news + [afn(los[1:])] # print(news) # #s = ['abc', 12, True, '',-12.4] #print(afn(s))
""" Created on Mon Feb 5 14:31:36 2018 @author: User """ def multlist(m1, m2): lenof = len(m1) newl = [] for i in range(lenof): newl.append(m1[i] * m2[i]) print(None) m1 = [1, 2, 23, 104] m2 = [-3, 2, 0, 6] multlist(m1, m2)
''' ''' def main(): info('Pump Microbone') close(description="Jan Inlet") if is_closed('F'): open(description= 'Microbone to CO2 Laser') else: close(name="T", description="Microbone to CO2 Laser") sleep(1) close(description= 'CO2 Laser to Roughing') #close(description= 'Microbone to Minibone') open(description= 'Microbone to Turbo') open(description= 'Microbone to Getter NP-10H') open(description= 'Microbone to Getter NP-10C') #open(description= 'Microbone to CO2 Laser') open(description= 'Microbone to Inlet Pipette') sleep(1) set_resource(name='CO2PumpTimeFlag', value=30) release('JanCO2Flag')
""" """ def main(): info('Pump Microbone') close(description='Jan Inlet') if is_closed('F'): open(description='Microbone to CO2 Laser') else: close(name='T', description='Microbone to CO2 Laser') sleep(1) close(description='CO2 Laser to Roughing') open(description='Microbone to Turbo') open(description='Microbone to Getter NP-10H') open(description='Microbone to Getter NP-10C') open(description='Microbone to Inlet Pipette') sleep(1) set_resource(name='CO2PumpTimeFlag', value=30) release('JanCO2Flag')
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse, obj[16]: Carryaway, obj[17]: Restaurantlessthan20, obj[18]: Restaurant20to50, obj[19]: Direction_same, obj[20]: Distance # {"feature": "Education", "instances": 41, "metric_value": 0.9892, "depth": 1} if obj[11]>1: # {"feature": "Occupation", "instances": 26, "metric_value": 0.9612, "depth": 2} if obj[12]>3: # {"feature": "Income", "instances": 20, "metric_value": 1.0, "depth": 3} if obj[13]>1: # {"feature": "Maritalstatus", "instances": 17, "metric_value": 0.9774, "depth": 4} if obj[9]<=1: # {"feature": "Carryaway", "instances": 15, "metric_value": 0.9183, "depth": 5} if obj[16]>1.0: # {"feature": "Children", "instances": 13, "metric_value": 0.7793, "depth": 6} if obj[10]<=0: return 'True' elif obj[10]>0: # {"feature": "Gender", "instances": 6, "metric_value": 1.0, "depth": 7} if obj[7]<=0: return 'False' elif obj[7]>0: return 'True' else: return 'True' else: return 'False' elif obj[16]<=1.0: return 'False' else: return 'False' elif obj[9]>1: return 'False' else: return 'False' elif obj[13]<=1: return 'False' else: return 'False' elif obj[12]<=3: return 'False' else: return 'False' elif obj[11]<=1: # {"feature": "Income", "instances": 15, "metric_value": 0.5665, "depth": 2} if obj[13]>2: return 'True' elif obj[13]<=2: # {"feature": "Coffeehouse", "instances": 4, "metric_value": 1.0, "depth": 3} if obj[15]<=0.0: return 'False' elif obj[15]>0.0: return 'True' else: return 'True' else: return 'False' else: return 'True'
def find_decision(obj): if obj[11] > 1: if obj[12] > 3: if obj[13] > 1: if obj[9] <= 1: if obj[16] > 1.0: if obj[10] <= 0: return 'True' elif obj[10] > 0: if obj[7] <= 0: return 'False' elif obj[7] > 0: return 'True' else: return 'True' else: return 'False' elif obj[16] <= 1.0: return 'False' else: return 'False' elif obj[9] > 1: return 'False' else: return 'False' elif obj[13] <= 1: return 'False' else: return 'False' elif obj[12] <= 3: return 'False' else: return 'False' elif obj[11] <= 1: if obj[13] > 2: return 'True' elif obj[13] <= 2: if obj[15] <= 0.0: return 'False' elif obj[15] > 0.0: return 'True' else: return 'True' else: return 'False' else: return 'True'
bil = 0 count = 0 hasil = 0 while(bil <= 100): if(bil % 2 == 1): count += 1 hasil += bil print(bil) bil += 1 print('Banyaknya bilangan ganjil :', count) print('Jumlah seluruh bilangan :', hasil)
bil = 0 count = 0 hasil = 0 while bil <= 100: if bil % 2 == 1: count += 1 hasil += bil print(bil) bil += 1 print('Banyaknya bilangan ganjil :', count) print('Jumlah seluruh bilangan :', hasil)
def mapping_Luo(t=1): names = [ 'Yao_6_2', 'AB_TMA_2', 'ABA_TMA_2', 'ABAB_TMA_2', 'ABABA_TMA_2', 'ABABA_IPrMeP_2'] xlocs = [ 21400, 5500, -7200, -11700, -17200, -30700] ylocs = [ 0, 0, 0, 0, 0, 0] zlocs = [ 2700, 2700, 2700, 2700, 2700, 2700] x_range=[[0, 500, 21], [0, 500, 21], [0, 500, 21], [0, 500, 21], [0, 500, 21], [0, 500, 21]] y_range=[[0, 500, 101],[0, 500, 101],[0, 500, 101], [0, 500, 101],[0, 500, 101],[0, 500, 101]] wa_range=[ [0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3]] # names = ['CRP_2_275', 'CRP_1_131', 'Yao_6', 'CRP_2_275F', 'CRP_1_275A', 'AB_TMA', 'iPrMeP_stat', 'ABA_TMA', 'ABAB_TMA', 'ABABA_TMA', # 'TMA_stat', 'ABABA_IPrMeP' ] # xlocs = [30400, 26100, 21400, 16200, 9600, 5500, -500, -7200, # -11700, -17200, -23700, -30700] # ylocs = [0, 0, 0, 0, 0, 0, 0, 0, # 0, 0, 0, 0] # zlocs = [2700, 2700, 2700, 2700, 2700, 2700, 2700, 2700, # 2700, 2700, 2700, 2700] # x_range=[[0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11], # [0, 500, 11], [0, 500, 11], [0, 500, 11], [0, 500, 11]] # y_range=[[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101], # [0, 500, 101],[0, 500, 101],[0, 500, 101],[0, 500, 101]] # wa_range=[[0, 26, 5], [0, 13, 3], [0, 26, 5], [0, 26, 5], [0, 26, 5], [0, 13, 3], [0, 13, 3], [0, 13, 3], # [0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3]] user = 'AL' det_exposure_time(t,t) assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(names)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(ylocs)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(zlocs)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(x_range)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(y_range)})' assert len(xlocs) == len(wa_range), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(wa_range)})' # Detectors, motors: dets = [pil300KW, pil1M] for num, (x, y, sample, x_r, y_r, wax_ra) in enumerate(zip(xlocs, ylocs, names, x_range, y_range, wa_range)): if num == 0: proposal_id('2121_1', '307948_Luo') else: proposal_id('2121_1', '307948_Luo2') pil1M.cam.file_path.put('/nsls2/xf12id2/data/images/users/2021_1/307948_Luo2/1M/%s'%sample) pil300KW.cam.file_path.put('/nsls2/xf12id2/data/images/users/2021_1/307948_Luo2/300KW/%s'%sample) for wa in np.linspace(wax_ra[0], wax_ra[1], wax_ra[2]): yield from bps.mv(waxs, wa) yield from bps.mv(piezo.x, x) yield from bps.mv(piezo.y, y+500) name_fmt = '{sam}_4m_16.1keV_wa{waxs}' sample_name = name_fmt.format(sam=sample, waxs='%2.1f'%wa) sample_id(user_name=user, sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.rel_grid_scan(dets, piezo.y, *y_r, piezo.x, *x_r, 0) #1 = snake, 0 = not-snake sample_id(user_name='test', sample_name='test') det_exposure_time(0.3,0.3)
def mapping__luo(t=1): names = ['Yao_6_2', 'AB_TMA_2', 'ABA_TMA_2', 'ABAB_TMA_2', 'ABABA_TMA_2', 'ABABA_IPrMeP_2'] xlocs = [21400, 5500, -7200, -11700, -17200, -30700] ylocs = [0, 0, 0, 0, 0, 0] zlocs = [2700, 2700, 2700, 2700, 2700, 2700] x_range = [[0, 500, 21], [0, 500, 21], [0, 500, 21], [0, 500, 21], [0, 500, 21], [0, 500, 21]] y_range = [[0, 500, 101], [0, 500, 101], [0, 500, 101], [0, 500, 101], [0, 500, 101], [0, 500, 101]] wa_range = [[0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3], [0, 13, 3]] user = 'AL' det_exposure_time(t, t) assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(names)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(ylocs)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(zlocs)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(x_range)})' assert len(xlocs) == len(names), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(y_range)})' assert len(xlocs) == len(wa_range), f'Number of X coordinates ({len(xlocs)}) is different from number of samples ({len(wa_range)})' dets = [pil300KW, pil1M] for (num, (x, y, sample, x_r, y_r, wax_ra)) in enumerate(zip(xlocs, ylocs, names, x_range, y_range, wa_range)): if num == 0: proposal_id('2121_1', '307948_Luo') else: proposal_id('2121_1', '307948_Luo2') pil1M.cam.file_path.put('/nsls2/xf12id2/data/images/users/2021_1/307948_Luo2/1M/%s' % sample) pil300KW.cam.file_path.put('/nsls2/xf12id2/data/images/users/2021_1/307948_Luo2/300KW/%s' % sample) for wa in np.linspace(wax_ra[0], wax_ra[1], wax_ra[2]): yield from bps.mv(waxs, wa) yield from bps.mv(piezo.x, x) yield from bps.mv(piezo.y, y + 500) name_fmt = '{sam}_4m_16.1keV_wa{waxs}' sample_name = name_fmt.format(sam=sample, waxs='%2.1f' % wa) sample_id(user_name=user, sample_name=sample_name) print(f'\n\t=== Sample: {sample_name} ===\n') yield from bp.rel_grid_scan(dets, piezo.y, *y_r, piezo.x, *x_r, 0) sample_id(user_name='test', sample_name='test') det_exposure_time(0.3, 0.3)
# -*- coding: utf-8 -*- """ Created on Mon Feb 12 21:55:16 2018 @author: User """ def by_courses(file): lol = [] name_dict = {} f = open(file, 'r') all_details = f.read() lol.append([all_details]) f.close() all_details = [line for line in all_details.split('\n') if line.strip() != ''] # strip the lines of newline and blank line for each in all_details: each = ((each.split(' '))) name = each[0] + ' ' + each[1] courses = (each[2::]) courses = un_camel(courses) courses = [item for item in courses.split(' ')] # split into courses courses = [x for x in courses if x!= ''] # remove empty name_dict[name] = (courses) for k, v in name_dict.items(): print(k,'-->', v) all_courses = (list(name_dict.values())) courses_set = [] for each in all_courses: for item in each: if item in courses_set: pass else: courses_set.append(item) revDict(name_dict, courses_set) def revDict(name_dict, alist): d1 = {k: [] for k in alist} # initialize an empty dictionary for all the courses for k, v in name_dict.items(): for i in v: if i in alist: # if the course name in alist d1[i].append(k) # append the name for k,v in d1.items(): print([k, sorted(v)]) def un_camel(courses): # convert from camelcase to uppercase uc_text = '' for x in courses: for item in x: if item.islower(): uc_text += item.upper() else: uc_text += item uc_text += ' ' # to add blank spaces between courses return uc_text by_courses('Names.txt') # b = {y:x for x,y in name_dict.items()} # just an experiment to see dictionary reversal - doesn't help in this case tho # print(b.items())
""" Created on Mon Feb 12 21:55:16 2018 @author: User """ def by_courses(file): lol = [] name_dict = {} f = open(file, 'r') all_details = f.read() lol.append([all_details]) f.close() all_details = [line for line in all_details.split('\n') if line.strip() != ''] for each in all_details: each = each.split(' ') name = each[0] + ' ' + each[1] courses = each[2:] courses = un_camel(courses) courses = [item for item in courses.split(' ')] courses = [x for x in courses if x != ''] name_dict[name] = courses for (k, v) in name_dict.items(): print(k, '-->', v) all_courses = list(name_dict.values()) courses_set = [] for each in all_courses: for item in each: if item in courses_set: pass else: courses_set.append(item) rev_dict(name_dict, courses_set) def rev_dict(name_dict, alist): d1 = {k: [] for k in alist} for (k, v) in name_dict.items(): for i in v: if i in alist: d1[i].append(k) for (k, v) in d1.items(): print([k, sorted(v)]) def un_camel(courses): uc_text = '' for x in courses: for item in x: if item.islower(): uc_text += item.upper() else: uc_text += item uc_text += ' ' return uc_text by_courses('Names.txt')
def alpha_numeric(m): return re.sub('[^A-Za-z0-9]+', ' ', m) def uri_from_fields(fields): string = '_'.join(alpha_numeric(f.strip().lower()) for f in fields) if len(string) == len(fields)-1: return '' return string def splitLocation(location): return re.search('[NS]',location).start() def getLatitude(s,l): second = float(s[-2:]) minute = float(s[-4:-2]) degree = float(s[:-4]) if l == "N": return str(degree+minute/60+second/3600) else: return str(-degree-minute/60-second/3600) def getLongitude(s,l): second = float(s[-2:]) minute = float(s[-4:-2]) degree = float(s[:-4]) if l == "E": return str(degree+minute/60+second/3600) else: return str(-degree-minute/60-second/3600) def ISOtime(s): MM_dict = {"JAN":"01","FEB":"02","MAR":"03","APR":"04","MAY":"05","JUN":"06","JUL":"07","AUG":"08","SEP":"09","OCT":"10","NOV":"11","DEC":"12"} return s[:4]+MM_dict[s[4:7]]+s[7:9]+"T"+s[9:11]+":"+s[11:] def parseFstatOutput(s): if s[-3:] == "NOP": return "baseClosed" if s[-3:] == "OPR": return "baseOpen" def parseEstatAction(action): if action == "ABORT": return "missionAbort" elif action == "LANDED": return "missionLanded" elif action == "REFUEL": return "aircraftRefuel" elif action == "RTB": return "missionReturnToBase" elif action == "TAKEOFF": return "aircraftTakeoff" elif action == "ON STATION": return "missionOnStation"
def alpha_numeric(m): return re.sub('[^A-Za-z0-9]+', ' ', m) def uri_from_fields(fields): string = '_'.join((alpha_numeric(f.strip().lower()) for f in fields)) if len(string) == len(fields) - 1: return '' return string def split_location(location): return re.search('[NS]', location).start() def get_latitude(s, l): second = float(s[-2:]) minute = float(s[-4:-2]) degree = float(s[:-4]) if l == 'N': return str(degree + minute / 60 + second / 3600) else: return str(-degree - minute / 60 - second / 3600) def get_longitude(s, l): second = float(s[-2:]) minute = float(s[-4:-2]) degree = float(s[:-4]) if l == 'E': return str(degree + minute / 60 + second / 3600) else: return str(-degree - minute / 60 - second / 3600) def is_otime(s): mm_dict = {'JAN': '01', 'FEB': '02', 'MAR': '03', 'APR': '04', 'MAY': '05', 'JUN': '06', 'JUL': '07', 'AUG': '08', 'SEP': '09', 'OCT': '10', 'NOV': '11', 'DEC': '12'} return s[:4] + MM_dict[s[4:7]] + s[7:9] + 'T' + s[9:11] + ':' + s[11:] def parse_fstat_output(s): if s[-3:] == 'NOP': return 'baseClosed' if s[-3:] == 'OPR': return 'baseOpen' def parse_estat_action(action): if action == 'ABORT': return 'missionAbort' elif action == 'LANDED': return 'missionLanded' elif action == 'REFUEL': return 'aircraftRefuel' elif action == 'RTB': return 'missionReturnToBase' elif action == 'TAKEOFF': return 'aircraftTakeoff' elif action == 'ON STATION': return 'missionOnStation'
def solve(input, days): # Lanternfish with internal timer t are the number of lanternfish with timer t+1 after a day for day in range(days): aux = input[0] input[0] = input[1] input[1] = input[2] input[2] = input[3] input[3] = input[4] input[4] = input[5] input[5] = input[6] # Lantern fish with interal timer 0 replicate, but they have to be added to those lanternfish that have # a timer equal to 7 input[6] = input[7] + aux input[7] = input[8] input[8] = aux return sum([input[key] for key in input]) # Get input and transform to my chosen data structure with open('Day6_input.txt','r') as inputfile: input = inputfile.read().split(",") input = [int(element) for element in input] # Lanterfish dictionary where the key represents their internal timer, and the value how many lanternfish # with that internal timer are alive right now input = { 0: input.count(0), 1: input.count(1), 2: input.count(2), 3: input.count(3), 4: input.count(4), 5: input.count(5), 6: input.count(6), 7: input.count(7), 8: input.count(8) } part1_sol = solve(input,80) print("Part 1 solution: ",part1_sol) # 80 days have already been calculated, we take advantage of it part2_sol = solve(input,256 - 80) print("Part 2 solution: ",part2_sol)
def solve(input, days): for day in range(days): aux = input[0] input[0] = input[1] input[1] = input[2] input[2] = input[3] input[3] = input[4] input[4] = input[5] input[5] = input[6] input[6] = input[7] + aux input[7] = input[8] input[8] = aux return sum([input[key] for key in input]) with open('Day6_input.txt', 'r') as inputfile: input = inputfile.read().split(',') input = [int(element) for element in input] input = {0: input.count(0), 1: input.count(1), 2: input.count(2), 3: input.count(3), 4: input.count(4), 5: input.count(5), 6: input.count(6), 7: input.count(7), 8: input.count(8)} part1_sol = solve(input, 80) print('Part 1 solution: ', part1_sol) part2_sol = solve(input, 256 - 80) print('Part 2 solution: ', part2_sol)
def funcao1(funcao, *args, **kwargs): return funcao(*args, **kwargs) def funcao2(nome): return f'Oi {nome}' def funcao3(nome, saudacao): return f'{saudacao} {nome}' executando = funcao1(funcao2, 'Luiz') print(executando) executando = funcao1(funcao3, 'Luiz', saudacao='Bom dia') print(executando)
def funcao1(funcao, *args, **kwargs): return funcao(*args, **kwargs) def funcao2(nome): return f'Oi {nome}' def funcao3(nome, saudacao): return f'{saudacao} {nome}' executando = funcao1(funcao2, 'Luiz') print(executando) executando = funcao1(funcao3, 'Luiz', saudacao='Bom dia') print(executando)
true = True; false = False; true1 = "True"; false1 = "False"; true2 = true; ''' I was trying to check if keyword is case sensitive which it is not but here the above defined variable value is taken which is bool This technique can be used to define case insensitive keywords at start to py program.''' false2 = false; print(true,type(true)); print(false,type(false)); print(true1,type(true1)); print(false1,type(false1)); print(true2,type(true2)); print(false2,type(false2));
true = True false = False true1 = 'True' false1 = 'False' true2 = true ' I was trying to check if keyword is case sensitive which it is not but here the above defined variable value is taken which is bool\nThis technique can be used to define case insensitive keywords at start to py program.' false2 = false print(true, type(true)) print(false, type(false)) print(true1, type(true1)) print(false1, type(false1)) print(true2, type(true2)) print(false2, type(false2))
## input = 1,2,3,4 ## output = ['1','2','3','4'], ('1','2','3','4') def abc(): values = input() print("----") print(values) print("----") x = values.split(",") print(x) y = tuple(x) print("===") print(y) if __name__ == "__main__": abc()
def abc(): values = input() print('----') print(values) print('----') x = values.split(',') print(x) y = tuple(x) print('===') print(y) if __name__ == '__main__': abc()
#!/usr/bin/env python3 FILENAME = "/tmp/passed" bmks = [] with open(FILENAME, "r") as f: for l in f: [m, a] = l.split(" ") t = (m, a.strip()) bmks.append(t) def quote(s): return '"{}"'.format(s) indent = " " output = '{}[ {}\n{}]'.format(indent, f'\n{indent}, '.join(f'("{m}", "{a}")' for m, a in bmks), indent) print("passedTests :: [(String, String)]") print("passedTests =") print(output)
filename = '/tmp/passed' bmks = [] with open(FILENAME, 'r') as f: for l in f: [m, a] = l.split(' ') t = (m, a.strip()) bmks.append(t) def quote(s): return '"{}"'.format(s) indent = ' ' output = '{}[ {}\n{}]'.format(indent, f'\n{indent}, '.join((f'("{m}", "{a}")' for (m, a) in bmks)), indent) print('passedTests :: [(String, String)]') print('passedTests =') print(output)
class Solution: def ladderLength(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """BFS. """ words = set(wordList) if endWord not in words: return 0 layer = set([beginWord]) res = 1 while layer: nlayer = set() for word in layer: if word == endWord: return res for i in range(len(word)): for c in string.ascii_lowercase: nword = word[:i] + c + word[i+1:] if nword in words: nlayer.add(nword) words -= nlayer layer = nlayer res += 1 return 0
class Solution: def ladder_length(self, beginWord: str, endWord: str, wordList: List[str]) -> int: """BFS. """ words = set(wordList) if endWord not in words: return 0 layer = set([beginWord]) res = 1 while layer: nlayer = set() for word in layer: if word == endWord: return res for i in range(len(word)): for c in string.ascii_lowercase: nword = word[:i] + c + word[i + 1:] if nword in words: nlayer.add(nword) words -= nlayer layer = nlayer res += 1 return 0
{ "includes": [ "../common.gypi" ], "targets": [ { "target_name": "libgdal_ogr_vrt_frmt", "type": "static_library", "sources": [ "../gdal/ogr/ogrsf_frmts/vrt/ogrvrtlayer.cpp", "../gdal/ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp", "../gdal/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp" ], "include_dirs": [ "../gdal/ogr/ogrsf_frmts/vrt" ] } ] }
{'includes': ['../common.gypi'], 'targets': [{'target_name': 'libgdal_ogr_vrt_frmt', 'type': 'static_library', 'sources': ['../gdal/ogr/ogrsf_frmts/vrt/ogrvrtlayer.cpp', '../gdal/ogr/ogrsf_frmts/vrt/ogrvrtdriver.cpp', '../gdal/ogr/ogrsf_frmts/vrt/ogrvrtdatasource.cpp'], 'include_dirs': ['../gdal/ogr/ogrsf_frmts/vrt']}]}
class Compose(object): """Composes several transforms together for object detection. Args: transforms (list of ``Transform`` objects): list of transforms to compose. """ def __init__(self, transforms): self.transforms = transforms def __call__(self, image, target): for t in self.transforms: image, target = t(image, target) return image, target
class Compose(object): """Composes several transforms together for object detection. Args: transforms (list of ``Transform`` objects): list of transforms to compose. """ def __init__(self, transforms): self.transforms = transforms def __call__(self, image, target): for t in self.transforms: (image, target) = t(image, target) return (image, target)
def subarraysCountBySum(a, k, s): ans=0 n=len(a) t=0 ii=1 while(k+t<=n): tmp=[] for i in range(t,ii+t): tmp.append(a[i]) print(tmp) ii+=1 if len(tmp)<=k and sum(tmp)==s: ans+=1 t+=1 else: break return ans a=list(map(int,input().split())) k,s=map(int,input().split()) print(subarraysCountBySum(a, k, s))
def subarrays_count_by_sum(a, k, s): ans = 0 n = len(a) t = 0 ii = 1 while k + t <= n: tmp = [] for i in range(t, ii + t): tmp.append(a[i]) print(tmp) ii += 1 if len(tmp) <= k and sum(tmp) == s: ans += 1 t += 1 else: break return ans a = list(map(int, input().split())) (k, s) = map(int, input().split()) print(subarrays_count_by_sum(a, k, s))
def main(request, response): response.headers.set(b"Content-Type", b"text/plain") response.status = 200 response.content = request.headers.get(b"Content-Type") response.close_connection = True
def main(request, response): response.headers.set(b'Content-Type', b'text/plain') response.status = 200 response.content = request.headers.get(b'Content-Type') response.close_connection = True
fruits = ['banana', 'orange', 'mango', 'lemon'] fruit = str(input('Enter a fruit: ')).strip().lower() if fruit not in fruits: fruits.append(fruit) print(fruits) else: print(f'{fruit} already in the list')
fruits = ['banana', 'orange', 'mango', 'lemon'] fruit = str(input('Enter a fruit: ')).strip().lower() if fruit not in fruits: fruits.append(fruit) print(fruits) else: print(f'{fruit} already in the list')
amount = 20 num=1 def setup(): size(640, 640) stroke(0, 150, 255, 100) def draw(): global num, amount fill(0, 40) rect(-1, -1, width+1, height+1) maxX = map(mouseX, 0, width, 1, 250) translate(width/2, height/2) for i in range(0,360,amount): x = sin(radians(i+num)) * maxX y = cos(radians(i+num)) * maxX x2 = sin(radians(i+amount-num)) * maxX y2 = cos(radians(i+amount-num)) * maxX noFill() bezier(x, y, x-x2, y-y2, x2-x, y2-y, x2, y2) bezier(x, y, x+x2, y+y2, x2+x, y2+y, x2, y2) fill(0, 150, 255) ellipse(x, y, 5, 5) ellipse(x2, y2, 5, 5) num += 0.5;
amount = 20 num = 1 def setup(): size(640, 640) stroke(0, 150, 255, 100) def draw(): global num, amount fill(0, 40) rect(-1, -1, width + 1, height + 1) max_x = map(mouseX, 0, width, 1, 250) translate(width / 2, height / 2) for i in range(0, 360, amount): x = sin(radians(i + num)) * maxX y = cos(radians(i + num)) * maxX x2 = sin(radians(i + amount - num)) * maxX y2 = cos(radians(i + amount - num)) * maxX no_fill() bezier(x, y, x - x2, y - y2, x2 - x, y2 - y, x2, y2) bezier(x, y, x + x2, y + y2, x2 + x, y2 + y, x2, y2) fill(0, 150, 255) ellipse(x, y, 5, 5) ellipse(x2, y2, 5, 5) num += 0.5
class EmailValidator(object): """Abstract email validator to subclass from. You should not instantiate an EmailValidator, as it merely provides the interface for is_email, not an implementation. """ def is_email(self, address, diagnose=False): """Interface for is_email method. Keyword arguments: address -- address to check. diagnose -- flag to report a diagnose or just True/False """ raise NotImplementedError() is_valid = is_email
class Emailvalidator(object): """Abstract email validator to subclass from. You should not instantiate an EmailValidator, as it merely provides the interface for is_email, not an implementation. """ def is_email(self, address, diagnose=False): """Interface for is_email method. Keyword arguments: address -- address to check. diagnose -- flag to report a diagnose or just True/False """ raise not_implemented_error() is_valid = is_email
# Copyright (c) Microsoft Corporation. # # 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 # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. async def test_listeners(page, server): log = [] def print_response(response): log.append(response) page.on("response", print_response) await page.goto(f"{server.PREFIX}/input/textarea.html") assert len(log) > 0 page.remove_listener("response", print_response) log = [] await page.goto(f"{server.PREFIX}/input/textarea.html") assert len(log) == 0
async def test_listeners(page, server): log = [] def print_response(response): log.append(response) page.on('response', print_response) await page.goto(f'{server.PREFIX}/input/textarea.html') assert len(log) > 0 page.remove_listener('response', print_response) log = [] await page.goto(f'{server.PREFIX}/input/textarea.html') assert len(log) == 0
class Backend(object): # should be implemented all methods def set(self, name, value): raise NotImplementedError() def get(self, name): raise NotImplementedError() def delete(self, name): raise NotImplementedError() def set_fields(self): raise NotImplementedError() def fields(self): raise NotImplementedError() def values(self): raise NotImplementedError() class AbstractBackend(Backend): bucket_prefix = 'ONTHEFLY' def __init__(self, options, original=None): self.options = options self.original = original self.field_registry = None self.value_registry = {} def get_value_from_original_settings(self, name): return getattr(self.original, name) def get_fields(self): if self.field_registry is None: self.field_registry = self.fields() return self.field_registry def add_field(self, name): if name not in self.get_fields(): self.field_registry.append(name) self.set_fields() def delete_field(self, name): if name in self.field_registry: self.field_registry.remove(name) self.set_fields() def set_value(self, name, value): if name in self.value_registry: del self.value_registry[name] return self.set(name, value) def get_value(self, name): if name in self.value_registry: value = self.value_registry[name] else: value = self.get(name) self.value_registry[name] = value return value def delete_value(self, name): if name in self.value_registry: del self.value_registry[name] return self.delete(name)
class Backend(object): def set(self, name, value): raise not_implemented_error() def get(self, name): raise not_implemented_error() def delete(self, name): raise not_implemented_error() def set_fields(self): raise not_implemented_error() def fields(self): raise not_implemented_error() def values(self): raise not_implemented_error() class Abstractbackend(Backend): bucket_prefix = 'ONTHEFLY' def __init__(self, options, original=None): self.options = options self.original = original self.field_registry = None self.value_registry = {} def get_value_from_original_settings(self, name): return getattr(self.original, name) def get_fields(self): if self.field_registry is None: self.field_registry = self.fields() return self.field_registry def add_field(self, name): if name not in self.get_fields(): self.field_registry.append(name) self.set_fields() def delete_field(self, name): if name in self.field_registry: self.field_registry.remove(name) self.set_fields() def set_value(self, name, value): if name in self.value_registry: del self.value_registry[name] return self.set(name, value) def get_value(self, name): if name in self.value_registry: value = self.value_registry[name] else: value = self.get(name) self.value_registry[name] = value return value def delete_value(self, name): if name in self.value_registry: del self.value_registry[name] return self.delete(name)
number_of_days = int(input()) type_of_room = str(input()) rating = str(input()) room_for_one_person = 18.00 apartment = 25.00 president_apartment = 35.00 apartment_discount = 0 president_apartment_discount = 0 total_price_for_a_room = 0 total_price_for_apartment = 0 total_price_for_presidential_apartment = 0 additional_discount = 0 additional_pay = 0 room_with_discounts = 0 apartment_with_discounts = 0 president_apartment_with_discounts = 0 apartment1 = 0 president_apartment1 = 0 if type_of_room == 'room for one person' or type_of_room == 'apartment' or \ type_of_room == 'president apartment': nights = number_of_days - 1 if type_of_room == 'room for one person': total_price_for_a_room = room_for_one_person * nights if rating == 'positive': additional_pay = total_price_for_a_room * 0.25 room_with_discounts = total_price_for_a_room + additional_pay elif rating == 'negative': additional_discount = total_price_for_a_room * 0.10 room_with_discounts = total_price_for_a_room - additional_discount print(f'{room_with_discounts:.2f}') elif type_of_room == 'apartment': total_price_for_apartment = apartment * nights if number_of_days < 10: apartment_discount = total_price_for_apartment * 0.30 elif 10 <= number_of_days <= 15: apartment_discount = total_price_for_apartment * 0.35 elif number_of_days > 15: apartment_discount = total_price_for_apartment * 0.50 apartment1 = total_price_for_apartment - apartment_discount if rating == 'positive': additional_pay = apartment1 * 0.25 apartment_with_discounts = apartment1 + additional_pay elif rating == 'negative': additional_discount = apartment1 * 0.10 apartment_with_discounts = apartment1 - additional_discount print(f'{apartment_with_discounts:.2f}') elif type_of_room == 'president apartment': total_price_for_presidential_apartment = president_apartment * nights if number_of_days < 10: president_apartment_discount = total_price_for_presidential_apartment * 0.10 elif 10 <= number_of_days <= 15: president_apartment_discount = total_price_for_presidential_apartment * 0.15 elif number_of_days > 15: president_apartment_discount = total_price_for_presidential_apartment * 0.20 president_apartment1 = total_price_for_presidential_apartment - president_apartment_discount if rating == 'positive': additional_pay = president_apartment1 * 0.25 president_apartment_with_discounts = president_apartment1 + additional_pay elif rating == 'negative': additional_discount = president_apartment1 * 0.10 president_apartment_with_discounts = president_apartment1 - additional_discount print(f'{president_apartment_with_discounts:.2f}')
number_of_days = int(input()) type_of_room = str(input()) rating = str(input()) room_for_one_person = 18.0 apartment = 25.0 president_apartment = 35.0 apartment_discount = 0 president_apartment_discount = 0 total_price_for_a_room = 0 total_price_for_apartment = 0 total_price_for_presidential_apartment = 0 additional_discount = 0 additional_pay = 0 room_with_discounts = 0 apartment_with_discounts = 0 president_apartment_with_discounts = 0 apartment1 = 0 president_apartment1 = 0 if type_of_room == 'room for one person' or type_of_room == 'apartment' or type_of_room == 'president apartment': nights = number_of_days - 1 if type_of_room == 'room for one person': total_price_for_a_room = room_for_one_person * nights if rating == 'positive': additional_pay = total_price_for_a_room * 0.25 room_with_discounts = total_price_for_a_room + additional_pay elif rating == 'negative': additional_discount = total_price_for_a_room * 0.1 room_with_discounts = total_price_for_a_room - additional_discount print(f'{room_with_discounts:.2f}') elif type_of_room == 'apartment': total_price_for_apartment = apartment * nights if number_of_days < 10: apartment_discount = total_price_for_apartment * 0.3 elif 10 <= number_of_days <= 15: apartment_discount = total_price_for_apartment * 0.35 elif number_of_days > 15: apartment_discount = total_price_for_apartment * 0.5 apartment1 = total_price_for_apartment - apartment_discount if rating == 'positive': additional_pay = apartment1 * 0.25 apartment_with_discounts = apartment1 + additional_pay elif rating == 'negative': additional_discount = apartment1 * 0.1 apartment_with_discounts = apartment1 - additional_discount print(f'{apartment_with_discounts:.2f}') elif type_of_room == 'president apartment': total_price_for_presidential_apartment = president_apartment * nights if number_of_days < 10: president_apartment_discount = total_price_for_presidential_apartment * 0.1 elif 10 <= number_of_days <= 15: president_apartment_discount = total_price_for_presidential_apartment * 0.15 elif number_of_days > 15: president_apartment_discount = total_price_for_presidential_apartment * 0.2 president_apartment1 = total_price_for_presidential_apartment - president_apartment_discount if rating == 'positive': additional_pay = president_apartment1 * 0.25 president_apartment_with_discounts = president_apartment1 + additional_pay elif rating == 'negative': additional_discount = president_apartment1 * 0.1 president_apartment_with_discounts = president_apartment1 - additional_discount print(f'{president_apartment_with_discounts:.2f}')
LIST_WORKFLOWS_GQL = ''' query workflowList { workflowList { edges{ node { id name objectType initialPrefetch initialState { id name } initialTransition { id name } } } } } ''' LIST_STATES_GQL = ''' query stateList { stateList { edges{ node { id name active initial workflow { id name } } } } } ''' MUTATE_WORKFLOW_GRAPH_GQL = ''' mutation workflowMutation($param: WorkflowMutationInput!) { workflowMutation(input:$param) { id name initialPrefetch objectType errors { messages } } } ''' MUTATE_STATE_GRAPH_GQL = ''' mutation stateMutation($param: StateMutationInput!) { stateMutation(input:$param) { id name initial active workflow errors { messages } } } ''' LIST_TRANSITIONS_GQL = ''' query transitionList($param: ID) { transitionList(workflow_Id:$param) { edges{ node { id name initialState { id name active initial variableDefinitions { edges { node { id name } } } } finalState { id name active initial variableDefinitions { edges { node { id name } } } } conditionSet { edges { node { id conditionType functionSet { edges { node { id functionModule functionName parameters{ edges { node { id name value } } } } } } } } } } } } } ''' LIST_WORKFLOW_STATES_GQL = ''' query stateList($param: ID) { stateList(workflow_Id:$param) { edges{ node { id name active initial workflow { id name } } } } } ''' LIST_WORKFLOW_GRAPH_GQL = ''' query workflowList($param: String) { workflowList(name:$param) { edges{ node { id name graph } } } } '''
list_workflows_gql = '\nquery workflowList {\n workflowList {\n edges{\n node {\n id\n name\n objectType\n initialPrefetch\n initialState {\n id\n name\n }\n initialTransition {\n id\n name\n }\n }\n }\n }\n}\n' list_states_gql = '\nquery stateList {\n stateList {\n edges{\n node {\n id\n name\n active\n initial\n workflow {\n id\n name\n }\n }\n }\n }\n}\n' mutate_workflow_graph_gql = '\nmutation workflowMutation($param: WorkflowMutationInput!) {\n workflowMutation(input:$param) {\n id\n name\n initialPrefetch\n objectType \n errors {\n messages\n }\n }\n}\n' mutate_state_graph_gql = '\nmutation stateMutation($param: StateMutationInput!) {\n stateMutation(input:$param) {\n id\n name\n initial\n active\n workflow\n errors {\n messages\n }\n }\n}\n' list_transitions_gql = '\nquery transitionList($param: ID) {\n transitionList(workflow_Id:$param) {\n edges{\n node {\n id\n name\n initialState {\n id\n name\n active\n initial\n variableDefinitions {\n edges {\n node {\n id\n name\n }\n }\n }\n }\n finalState {\n id\n name\n active\n initial\n variableDefinitions {\n edges {\n node {\n id\n name\n }\n }\n }\n }\n conditionSet {\n edges {\n node {\n id\n conditionType\n functionSet {\n edges {\n node {\n id\n functionModule\n functionName\n parameters{\n edges {\n node {\n id\n name\n value\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n }\n}\n' list_workflow_states_gql = '\nquery stateList($param: ID) {\n stateList(workflow_Id:$param) {\n edges{\n node {\n id\n name\n active\n initial\n workflow {\n id\n name\n }\n \n }\n }\n }\n}\n' list_workflow_graph_gql = '\nquery workflowList($param: String) {\n workflowList(name:$param) {\n edges{\n node {\n id\n name\n graph\n }\n }\n }\n}\n'
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ # Write your code here x = ['0', '1', '8'] t = int(int(input())) for _ in range(t): n = int(input()) if str(n) == str(n)[::-1] and set(str(n)).issubset(x): print('YES') else: print('NO')
""" # Sample code to perform I/O: name = input() # Reading input from STDIN print('Hi, %s.' % name) # Writing output to STDOUT # Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail """ x = ['0', '1', '8'] t = int(int(input())) for _ in range(t): n = int(input()) if str(n) == str(n)[::-1] and set(str(n)).issubset(x): print('YES') else: print('NO')
""" if __name__ == '__main__': for _ in range(int(input())): name = input() score = float(input()) """ # pythonNestedLists.py #!/usr/bin/env python N = int(input()) students = list() for i in range(N): students.append([input(), float(input())]) scores = set([students[x][1] for x in range(N)]) scores = list(scores) scores.sort() students = [x[0] for x in students if x[1] == scores[1]] students.sort() for s in students: print (s)
""" if __name__ == '__main__': for _ in range(int(input())): name = input() score = float(input()) """ n = int(input()) students = list() for i in range(N): students.append([input(), float(input())]) scores = set([students[x][1] for x in range(N)]) scores = list(scores) scores.sort() students = [x[0] for x in students if x[1] == scores[1]] students.sort() for s in students: print(s)
with open("text.txt", "w") as my_file: my_file.write("Tretas dos Bronzetas") if my_file.closed == False: my_file.close() print(my_file.closed)
with open('text.txt', 'w') as my_file: my_file.write('Tretas dos Bronzetas') if my_file.closed == False: my_file.close() print(my_file.closed)
test = { 'name': 'Mutability', 'points': 0, 'suites': [ { 'type': 'wwpp', 'cases': [ { 'code': """ >>> lst = [5, 6, 7, 8] >>> lst.append(6) Nothing >>> lst [5, 6, 7, 8, 6] >>> lst.insert(0, 9) >>> lst [9, 5, 6, 7, 8, 6] >>> x = lst.pop(2) >>> lst [9, 5, 7, 8, 6] >>> lst.remove(x) >>> lst [9, 5, 7, 8] >>> a, b = lst, lst[:] >>> a is lst True >>> b == lst True >>> b is lst False """ }, ] }, { 'type': 'wwpp', 'cases': [ { 'code': """ >>> pokemon = {'pikachu': 25, 'dragonair': 148, 'mew': 151} >>> pokemon['pikachu'] 25 >>> len(pokemon) 3 >>> pokemon['jolteon'] = 135 >>> pokemon['mew'] = 25 >>> len(pokemon) 4 >>> 'mewtwo' in pokemon False >>> 'pikachu' in pokemon True >>> 25 in pokemon False >>> 148 in pokemon.values() True >>> 151 in pokemon.keys() False >>> 'mew' in pokemon.keys() True >>> pokemon['ditto'] = pokemon['jolteon'] >>> pokemon['ditto'] 135 """ }, ] } ] }
test = {'name': 'Mutability', 'points': 0, 'suites': [{'type': 'wwpp', 'cases': [{'code': '\n >>> lst = [5, 6, 7, 8]\n >>> lst.append(6)\n Nothing\n >>> lst\n [5, 6, 7, 8, 6]\n >>> lst.insert(0, 9)\n >>> lst\n [9, 5, 6, 7, 8, 6]\n >>> x = lst.pop(2)\n >>> lst\n [9, 5, 7, 8, 6]\n >>> lst.remove(x)\n >>> lst\n [9, 5, 7, 8]\n >>> a, b = lst, lst[:]\n >>> a is lst\n True\n >>> b == lst\n True\n >>> b is lst\n False\n '}]}, {'type': 'wwpp', 'cases': [{'code': "\n >>> pokemon = {'pikachu': 25, 'dragonair': 148, 'mew': 151}\n >>> pokemon['pikachu']\n 25\n >>> len(pokemon)\n 3\n >>> pokemon['jolteon'] = 135\n >>> pokemon['mew'] = 25\n >>> len(pokemon)\n 4\n >>> 'mewtwo' in pokemon\n False\n >>> 'pikachu' in pokemon\n True\n >>> 25 in pokemon\n False\n >>> 148 in pokemon.values()\n True\n >>> 151 in pokemon.keys()\n False\n >>> 'mew' in pokemon.keys()\n True\n >>> pokemon['ditto'] = pokemon['jolteon']\n >>> pokemon['ditto']\n 135\n "}]}]}
DESCRIBE_VMS = [ { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM", "type": "Microsoft.Compute/virtualMachines", "location": "West US", "resource_group": "TestRG", "name": "TestVM", "plan": { "product": "Standard", }, "handware_profile": { "vm_size": "Standard_D2s_v3", }, "license_type": "Windows_Client ", "os_profile": { "computer_name": "TestVM", }, "identity": { "type": "SystemAssigned", }, "zones": [ "West US 2", ], "additional_capabilities": { "ultra_ssd_enabled": True, }, "priority": "Low", "eviction_policy": "Deallocate", }, { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1", "type": "Microsoft.Compute/virtualMachines", "location": "West US", "resource_group": "TestRG", "name": "TestVM1", "plan": { "product": "Standard", }, "handware_profile": { "vm_size": "Standard_D2s_v3", }, "license_type": "Windows_Client ", "os_profile": { "computer_name": "TestVM1", }, "identity": { "type": "SystemAssigned", }, "zones": [ "West US 2", ], "additional_capabilities": { "ultra_ssd_enabled": True, }, "priority": "Low", "eviction_policy": "Deallocate", }, ] DESCRIBE_VM_DATA_DISKS = [ { "lun": 0, "name": "dd0", "create_option": "Empty", "caching": "ReadWrite", "managed_disk": { "storage_account_type": "Premium_LRS", "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd0", }, "disk_size_gb": 30, }, { "lun": 0, "name": "dd1", "create_option": "Empty", "caching": "ReadWrite", "managed_disk": { "storage_account_type": "Premium_LRS", "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd1", }, "disk_size_gb": 30, }, ] DESCRIBE_DISKS = [ { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd0", "type": "Microsoft.Compute/disks", "location": "West US", "resource_group": "TestRG", "name": "dd0", "creation_data": { "create_option": "Attach", }, "disk_size_gb": 100, "encryption_settings_collection": { "enabled": True, }, "max_shares": 10, "network_access_policy": "AllowAll", "os_type": "Windows", "tier": "P4", "sku": { "name": "Standard_LRS", }, "zones": [ "West US 2", ], }, { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd1", "type": "Microsoft.Compute/disks", "location": "West US", "resource_group": "TestRG", "name": "dd1", "creation_data": { "create_option": "Attach", }, "disk_size_gb": 100, "encryption_settings_collection": { "enabled": True, }, "max_shares": 10, "network_access_policy": "AllowAll", "os_type": "Windows", "tier": "P4", "sku": { "name": "Standard_LRS", }, "zones": [ "West US 2", ], }, ] DESCRIBE_SNAPSHOTS = [ { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/snapshots/ss0", "type": "Microsoft.Compute/snapshots", "location": "West US", "resource_group": "TestRG", "name": "ss0", "creation_data": { "create_option": "Attach", }, "disk_size_gb": 100, "encryption_settings_collection": { "enabled": True, }, "incremental": True, "network_access_policy": "AllowAll", "os_type": "Windows", "tier": "P4", "sku": { "name": "Standard_LRS", }, }, { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/snapshots/ss1", "type": "Microsoft.Compute/snapshots", "location": "West US", "resource_group": "TestRG", "name": "ss1", "creation_data": { "create_option": "Attach", }, "disk_size_gb": 100, "encryption_settings_collection": { "enabled": True, }, "incremental": True, "network_access_policy": "AllowAll", "os_type": "Windows", "tier": "P4", "sku": { "name": "Standard_LRS", }, }, ] DESCRIBE_VMEXTENSIONS = [ { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachines/TestVM/extensions/extensions1", "type": "Microsoft.Compute/virtualMachines/extensions", "resource_group": "TestRG", "name": "extensions1", "location": "West US", "vm_id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM", }, { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachines/TestVM1/extensions/extensions2", "type": "Microsoft.Compute/virtualMachines/extensions", "resource_group": "TestRG", "name": "extensions2", "location": "West US", "vm_id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1", }, ] DESCRIBE_VMAVAILABLESIZES = [ { "numberOfCores": 2, "type": "Microsoft.Compute/virtualMachines/availablesizes", "osDiskSizeInMB": 1234, "name": "size1", "resourceDiskSizeInMB": 2312, "memoryInMB": 4352, "maxDataDiskCount": 3214, "vm_id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM", }, { "numberOfCores": 2, "type": "Microsoft.Compute/virtualMachines/availablesizes", "osDiskSizeInMB": 1234, "name": "size2", "resourceDiskSizeInMB": 2312, "memoryInMB": 4352, "maxDataDiskCount": 3214, "vm_id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1", }, ] DESCRIBE_VMSCALESETS = [ { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachineScaleSets/set1", "type": "Microsoft.Compute/virtualMachineScaleSets", "resource_group": "TestRG", "name": "set1", "location": "West US", }, { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachineScaleSets/set2", "type": "Microsoft.Compute/virtualMachineScaleSets", "resource_group": "TestRG", "name": "set2", "location": "West US", }, ] DESCRIBE_VMSCALESETEXTENSIONS = [ { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachineScaleSets/set1/extensions/extension1", "type": "Microsoft.Compute/virtualMachineScaleSets/extensions", "resource_group": "TestRG", "name": "extension1", "set_id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachineScaleSets/set1", }, { "id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachineScaleSets/set2/extensions/extension2", "type": "Microsoft.Compute/virtualMachineScaleSets/extensions", "resource_group": "TestRG", "name": "extension2", "set_id": "/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/\ virtualMachineScaleSets/set2", }, ]
describe_vms = [{'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM', 'type': 'Microsoft.Compute/virtualMachines', 'location': 'West US', 'resource_group': 'TestRG', 'name': 'TestVM', 'plan': {'product': 'Standard'}, 'handware_profile': {'vm_size': 'Standard_D2s_v3'}, 'license_type': 'Windows_Client ', 'os_profile': {'computer_name': 'TestVM'}, 'identity': {'type': 'SystemAssigned'}, 'zones': ['West US 2'], 'additional_capabilities': {'ultra_ssd_enabled': True}, 'priority': 'Low', 'eviction_policy': 'Deallocate'}, {'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1', 'type': 'Microsoft.Compute/virtualMachines', 'location': 'West US', 'resource_group': 'TestRG', 'name': 'TestVM1', 'plan': {'product': 'Standard'}, 'handware_profile': {'vm_size': 'Standard_D2s_v3'}, 'license_type': 'Windows_Client ', 'os_profile': {'computer_name': 'TestVM1'}, 'identity': {'type': 'SystemAssigned'}, 'zones': ['West US 2'], 'additional_capabilities': {'ultra_ssd_enabled': True}, 'priority': 'Low', 'eviction_policy': 'Deallocate'}] describe_vm_data_disks = [{'lun': 0, 'name': 'dd0', 'create_option': 'Empty', 'caching': 'ReadWrite', 'managed_disk': {'storage_account_type': 'Premium_LRS', 'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd0'}, 'disk_size_gb': 30}, {'lun': 0, 'name': 'dd1', 'create_option': 'Empty', 'caching': 'ReadWrite', 'managed_disk': {'storage_account_type': 'Premium_LRS', 'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd1'}, 'disk_size_gb': 30}] describe_disks = [{'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd0', 'type': 'Microsoft.Compute/disks', 'location': 'West US', 'resource_group': 'TestRG', 'name': 'dd0', 'creation_data': {'create_option': 'Attach'}, 'disk_size_gb': 100, 'encryption_settings_collection': {'enabled': True}, 'max_shares': 10, 'network_access_policy': 'AllowAll', 'os_type': 'Windows', 'tier': 'P4', 'sku': {'name': 'Standard_LRS'}, 'zones': ['West US 2']}, {'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/disks/dd1', 'type': 'Microsoft.Compute/disks', 'location': 'West US', 'resource_group': 'TestRG', 'name': 'dd1', 'creation_data': {'create_option': 'Attach'}, 'disk_size_gb': 100, 'encryption_settings_collection': {'enabled': True}, 'max_shares': 10, 'network_access_policy': 'AllowAll', 'os_type': 'Windows', 'tier': 'P4', 'sku': {'name': 'Standard_LRS'}, 'zones': ['West US 2']}] describe_snapshots = [{'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/snapshots/ss0', 'type': 'Microsoft.Compute/snapshots', 'location': 'West US', 'resource_group': 'TestRG', 'name': 'ss0', 'creation_data': {'create_option': 'Attach'}, 'disk_size_gb': 100, 'encryption_settings_collection': {'enabled': True}, 'incremental': True, 'network_access_policy': 'AllowAll', 'os_type': 'Windows', 'tier': 'P4', 'sku': {'name': 'Standard_LRS'}}, {'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/snapshots/ss1', 'type': 'Microsoft.Compute/snapshots', 'location': 'West US', 'resource_group': 'TestRG', 'name': 'ss1', 'creation_data': {'create_option': 'Attach'}, 'disk_size_gb': 100, 'encryption_settings_collection': {'enabled': True}, 'incremental': True, 'network_access_policy': 'AllowAll', 'os_type': 'Windows', 'tier': 'P4', 'sku': {'name': 'Standard_LRS'}}] describe_vmextensions = [{'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachines/TestVM/extensions/extensions1', 'type': 'Microsoft.Compute/virtualMachines/extensions', 'resource_group': 'TestRG', 'name': 'extensions1', 'location': 'West US', 'vm_id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM'}, {'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachines/TestVM1/extensions/extensions2', 'type': 'Microsoft.Compute/virtualMachines/extensions', 'resource_group': 'TestRG', 'name': 'extensions2', 'location': 'West US', 'vm_id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1'}] describe_vmavailablesizes = [{'numberOfCores': 2, 'type': 'Microsoft.Compute/virtualMachines/availablesizes', 'osDiskSizeInMB': 1234, 'name': 'size1', 'resourceDiskSizeInMB': 2312, 'memoryInMB': 4352, 'maxDataDiskCount': 3214, 'vm_id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM'}, {'numberOfCores': 2, 'type': 'Microsoft.Compute/virtualMachines/availablesizes', 'osDiskSizeInMB': 1234, 'name': 'size2', 'resourceDiskSizeInMB': 2312, 'memoryInMB': 4352, 'maxDataDiskCount': 3214, 'vm_id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/virtualMachines/TestVM1'}] describe_vmscalesets = [{'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachineScaleSets/set1', 'type': 'Microsoft.Compute/virtualMachineScaleSets', 'resource_group': 'TestRG', 'name': 'set1', 'location': 'West US'}, {'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachineScaleSets/set2', 'type': 'Microsoft.Compute/virtualMachineScaleSets', 'resource_group': 'TestRG', 'name': 'set2', 'location': 'West US'}] describe_vmscalesetextensions = [{'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachineScaleSets/set1/extensions/extension1', 'type': 'Microsoft.Compute/virtualMachineScaleSets/extensions', 'resource_group': 'TestRG', 'name': 'extension1', 'set_id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachineScaleSets/set1'}, {'id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachineScaleSets/set2/extensions/extension2', 'type': 'Microsoft.Compute/virtualMachineScaleSets/extensions', 'resource_group': 'TestRG', 'name': 'extension2', 'set_id': '/subscriptions/00-00-00-00/resourceGroups/TestRG/providers/Microsoft.Compute/ virtualMachineScaleSets/set2'}]
''' Pattern Enter number of rows: 5 1 21 321 4321 54321 ''' print('Number Pattern:') number_rows=int(input('Enter number of rows: ')) for row in range(1,number_rows+1): for column in range(row,0,-1): if column < 10: print(f'0{column}',end=' ') else: print(column,end=' ') print()
""" Pattern Enter number of rows: 5 1 21 321 4321 54321 """ print('Number Pattern:') number_rows = int(input('Enter number of rows: ')) for row in range(1, number_rows + 1): for column in range(row, 0, -1): if column < 10: print(f'0{column}', end=' ') else: print(column, end=' ') print()
class Solution: def isStrobogrammatic(self, num: str) -> bool: dic = {'1': '1', '6': '9', '8': '8', '9': '6', '0': '0'} l, r = 0, len(num)-1 while l <= r: if num[l] not in dic or dic[num[l]] != num[r]: return False l += 1 r -= 1 return True
class Solution: def is_strobogrammatic(self, num: str) -> bool: dic = {'1': '1', '6': '9', '8': '8', '9': '6', '0': '0'} (l, r) = (0, len(num) - 1) while l <= r: if num[l] not in dic or dic[num[l]] != num[r]: return False l += 1 r -= 1 return True
# Runtime: 128 ms # Beats 99.53% of Python submissions # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def insertIntoBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ curr_root = root if not curr_root: root = TreeNode(val) return root while curr_root: if curr_root.val > val: if curr_root.left: curr_root = curr_root.left else: curr_root.left = TreeNode(val) return root else: if curr_root.right: curr_root = curr_root.right else: curr_root.right = TreeNode(val) return root return root # Or, 4 ms slower recursive solution: # def insertIntoBST(self, root, val): # """ # :type root: TreeNode # :type val: int # :rtype: TreeNode # """ # if not root: # return TreeNode(val) # else: # if root.val > val: # if not root.left: # root.left = TreeNode(val) # else: # self.insertIntoBST(root.left, val) # else: # if not root.right: # root.right = TreeNode(val) # else: # self.insertIntoBST(root.right, val) # return root
class Solution: def insert_into_bst(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ curr_root = root if not curr_root: root = tree_node(val) return root while curr_root: if curr_root.val > val: if curr_root.left: curr_root = curr_root.left else: curr_root.left = tree_node(val) return root elif curr_root.right: curr_root = curr_root.right else: curr_root.right = tree_node(val) return root return root
""" Iterate List of list vertically tags : Twitter, array """ class Solution(): def vertical_iterator(self, arr): ans = [] arr_len = len(arr) col = 0 while True: is_empty = True for x in range(arr_len): if col < len(arr[x]): is_empty = False ans.append(arr[x][col]) if is_empty: break col += 1 print (ans) abc = Solution() abc.vertical_iterator([ [5,6], [7], [1,2,3,4], ])
""" Iterate List of list vertically tags : Twitter, array """ class Solution: def vertical_iterator(self, arr): ans = [] arr_len = len(arr) col = 0 while True: is_empty = True for x in range(arr_len): if col < len(arr[x]): is_empty = False ans.append(arr[x][col]) if is_empty: break col += 1 print(ans) abc = solution() abc.vertical_iterator([[5, 6], [7], [1, 2, 3, 4]])
# -*- coding: utf-8 -*- name = 'usd' version = '20.02' requires = [ 'alembic-1.5', 'boost-1.55', 'tbb-4.4.6', 'opensubdiv-3.2', 'ilmbase-2.2', 'jinja-2', 'jemalloc-4', 'openexr-2.2', 'pyilmbase-2.2', 'materialx', 'oiio-1.8', 'ptex-2.0', 'PyOpenGL', 'embree_lib', 'glew', 'renderman-22.6', 'ocio-1.0.9' ] build_requires = [ 'pyside-1.2' ] private_build_requires = [ 'cmake-3.2' ] variants = [['platform-linux', 'arch-x86_64']] def commands(): env.PYTHONPATH.append('{root}/lib/python') env.LD_LIBRARY_PATH.append('{root}/lib/') appendenv('PATH', '{root}/bin/')
name = 'usd' version = '20.02' requires = ['alembic-1.5', 'boost-1.55', 'tbb-4.4.6', 'opensubdiv-3.2', 'ilmbase-2.2', 'jinja-2', 'jemalloc-4', 'openexr-2.2', 'pyilmbase-2.2', 'materialx', 'oiio-1.8', 'ptex-2.0', 'PyOpenGL', 'embree_lib', 'glew', 'renderman-22.6', 'ocio-1.0.9'] build_requires = ['pyside-1.2'] private_build_requires = ['cmake-3.2'] variants = [['platform-linux', 'arch-x86_64']] def commands(): env.PYTHONPATH.append('{root}/lib/python') env.LD_LIBRARY_PATH.append('{root}/lib/') appendenv('PATH', '{root}/bin/')
contador = 1 while contador <= 9: for contador2 in range(7, 4, -1): print(f'I={contador} J={contador2}') contador += 2
contador = 1 while contador <= 9: for contador2 in range(7, 4, -1): print(f'I={contador} J={contador2}') contador += 2
# Advent of Code - Day 4 valid_passport_data = { 'ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt', } count_required_data = len(valid_passport_data) def ecl_rule(value): return value in {'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'} def pid_rule(value): try: int(value) isnumber = True except: isnumber = False return (len(value) == 9) and isnumber def eyr_rule(value): try: year = int(value) except: return False return year >= 2020 and year <= 2030 def hcl_rule(value): try: int(value[1:], 16) except: return False return value[0] == '#' and len(value) == 7 def byr_rule(value): try: year = int(value) except: return False return year >= 1920 and year <= 2002 def iyr_rule(value): try: year = int(value) except: return False return year >= 2010 and year <= 2020 def hgt_rule(value): units = value[-2:] try: height = float(value[:-2]) except: return False if units == 'cm': return height >= 150.00 and height <= 193.00 if units == 'in': return height >= 59.00 and height <= 76.00 return False validation_rules = { 'ecl': ecl_rule, 'pid': pid_rule, 'eyr': eyr_rule, 'hcl': hcl_rule, 'byr': byr_rule, 'hgt': hgt_rule, 'iyr': iyr_rule } def load_passports(path): with open(path, 'r') as file: lines = file.readlines() passports = [] passport_data = {} for line in lines: if ':' in line: key_value_list = line.split() for key_value in key_value_list: key, value = key_value.split(':') passport_data[key] = value else: passports.append(passport_data) passport_data = {} passports.append(passport_data) return passports def validate_passport(passport): keys = set(passport) common_data = valid_passport_data.intersection(keys) if len(common_data) == count_required_data: is_valid = True for key in keys: if key == 'cid': continue try: value = passport[key] is_valid = (is_valid and validation_rules[key](value)) except Exception as e: print(f'ValidationError: {e}') return int(is_valid) return 0 # === MAIN === valid_passports_count = 0 passports = load_passports('day4.txt') for p in passports: valid_passports_count += validate_passport(p) print(valid_passports_count)
valid_passport_data = {'ecl', 'pid', 'eyr', 'hcl', 'byr', 'iyr', 'hgt'} count_required_data = len(valid_passport_data) def ecl_rule(value): return value in {'amb', 'blu', 'brn', 'gry', 'grn', 'hzl', 'oth'} def pid_rule(value): try: int(value) isnumber = True except: isnumber = False return len(value) == 9 and isnumber def eyr_rule(value): try: year = int(value) except: return False return year >= 2020 and year <= 2030 def hcl_rule(value): try: int(value[1:], 16) except: return False return value[0] == '#' and len(value) == 7 def byr_rule(value): try: year = int(value) except: return False return year >= 1920 and year <= 2002 def iyr_rule(value): try: year = int(value) except: return False return year >= 2010 and year <= 2020 def hgt_rule(value): units = value[-2:] try: height = float(value[:-2]) except: return False if units == 'cm': return height >= 150.0 and height <= 193.0 if units == 'in': return height >= 59.0 and height <= 76.0 return False validation_rules = {'ecl': ecl_rule, 'pid': pid_rule, 'eyr': eyr_rule, 'hcl': hcl_rule, 'byr': byr_rule, 'hgt': hgt_rule, 'iyr': iyr_rule} def load_passports(path): with open(path, 'r') as file: lines = file.readlines() passports = [] passport_data = {} for line in lines: if ':' in line: key_value_list = line.split() for key_value in key_value_list: (key, value) = key_value.split(':') passport_data[key] = value else: passports.append(passport_data) passport_data = {} passports.append(passport_data) return passports def validate_passport(passport): keys = set(passport) common_data = valid_passport_data.intersection(keys) if len(common_data) == count_required_data: is_valid = True for key in keys: if key == 'cid': continue try: value = passport[key] is_valid = is_valid and validation_rules[key](value) except Exception as e: print(f'ValidationError: {e}') return int(is_valid) return 0 valid_passports_count = 0 passports = load_passports('day4.txt') for p in passports: valid_passports_count += validate_passport(p) print(valid_passports_count)