content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
n, k, v = int(input()), int(input()), [] for i in range(n): v.append(int(input())) v = sorted(v, reverse=True) print(k + v[k:].count(v[k-1]))
(n, k, v) = (int(input()), int(input()), []) for i in range(n): v.append(int(input())) v = sorted(v, reverse=True) print(k + v[k:].count(v[k - 1]))
def get_field_name_from_line(line): return line.split(':')[1].strip() def remove_description(line): if '-' in line: return line.split('-')[0].strip() else: return line def split_multiple_field_names(line): if ',' in line: field_names = line.split(',') return map(lambda x: x.strip().upper(), field_names) else: return [line.upper()] f = open('../data/8-20-17.nm2') out = open('../data/8-20-17-field-names.txt', 'w') for line in f: if line.startswith('FieldName'): field_name = get_field_name_from_line(line) field_name = remove_description(field_name) field_name_list = split_multiple_field_names(field_name) for name in field_name_list: out.writelines([name, '\n']) f.close() out.close()
def get_field_name_from_line(line): return line.split(':')[1].strip() def remove_description(line): if '-' in line: return line.split('-')[0].strip() else: return line def split_multiple_field_names(line): if ',' in line: field_names = line.split(',') return map(lambda x: x.strip().upper(), field_names) else: return [line.upper()] f = open('../data/8-20-17.nm2') out = open('../data/8-20-17-field-names.txt', 'w') for line in f: if line.startswith('FieldName'): field_name = get_field_name_from_line(line) field_name = remove_description(field_name) field_name_list = split_multiple_field_names(field_name) for name in field_name_list: out.writelines([name, '\n']) f.close() out.close()
class Circle: def __init__(self, radius): self.radius = radius def compute_area(self): return self.radius ** 2 * 3.14 circle = Circle(2) print("Area of circuit: " + str(circle.compute_area()))
class Circle: def __init__(self, radius): self.radius = radius def compute_area(self): return self.radius ** 2 * 3.14 circle = circle(2) print('Area of circuit: ' + str(circle.compute_area()))
class Solution: def addStrings(self, num1: str, num2: str) -> str: i, j, result, carry = len(num1) - 1, len(num2) - 1, '', 0 while i >= 0 or j >= 0: if i >= 0: carry += ord(num1[i]) - ord('0') if j >= 0: carry += ord(num2[j]) - ord('0') result += chr(carry % 10 + ord('0')) carry //= 10 i -= 1 j -= 1 if carry == 1: result += '1' return result[::-1]
class Solution: def add_strings(self, num1: str, num2: str) -> str: (i, j, result, carry) = (len(num1) - 1, len(num2) - 1, '', 0) while i >= 0 or j >= 0: if i >= 0: carry += ord(num1[i]) - ord('0') if j >= 0: carry += ord(num2[j]) - ord('0') result += chr(carry % 10 + ord('0')) carry //= 10 i -= 1 j -= 1 if carry == 1: result += '1' return result[::-1]
word = input('Enter a word') len = len(word) for i in range(len-1, -1, -1): print(word[i], end='')
word = input('Enter a word') len = len(word) for i in range(len - 1, -1, -1): print(word[i], end='')
ss = input('Please give me a string: ') if ss == ss[::-1]: print("Yes, %s is a palindrome." % ss) else: print('Nevermind, %s isn\'t a palindrome.' % ss)
ss = input('Please give me a string: ') if ss == ss[::-1]: print('Yes, %s is a palindrome.' % ss) else: print("Nevermind, %s isn't a palindrome." % ss)
class AbridgerError(Exception): pass class ConfigFileLoaderError(AbridgerError): pass class IncludeError(ConfigFileLoaderError): pass class DataError(ConfigFileLoaderError): pass class FileNotFoundError(ConfigFileLoaderError): pass class DatabaseUrlError(AbridgerError): pass class ExtractionModelError(AbridgerError): pass class UnknownTableError(AbridgerError): pass class UnknownColumnError(AbridgerError): pass class InvalidConfigError(ExtractionModelError): pass class RelationIntegrityError(ExtractionModelError): pass class GeneratorError(Exception): pass class CyclicDependencyError(GeneratorError): pass
class Abridgererror(Exception): pass class Configfileloadererror(AbridgerError): pass class Includeerror(ConfigFileLoaderError): pass class Dataerror(ConfigFileLoaderError): pass class Filenotfounderror(ConfigFileLoaderError): pass class Databaseurlerror(AbridgerError): pass class Extractionmodelerror(AbridgerError): pass class Unknowntableerror(AbridgerError): pass class Unknowncolumnerror(AbridgerError): pass class Invalidconfigerror(ExtractionModelError): pass class Relationintegrityerror(ExtractionModelError): pass class Generatorerror(Exception): pass class Cyclicdependencyerror(GeneratorError): pass
def aumentar(preco, taxa): p = preco + (preco * taxa/100) return p def diminuir(preco, taxa): p = preco - (preco * taxa/100) return p def dobro(preco): p = preco * 2 return p def metade(preco): p = preco / 2 return p
def aumentar(preco, taxa): p = preco + preco * taxa / 100 return p def diminuir(preco, taxa): p = preco - preco * taxa / 100 return p def dobro(preco): p = preco * 2 return p def metade(preco): p = preco / 2 return p
DOMAIN = "fitx" ICON = "mdi:weight-lifter" CONF_LOCATIONS = 'locations' CONF_ID = 'id' ATTR_ADDRESS = "address" ATTR_STUDIO_NAME = "studioName" ATTR_ID = CONF_ID ATTR_URL = "url" DEFAULT_ENDPOINT = "https://www.fitx.de/fitnessstudios/{id}" REQUEST_METHOD = "GET" REQUEST_AUTH = None REQUEST_HEADERS = None REQUEST_PAYLOAD = None REQUEST_VERIFY_SSL = True
domain = 'fitx' icon = 'mdi:weight-lifter' conf_locations = 'locations' conf_id = 'id' attr_address = 'address' attr_studio_name = 'studioName' attr_id = CONF_ID attr_url = 'url' default_endpoint = 'https://www.fitx.de/fitnessstudios/{id}' request_method = 'GET' request_auth = None request_headers = None request_payload = None request_verify_ssl = True
#!/usr/bin/env python3 # coding: UTF-8 '''! module description @author <A href="email:[email protected]">George L Fulk</A> ''' __version__ = 0.01 def main(): '''! main description ''' print("Hello world") return 0 if __name__ == "__main__": # command line entry point main() # END #
"""! module description @author <A href="email:[email protected]">George L Fulk</A> """ __version__ = 0.01 def main(): """! main description """ print('Hello world') return 0 if __name__ == '__main__': main()
# https://www.facebook.com/hackercup/problem/169401886867367/ __author__ = "Moonis Javed" __email__ = "[email protected]" def numberOfDays(arr): arr = sorted(arr) n = 0 while len(arr) > 0: k = arr[-1] w = k del arr[-1] while w <= 50: try: del arr[0] w += k except: break if w > 50: n += 1 return n if __name__ == "__main__": f = open("input2.txt").read().split("\n") writeF = open("output2.txt","w") n = int(f[0]) del f[0] for i in range(1,n+1): t = int(f[0]) del f[0] arr =[None]*t for j in xrange(t): arr[j] = int(f[0]) del f[0] writeF.write("Case #%d: %d\n" % (i,numberOfDays(arr))) # print i
__author__ = 'Moonis Javed' __email__ = '[email protected]' def number_of_days(arr): arr = sorted(arr) n = 0 while len(arr) > 0: k = arr[-1] w = k del arr[-1] while w <= 50: try: del arr[0] w += k except: break if w > 50: n += 1 return n if __name__ == '__main__': f = open('input2.txt').read().split('\n') write_f = open('output2.txt', 'w') n = int(f[0]) del f[0] for i in range(1, n + 1): t = int(f[0]) del f[0] arr = [None] * t for j in xrange(t): arr[j] = int(f[0]) del f[0] writeF.write('Case #%d: %d\n' % (i, number_of_days(arr)))
class Robot: def __init__(self, left="MOTOR4", right="MOTOR2", config=1): print("init") def forward(self): print("forward") def backward(self): print("backward") def left(self): print("left") def right(self): print("right") def stop(self): print("stop")
class Robot: def __init__(self, left='MOTOR4', right='MOTOR2', config=1): print('init') def forward(self): print('forward') def backward(self): print('backward') def left(self): print('left') def right(self): print('right') def stop(self): print('stop')
''' Created on 1.12.2016 @author: Darren '''''' Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. " '''
""" Created on 1.12.2016 @author: Darren Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below. For example, given the following triangle [ [2], [3,4], [6,5,7], [4,1,8,3] ] The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11). Note: Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle. " """
#Represents an object class Object: def __init__(self,ID,name): self.name = name self.ID = ID self.importance = 1 #keep track of the events in which this file was the object self.modifiedIn = [] self.addedIn = [] self.deletedIn = [] def getName(self): return self.name def getID(self): return self.ID def getImportance(self): return self.importance #Add an event to the right list according to the modifier #@param event : Event object #@param modifier : "Added" "Deleted" or "Modified" def addEvent(self, event, modifier): if modifier == "Added": if(not event in self.addedIn): self.addedIn.append(event) elif modifier == "Deleted": if(not event in self.deletedIn): self.deletedIn.append(event) else: if(not event in self.modifiedIn): self.modifiedIn.append(event) #Function that calculates the importance of a object based on a ratio: #the number of months in which it was changed / the number of months is exists #@param firstAndLastTimeStamp = tuple with the first timestamp of the log and the last def calculateImportanceRatio(self,firstAndLastTimeStamp): addedTimestamps = [] for event in self.addedIn: addedTimestamps.append(event.getTimestamp()) addedTimestamps.sort() deletedTimestamps = [] for event in self.deletedIn: deletedTimestamps.append(event.getTimestamp()) deletedTimestamps.sort() timestamps = [] for event in self.modifiedIn: timestamps.append(event.getTimestamp()) for event in self.addedIn: timestamps.append(event.getTimestamp()) numberOfMonthsExistence = 0 numberOfMonthsChanged = 0 iteratorAdded = 0 iteratorDeleted = 0 if(not addedTimestamps): beginstamp = firstAndLastTimeStamp[0] #only 2 scenarios possible : 0 or 1 deleted timestamp if(not deletedTimestamps): endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[0] numberOfMonthsExistence += self.calculateNumberOfMonthsExistence(beginstamp,endstamp) numberOfMonthsChanged += self.calculateNumberOfMonthsChanged(beginstamp,endstamp,timestamps) while(iteratorAdded < len(addedTimestamps)): beginstamp = addedTimestamps[iteratorAdded] iteratorAdded += 1 if(iteratorDeleted == len(deletedTimestamps)): #all deleted stamps are done endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[iteratorDeleted] iteratorDeleted += 1 if(endstamp < beginstamp): beginstamp = firstAndLastTimeStamp[0] iteratorAdded -= 1 numberOfMonthsExistence += self.calculateNumberOfMonthsExistence(beginstamp,endstamp) numberOfMonthsChanged += self.calculateNumberOfMonthsChanged(beginstamp,endstamp,timestamps) importance = numberOfMonthsChanged/numberOfMonthsExistence #TO DO: what if importance = 0 ? if importance == 0 : importance = 0.00001 self.importance = importance #calculate how many months this object exists between these 2 timestamps def calculateNumberOfMonthsExistence(self,beginstamp, endstamp): numberOfMonths = abs(endstamp.year - beginstamp.year) * 12 + abs(endstamp.month - beginstamp.month) numberOfMonths += 1 return numberOfMonths #calculate in how many months between begin and end the object was changed #@param timestamps = list of timestamps when the file was committed def calculateNumberOfMonthsChanged(self,beginstamp,endstamp,timestamps): timestamps.sort() numberOfMonths = 0 currentMonth = -1 currentYear = -1 for stamp in timestamps: #only consider the timestamps between the timespan if((stamp >= beginstamp)and(stamp <= endstamp)): if((stamp.month != currentMonth) or (currentYear != stamp.year)): currentMonth = stamp.month currentYear = stamp.year numberOfMonths += 1 return numberOfMonths
class Object: def __init__(self, ID, name): self.name = name self.ID = ID self.importance = 1 self.modifiedIn = [] self.addedIn = [] self.deletedIn = [] def get_name(self): return self.name def get_id(self): return self.ID def get_importance(self): return self.importance def add_event(self, event, modifier): if modifier == 'Added': if not event in self.addedIn: self.addedIn.append(event) elif modifier == 'Deleted': if not event in self.deletedIn: self.deletedIn.append(event) elif not event in self.modifiedIn: self.modifiedIn.append(event) def calculate_importance_ratio(self, firstAndLastTimeStamp): added_timestamps = [] for event in self.addedIn: addedTimestamps.append(event.getTimestamp()) addedTimestamps.sort() deleted_timestamps = [] for event in self.deletedIn: deletedTimestamps.append(event.getTimestamp()) deletedTimestamps.sort() timestamps = [] for event in self.modifiedIn: timestamps.append(event.getTimestamp()) for event in self.addedIn: timestamps.append(event.getTimestamp()) number_of_months_existence = 0 number_of_months_changed = 0 iterator_added = 0 iterator_deleted = 0 if not addedTimestamps: beginstamp = firstAndLastTimeStamp[0] if not deletedTimestamps: endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[0] number_of_months_existence += self.calculateNumberOfMonthsExistence(beginstamp, endstamp) number_of_months_changed += self.calculateNumberOfMonthsChanged(beginstamp, endstamp, timestamps) while iteratorAdded < len(addedTimestamps): beginstamp = addedTimestamps[iteratorAdded] iterator_added += 1 if iteratorDeleted == len(deletedTimestamps): endstamp = firstAndLastTimeStamp[1] else: endstamp = deletedTimestamps[iteratorDeleted] iterator_deleted += 1 if endstamp < beginstamp: beginstamp = firstAndLastTimeStamp[0] iterator_added -= 1 number_of_months_existence += self.calculateNumberOfMonthsExistence(beginstamp, endstamp) number_of_months_changed += self.calculateNumberOfMonthsChanged(beginstamp, endstamp, timestamps) importance = numberOfMonthsChanged / numberOfMonthsExistence if importance == 0: importance = 1e-05 self.importance = importance def calculate_number_of_months_existence(self, beginstamp, endstamp): number_of_months = abs(endstamp.year - beginstamp.year) * 12 + abs(endstamp.month - beginstamp.month) number_of_months += 1 return numberOfMonths def calculate_number_of_months_changed(self, beginstamp, endstamp, timestamps): timestamps.sort() number_of_months = 0 current_month = -1 current_year = -1 for stamp in timestamps: if stamp >= beginstamp and stamp <= endstamp: if stamp.month != currentMonth or currentYear != stamp.year: current_month = stamp.month current_year = stamp.year number_of_months += 1 return numberOfMonths
def uint(x): # casts x to unsigned int (1 byte) return x & 0xff def chunkify(string, size): # breaks up string into chunks of size chunks = [] for i in range(0, len(string), size): chunks.append(string[i:i + size]) return chunks def gen_rcons(rounds): # generates and returns round constants # the round constants don't depend on the # key so these constants could have been # hard coded, but I wanted to build it anyway rcons = [] for i in range(rounds): value = 0 if i + 1 > 1: if rcons[i - 1] >= 0x80: value = uint((2 * rcons[i - 1]) ^ 0x11b) else: value = uint(2 * rcons[i - 1]) else: value = 1 rcons.append(value) return list(map(lambda x: x << 24, rcons)) def generate_round_keys(key, rounds, sbox): # Generates round keys based on main key # basic variables used for looping, etc. key_size = len(key) * 8 R = rounds + 1 rcons = gen_rcons(rounds) # get round key constants N = key_size // 32 # split key into 32 bit words and parse to int K = [int(k.encode("utf-8").hex(), 16) for k in chunkify(key, 4)] W = [0] * (4 * R) # main loop to generate expanded round subkeys for i in range(4 * R): if i < N: W[i] = K[i] elif i >= N and i % N == 0: word_str = hex(W[i - 1])[2:].zfill(8) # turn int to 8 digit hex rot = word_str[2:] + word_str[:2] # rotate left 1 byte hex_bytes = chunkify(rot, 2) # split into byte chunks subvals = [sbox(hexb) for hexb in hex_bytes] # sub out hex bytes with s-box sval = (subvals[0] << 24) \ + (subvals[1] << 16) \ + (subvals[2] << 8) \ + subvals[3] # concat hex bytes and parse to 32 bit int W[i] = W[i - N] ^ sval ^ rcons[(i // N) - 1] elif i >= N and N > 6 and i % N == 4: word_str = hex(W[i - 1])[2:].zfill(8) # turn int to 8 digit hex hex_bytes = chunkify(word_str, 2) # split into byte chunks subvals = [sbox(hexb) for hexb in hex_bytes] # sub out hex bytes with s-box sval = (subvals[0] << 24) \ + (subvals[1] << 16) \ + (subvals[2] << 8) \ + subvals[3] # concat hex bytes and parse to 32 bit int W[i] = W[i - N] ^ sval else: W[i] = W[i - N] ^ W[i - 1] # subkeys are all 128 bits, but each entry is 32 bits # so combine all entries by groups of 4 for later use return [tuple(W[i:i + 4]) for i in range(0, len(W), 4)] def add_round_key(state, round_key): # adds each byte of the round key to the # respective byte of the state key = [] # round key is a tuple of 4, 32 bit ints for rk in round_key: hx = hex(rk)[2:].zfill(8) # turn int to hex # add each byte to the key list as an int key += [int(hx[i:i + 2], 16) for i in range(0, len(hx), 2)] for i in range(len(state)): # run through the state and add each byte to the # respective byte in the key key_state = [key[j] for j in range(i, len(key), 4)] state[i] = [sv ^ kv for sv, kv in zip(state[i], key_state)] return state
def uint(x): return x & 255 def chunkify(string, size): chunks = [] for i in range(0, len(string), size): chunks.append(string[i:i + size]) return chunks def gen_rcons(rounds): rcons = [] for i in range(rounds): value = 0 if i + 1 > 1: if rcons[i - 1] >= 128: value = uint(2 * rcons[i - 1] ^ 283) else: value = uint(2 * rcons[i - 1]) else: value = 1 rcons.append(value) return list(map(lambda x: x << 24, rcons)) def generate_round_keys(key, rounds, sbox): key_size = len(key) * 8 r = rounds + 1 rcons = gen_rcons(rounds) n = key_size // 32 k = [int(k.encode('utf-8').hex(), 16) for k in chunkify(key, 4)] w = [0] * (4 * R) for i in range(4 * R): if i < N: W[i] = K[i] elif i >= N and i % N == 0: word_str = hex(W[i - 1])[2:].zfill(8) rot = word_str[2:] + word_str[:2] hex_bytes = chunkify(rot, 2) subvals = [sbox(hexb) for hexb in hex_bytes] sval = (subvals[0] << 24) + (subvals[1] << 16) + (subvals[2] << 8) + subvals[3] W[i] = W[i - N] ^ sval ^ rcons[i // N - 1] elif i >= N and N > 6 and (i % N == 4): word_str = hex(W[i - 1])[2:].zfill(8) hex_bytes = chunkify(word_str, 2) subvals = [sbox(hexb) for hexb in hex_bytes] sval = (subvals[0] << 24) + (subvals[1] << 16) + (subvals[2] << 8) + subvals[3] W[i] = W[i - N] ^ sval else: W[i] = W[i - N] ^ W[i - 1] return [tuple(W[i:i + 4]) for i in range(0, len(W), 4)] def add_round_key(state, round_key): key = [] for rk in round_key: hx = hex(rk)[2:].zfill(8) key += [int(hx[i:i + 2], 16) for i in range(0, len(hx), 2)] for i in range(len(state)): key_state = [key[j] for j in range(i, len(key), 4)] state[i] = [sv ^ kv for (sv, kv) in zip(state[i], key_state)] return state
def modulus_three(n): r = n % 3 if r == 0: print("Multiple of 3") elif r == 1: print("Remainder 1") else: assert r == 2, "Remainder is not 2" print("Remainder 2") def modulus_four(n): r = n % 4 if r == 0: print("Multiple of 4") elif r == 1: print("Remainder 1") elif r == 2: print("Remainder 2") elif r == 3: print("Remainder 3") else: assert False, "This should never happen" if __name__ == '__main__': print(modulus_four(5))
def modulus_three(n): r = n % 3 if r == 0: print('Multiple of 3') elif r == 1: print('Remainder 1') else: assert r == 2, 'Remainder is not 2' print('Remainder 2') def modulus_four(n): r = n % 4 if r == 0: print('Multiple of 4') elif r == 1: print('Remainder 1') elif r == 2: print('Remainder 2') elif r == 3: print('Remainder 3') else: assert False, 'This should never happen' if __name__ == '__main__': print(modulus_four(5))
BASE_FILES = "C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\" BASE_FILES_GENERAL = BASE_FILES + "general\\" G1 = BASE_FILES + "t_graph_1.ttl" G1_NT = BASE_FILES + "t_graph_1.nt" G1_TSVO_SPO = BASE_FILES + "t_graph_1.tsv" G1_JSON_LD = BASE_FILES + "t_graph_1.json" G1_XML = BASE_FILES + "t_graph_1.xml" G1_N3 = BASE_FILES + "t_graph_1.n3" G1_ALL_CLASSES_NO_COMMENTS = BASE_FILES_GENERAL + "g1_all_classes_no_comments.shex" # PREFIX xml: <http://www.w3.org/XML/1998/namespace/> # PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> # PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#> # PREFIX xsd: <http://www.w3.org/2001/XMLSchema#> # PREFIX foaf: <http://xmlns.com/foaf/0.1/> # NAMESPACES_WITH_FOAF_AND_EX = {"http://example.org/" : "ex", # "http://www.w3.org/XML/1998/namespace/" : "xml", # "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", # "http://www.w3.org/2000/01/rdf-schema#" : "rdfs", # "http://www.w3.org/2001/XMLSchema#": "xsd", # "http://xmlns.com/foaf/0.1/": "foaf" # } def default_namespaces(): return {"http://example.org/": "ex", "http://www.w3.org/XML/1998/namespace/": "xml", "http://www.w3.org/1999/02/22-rdf-syntax-ns#": "rdf", "http://www.w3.org/2000/01/rdf-schema#": "rdfs", "http://www.w3.org/2001/XMLSchema#": "xsd", "http://xmlns.com/foaf/0.1/": "foaf" }
base_files = 'C:\\Users\\Dani\\repos-git\\shexerp3\\test\\t_files\\' base_files_general = BASE_FILES + 'general\\' g1 = BASE_FILES + 't_graph_1.ttl' g1_nt = BASE_FILES + 't_graph_1.nt' g1_tsvo_spo = BASE_FILES + 't_graph_1.tsv' g1_json_ld = BASE_FILES + 't_graph_1.json' g1_xml = BASE_FILES + 't_graph_1.xml' g1_n3 = BASE_FILES + 't_graph_1.n3' g1_all_classes_no_comments = BASE_FILES_GENERAL + 'g1_all_classes_no_comments.shex' def default_namespaces(): return {'http://example.org/': 'ex', 'http://www.w3.org/XML/1998/namespace/': 'xml', 'http://www.w3.org/1999/02/22-rdf-syntax-ns#': 'rdf', 'http://www.w3.org/2000/01/rdf-schema#': 'rdfs', 'http://www.w3.org/2001/XMLSchema#': 'xsd', 'http://xmlns.com/foaf/0.1/': 'foaf'}
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") def deps(): excludes = native.existing_rules().keys() if "bazel_installer" not in excludes: http_file( name = "bazel_installer", downloaded_file_path = "bazel-installer.sh", sha256 = "bd7a3a583a18640f58308c26e654239d412adaa833b6b6a7b57a216ab62fabc2", urls = [ "https://releases.bazel.build/4.0.0/release/bazel-4.0.0-installer-linux-x86_64.sh", "https://github.com/bazelbuild/bazel/releases/download/4.0.0/bazel-4.0.0-installer-linux-x86_64.sh", ], )
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_file') def deps(): excludes = native.existing_rules().keys() if 'bazel_installer' not in excludes: http_file(name='bazel_installer', downloaded_file_path='bazel-installer.sh', sha256='bd7a3a583a18640f58308c26e654239d412adaa833b6b6a7b57a216ab62fabc2', urls=['https://releases.bazel.build/4.0.0/release/bazel-4.0.0-installer-linux-x86_64.sh', 'https://github.com/bazelbuild/bazel/releases/download/4.0.0/bazel-4.0.0-installer-linux-x86_64.sh'])
class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if not self.language == language: return f"{self.name} does not know {language}" self.skills += skills_earned return f"{self.name} watched {course_name}" def change_language(self, new_language, skills_needed): if not skills_needed <= self.skills: needed_skills = skills_needed - self.skills return f"{self.name} needs {needed_skills} more skills" if self.language == new_language: return f"{self.name} already knows {self.language}" previous_language = self.language self.language = new_language return f"{self.name} switched from {previous_language} to {new_language}"
class Programmer: def __init__(self, name, language, skills): self.name = name self.language = language self.skills = skills def watch_course(self, course_name, language, skills_earned): if not self.language == language: return f'{self.name} does not know {language}' self.skills += skills_earned return f'{self.name} watched {course_name}' def change_language(self, new_language, skills_needed): if not skills_needed <= self.skills: needed_skills = skills_needed - self.skills return f'{self.name} needs {needed_skills} more skills' if self.language == new_language: return f'{self.name} already knows {self.language}' previous_language = self.language self.language = new_language return f'{self.name} switched from {previous_language} to {new_language}'
#returns the value to the variable # x = 900 print(x) #print will take the argument x as the value in the variable #
x = 900 print(x)
def add(tree, x): if not tree: tree.extend([x, None, None]) print('DONE') return key = tree[0] if x == key: print('ALREADY') elif x < key: left = tree[1] if left == None: tree[1] = [x, None, None] print('DONE') else: add(left, x) elif x > key: right = tree[2] if right == None: tree[2] = [x, None, None] print('DONE') else: add(right, x) def find(tree, x): if not tree: return False key = tree[0] if x == key: return True elif x < key: left = tree[1] if left == None: return False else: return find(left, x) elif x > key: right = tree[2] if right == None: return False else: return find(right, x) def printtree(tree, count=0): # if not tree: # return if tree[1]: printtree(tree[1], count + 1) print(f"{''.join('.' * count)}{tree[0]}") if tree[2]: printtree(tree[2], count + 1) tree = [] with open('input.txt', 'r', encoding='utf-8') as file: string = file.readline().strip() while string != '': line = [i for i in string.split()] if line[0] == 'ADD': add(tree, int(line[1])) elif line[0] == 'SEARCH': if find(tree, int(line[1])): print('YES') else: print('NO') elif line[0] == 'PRINTTREE': printtree(tree) string = file.readline().strip()
def add(tree, x): if not tree: tree.extend([x, None, None]) print('DONE') return key = tree[0] if x == key: print('ALREADY') elif x < key: left = tree[1] if left == None: tree[1] = [x, None, None] print('DONE') else: add(left, x) elif x > key: right = tree[2] if right == None: tree[2] = [x, None, None] print('DONE') else: add(right, x) def find(tree, x): if not tree: return False key = tree[0] if x == key: return True elif x < key: left = tree[1] if left == None: return False else: return find(left, x) elif x > key: right = tree[2] if right == None: return False else: return find(right, x) def printtree(tree, count=0): if tree[1]: printtree(tree[1], count + 1) print(f"{''.join('.' * count)}{tree[0]}") if tree[2]: printtree(tree[2], count + 1) tree = [] with open('input.txt', 'r', encoding='utf-8') as file: string = file.readline().strip() while string != '': line = [i for i in string.split()] if line[0] == 'ADD': add(tree, int(line[1])) elif line[0] == 'SEARCH': if find(tree, int(line[1])): print('YES') else: print('NO') elif line[0] == 'PRINTTREE': printtree(tree) string = file.readline().strip()
batch_size, num_samples, sample_rate = 32, 32000, 16000.0 # A Tensor of [batch_size, num_samples] mono PCM samples in the range [-1, 1]. pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32) # A 1024-point STFT with frames of 64 ms and 75% overlap. stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256, fft_length=1024) spectrograms = tf.abs(stfts) # Warp the linear scale spectrograms into the mel-scale. num_spectrogram_bins = stfts.shape[-1].value lower_edge_hertz, upper_edge_hertz, num_mel_bins = 80.0, 7600.0, 80 linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix( num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, upper_edge_hertz) mel_spectrograms = tf.tensordot( spectrograms, linear_to_mel_weight_matrix, 1) mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate( linear_to_mel_weight_matrix.shape[-1:])) # Compute a stabilized log to get log-magnitude mel-scale spectrograms. log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-6) # Compute MFCCs from log_mel_spectrograms and take the first 13. mfccs = tf.signal.mfccs_from_log_mel_spectrograms( log_mel_spectrograms)[..., :13]
(batch_size, num_samples, sample_rate) = (32, 32000, 16000.0) pcm = tf.random.normal([batch_size, num_samples], dtype=tf.float32) stfts = tf.signal.stft(pcm, frame_length=1024, frame_step=256, fft_length=1024) spectrograms = tf.abs(stfts) num_spectrogram_bins = stfts.shape[-1].value (lower_edge_hertz, upper_edge_hertz, num_mel_bins) = (80.0, 7600.0, 80) linear_to_mel_weight_matrix = tf.signal.linear_to_mel_weight_matrix(num_mel_bins, num_spectrogram_bins, sample_rate, lower_edge_hertz, upper_edge_hertz) mel_spectrograms = tf.tensordot(spectrograms, linear_to_mel_weight_matrix, 1) mel_spectrograms.set_shape(spectrograms.shape[:-1].concatenate(linear_to_mel_weight_matrix.shape[-1:])) log_mel_spectrograms = tf.math.log(mel_spectrograms + 1e-06) mfccs = tf.signal.mfccs_from_log_mel_spectrograms(log_mel_spectrograms)[..., :13]
class Element: dependencies = [] def __init__(self, name): self.name = name def add_dependencies(self, *elements): for element in elements: if not self.dependencies.__contains__(element): self.dependencies.append(element) def remove_dependencies(self, *elements): for element in elements: if self.dependencies.__contains__(element): self.dependencies.remove(element)
class Element: dependencies = [] def __init__(self, name): self.name = name def add_dependencies(self, *elements): for element in elements: if not self.dependencies.__contains__(element): self.dependencies.append(element) def remove_dependencies(self, *elements): for element in elements: if self.dependencies.__contains__(element): self.dependencies.remove(element)
# known contracts from protocol CONTRACTS = [ # NFT - Meteor Dust "terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7", # NFT - Eggs "terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg", # NFT - Dragons "terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6", # NFT - Loot "terra14gfnxnwl0yz6njzet4n33erq5n70wt79nm24el", ] def handle(exporter, elem, txinfo, contract): print(f"Levana! {contract}") #print(elem)
contracts = ['terra1p70x7jkqhf37qa7qm4v23g4u4g8ka4ktxudxa7', 'terra1k0y373yxqne22pc9g7jvnr4qclpsxtafevtrpg', 'terra1vhuyuwwr4rkdpez5f5lmuqavut28h5dt29rpn6', 'terra14gfnxnwl0yz6njzet4n33erq5n70wt79nm24el'] def handle(exporter, elem, txinfo, contract): print(f'Levana! {contract}')
def isPalindrome(string, i = 0): j = len(string) - 1 -i return True if i > j else string[i] == string[j] and isPalindrome(string, i+1) def isPalindrome(string): return string == string[::-1] def isPalindromeUsingIndexes(string): lIx = 0 rIdx = len(string) -1 while lIx < rIdx: if(string[lIx] != string [rIdx]): return False else: lIx += 1 rIdx -=1 return True
def is_palindrome(string, i=0): j = len(string) - 1 - i return True if i > j else string[i] == string[j] and is_palindrome(string, i + 1) def is_palindrome(string): return string == string[::-1] def is_palindrome_using_indexes(string): l_ix = 0 r_idx = len(string) - 1 while lIx < rIdx: if string[lIx] != string[rIdx]: return False else: l_ix += 1 r_idx -= 1 return True
# coding=utf-8 # *** WARNING: this file was generated by crd2pulumi. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** SNAKE_TO_CAMEL_CASE_TABLE = { "access_modes": "accessModes", "api_group": "apiGroup", "api_version": "apiVersion", "app_protocol": "appProtocol", "association_status": "associationStatus", "available_nodes": "availableNodes", "change_budget": "changeBudget", "client_ip": "clientIP", "cluster_ip": "clusterIP", "config_ref": "configRef", "daemon_set": "daemonSet", "data_source": "dataSource", "elasticsearch_association_status": "elasticsearchAssociationStatus", "elasticsearch_ref": "elasticsearchRef", "expected_nodes": "expectedNodes", "external_i_ps": "externalIPs", "external_name": "externalName", "external_traffic_policy": "externalTrafficPolicy", "file_realm": "fileRealm", "health_check_node_port": "healthCheckNodePort", "ip_family": "ipFamily", "kibana_association_status": "kibanaAssociationStatus", "kibana_ref": "kibanaRef", "last_probe_time": "lastProbeTime", "last_transition_time": "lastTransitionTime", "load_balancer_ip": "loadBalancerIP", "load_balancer_source_ranges": "loadBalancerSourceRanges", "match_expressions": "matchExpressions", "match_labels": "matchLabels", "max_surge": "maxSurge", "max_unavailable": "maxUnavailable", "min_available": "minAvailable", "node_port": "nodePort", "node_sets": "nodeSets", "pod_disruption_budget": "podDisruptionBudget", "pod_template": "podTemplate", "publish_not_ready_addresses": "publishNotReadyAddresses", "remote_clusters": "remoteClusters", "rolling_update": "rollingUpdate", "secret_name": "secretName", "secret_token_secret": "secretTokenSecret", "secure_settings": "secureSettings", "self_signed_certificate": "selfSignedCertificate", "service_account_name": "serviceAccountName", "session_affinity": "sessionAffinity", "session_affinity_config": "sessionAffinityConfig", "storage_class_name": "storageClassName", "subject_alt_names": "subjectAltNames", "target_port": "targetPort", "timeout_seconds": "timeoutSeconds", "topology_keys": "topologyKeys", "update_strategy": "updateStrategy", "volume_claim_templates": "volumeClaimTemplates", "volume_mode": "volumeMode", "volume_name": "volumeName", } CAMEL_TO_SNAKE_CASE_TABLE = { "accessModes": "access_modes", "apiGroup": "api_group", "apiVersion": "api_version", "appProtocol": "app_protocol", "associationStatus": "association_status", "availableNodes": "available_nodes", "changeBudget": "change_budget", "clientIP": "client_ip", "clusterIP": "cluster_ip", "configRef": "config_ref", "daemonSet": "daemon_set", "dataSource": "data_source", "elasticsearchAssociationStatus": "elasticsearch_association_status", "elasticsearchRef": "elasticsearch_ref", "expectedNodes": "expected_nodes", "externalIPs": "external_i_ps", "externalName": "external_name", "externalTrafficPolicy": "external_traffic_policy", "fileRealm": "file_realm", "healthCheckNodePort": "health_check_node_port", "ipFamily": "ip_family", "kibanaAssociationStatus": "kibana_association_status", "kibanaRef": "kibana_ref", "lastProbeTime": "last_probe_time", "lastTransitionTime": "last_transition_time", "loadBalancerIP": "load_balancer_ip", "loadBalancerSourceRanges": "load_balancer_source_ranges", "matchExpressions": "match_expressions", "matchLabels": "match_labels", "maxSurge": "max_surge", "maxUnavailable": "max_unavailable", "minAvailable": "min_available", "nodePort": "node_port", "nodeSets": "node_sets", "podDisruptionBudget": "pod_disruption_budget", "podTemplate": "pod_template", "publishNotReadyAddresses": "publish_not_ready_addresses", "remoteClusters": "remote_clusters", "rollingUpdate": "rolling_update", "secretName": "secret_name", "secretTokenSecret": "secret_token_secret", "secureSettings": "secure_settings", "selfSignedCertificate": "self_signed_certificate", "serviceAccountName": "service_account_name", "sessionAffinity": "session_affinity", "sessionAffinityConfig": "session_affinity_config", "storageClassName": "storage_class_name", "subjectAltNames": "subject_alt_names", "targetPort": "target_port", "timeoutSeconds": "timeout_seconds", "topologyKeys": "topology_keys", "updateStrategy": "update_strategy", "volumeClaimTemplates": "volume_claim_templates", "volumeMode": "volume_mode", "volumeName": "volume_name", }
snake_to_camel_case_table = {'access_modes': 'accessModes', 'api_group': 'apiGroup', 'api_version': 'apiVersion', 'app_protocol': 'appProtocol', 'association_status': 'associationStatus', 'available_nodes': 'availableNodes', 'change_budget': 'changeBudget', 'client_ip': 'clientIP', 'cluster_ip': 'clusterIP', 'config_ref': 'configRef', 'daemon_set': 'daemonSet', 'data_source': 'dataSource', 'elasticsearch_association_status': 'elasticsearchAssociationStatus', 'elasticsearch_ref': 'elasticsearchRef', 'expected_nodes': 'expectedNodes', 'external_i_ps': 'externalIPs', 'external_name': 'externalName', 'external_traffic_policy': 'externalTrafficPolicy', 'file_realm': 'fileRealm', 'health_check_node_port': 'healthCheckNodePort', 'ip_family': 'ipFamily', 'kibana_association_status': 'kibanaAssociationStatus', 'kibana_ref': 'kibanaRef', 'last_probe_time': 'lastProbeTime', 'last_transition_time': 'lastTransitionTime', 'load_balancer_ip': 'loadBalancerIP', 'load_balancer_source_ranges': 'loadBalancerSourceRanges', 'match_expressions': 'matchExpressions', 'match_labels': 'matchLabels', 'max_surge': 'maxSurge', 'max_unavailable': 'maxUnavailable', 'min_available': 'minAvailable', 'node_port': 'nodePort', 'node_sets': 'nodeSets', 'pod_disruption_budget': 'podDisruptionBudget', 'pod_template': 'podTemplate', 'publish_not_ready_addresses': 'publishNotReadyAddresses', 'remote_clusters': 'remoteClusters', 'rolling_update': 'rollingUpdate', 'secret_name': 'secretName', 'secret_token_secret': 'secretTokenSecret', 'secure_settings': 'secureSettings', 'self_signed_certificate': 'selfSignedCertificate', 'service_account_name': 'serviceAccountName', 'session_affinity': 'sessionAffinity', 'session_affinity_config': 'sessionAffinityConfig', 'storage_class_name': 'storageClassName', 'subject_alt_names': 'subjectAltNames', 'target_port': 'targetPort', 'timeout_seconds': 'timeoutSeconds', 'topology_keys': 'topologyKeys', 'update_strategy': 'updateStrategy', 'volume_claim_templates': 'volumeClaimTemplates', 'volume_mode': 'volumeMode', 'volume_name': 'volumeName'} camel_to_snake_case_table = {'accessModes': 'access_modes', 'apiGroup': 'api_group', 'apiVersion': 'api_version', 'appProtocol': 'app_protocol', 'associationStatus': 'association_status', 'availableNodes': 'available_nodes', 'changeBudget': 'change_budget', 'clientIP': 'client_ip', 'clusterIP': 'cluster_ip', 'configRef': 'config_ref', 'daemonSet': 'daemon_set', 'dataSource': 'data_source', 'elasticsearchAssociationStatus': 'elasticsearch_association_status', 'elasticsearchRef': 'elasticsearch_ref', 'expectedNodes': 'expected_nodes', 'externalIPs': 'external_i_ps', 'externalName': 'external_name', 'externalTrafficPolicy': 'external_traffic_policy', 'fileRealm': 'file_realm', 'healthCheckNodePort': 'health_check_node_port', 'ipFamily': 'ip_family', 'kibanaAssociationStatus': 'kibana_association_status', 'kibanaRef': 'kibana_ref', 'lastProbeTime': 'last_probe_time', 'lastTransitionTime': 'last_transition_time', 'loadBalancerIP': 'load_balancer_ip', 'loadBalancerSourceRanges': 'load_balancer_source_ranges', 'matchExpressions': 'match_expressions', 'matchLabels': 'match_labels', 'maxSurge': 'max_surge', 'maxUnavailable': 'max_unavailable', 'minAvailable': 'min_available', 'nodePort': 'node_port', 'nodeSets': 'node_sets', 'podDisruptionBudget': 'pod_disruption_budget', 'podTemplate': 'pod_template', 'publishNotReadyAddresses': 'publish_not_ready_addresses', 'remoteClusters': 'remote_clusters', 'rollingUpdate': 'rolling_update', 'secretName': 'secret_name', 'secretTokenSecret': 'secret_token_secret', 'secureSettings': 'secure_settings', 'selfSignedCertificate': 'self_signed_certificate', 'serviceAccountName': 'service_account_name', 'sessionAffinity': 'session_affinity', 'sessionAffinityConfig': 'session_affinity_config', 'storageClassName': 'storage_class_name', 'subjectAltNames': 'subject_alt_names', 'targetPort': 'target_port', 'timeoutSeconds': 'timeout_seconds', 'topologyKeys': 'topology_keys', 'updateStrategy': 'update_strategy', 'volumeClaimTemplates': 'volume_claim_templates', 'volumeMode': 'volume_mode', 'volumeName': 'volume_name'}
# List of addresses within the Battle Animation Scripts for the following commands which cause screen flashes: # B0 - Set background palette color addition (absolute) # B5 - Add color to background palette (relative) # AF - Set background palette color subtraction (absolute) # B6 - Subtract color from background palette (relative) # By changing address + 1 to E0 (for absolute) or F0 (for relative), it causes no change to the background color (that is, no flash) BATTLE_ANIMATION_FLASHES = { "Goner": [ 0x100088, # AF E0 - set background color subtraction to 0 (black) 0x10008C, # B6 61 - increase background color subtraction by 1 (red) 0x100092, # B6 31 - decrease background color subtraction by 1 (yellow) 0x100098, # B6 81 - increase background color subtraction by 1 (cyan) 0x1000A1, # B6 91 - decrease background color subtraction by 1 (cyan) 0x1000A3, # B6 21 - increase background color subtraction by 1 (yellow) 0x1000D3, # B6 8F - increase background color subtraction by 15 (cyan) 0x1000DF, # B0 FF - set background color addition to 31 (white) 0x100172, # B5 F2 - decrease background color addition by 2 (white) ], "Final KEFKA Death": [ 0x10023A, # B0 FF - set background color addition to 31 (white) 0x100240, # B5 F4 - decrease background color addition by 4 (white) 0x100248, # B0 FF - set background color addition to 31 (white) 0x10024E, # B5 F4 - decrease background color addition by 4 (white) ], "Atom Edge": [ # Also True Edge 0x1003D0, # AF E0 - set background color subtraction to 0 (black) 0x1003DD, # B6 E1 - increase background color subtraction by 1 (black) 0x1003E6, # B6 E1 - increase background color subtraction by 1 (black) 0x10044B, # B6 F1 - decrease background color subtraction by 1 (black) 0x100457, # B6 F1 - decrease background color subtraction by 1 (black) ], "Boss Death": [ 0x100476, # B0 FF - set background color addition to 31 (white) 0x10047C, # B5 F4 - decrease background color addition by 4 (white) 0x100484, # B0 FF - set background color addition to 31 (white) 0x100497, # B5 F4 - decrease background color addition by 4 (white) ], "Transform into Magicite": [ 0x100F30, # B0 FF - set background color addition to 31 (white) 0x100F3F, # B5 F2 - decrease background color addition by 2 (white) 0x100F4E, # B5 F2 - decrease background color addition by 2 (white) ], "Purifier": [ 0x101340, # AF E0 - set background color subtraction to 0 (black) 0x101348, # B6 62 - increase background color subtraction by 2 (red) 0x101380, # B6 81 - increase background color subtraction by 1 (cyan) 0x10138A, # B6 F1 - decrease background color subtraction by 1 (black) ], "Wall": [ 0x10177B, # AF E0 - set background color subtraction to 0 (black) 0x10177F, # B6 61 - increase background color subtraction by 1 (red) 0x101788, # B6 51 - decrease background color subtraction by 1 (magenta) 0x101791, # B6 81 - increase background color subtraction by 1 (cyan) 0x10179A, # B6 31 - decrease background color subtraction by 1 (yellow) 0x1017A3, # B6 41 - increase background color subtraction by 1 (magenta) 0x1017AC, # B6 91 - decrease background color subtraction by 1 (cyan) 0x1017B5, # B6 51 - decrease background color subtraction by 1 (magenta) ], "Pearl": [ 0x10190E, # B0 E0 - set background color addition to 0 (white) 0x101913, # B5 E2 - increase background color addition by 2 (white) 0x10191E, # B5 F1 - decrease background color addition by 1 (white) 0x10193E, # B6 C2 - increase background color subtraction by 2 (blue) ], "Ice 3": [ 0x101978, # B0 FF - set background color addition to 31 (white) 0x10197B, # B5 F4 - decrease background color addition by 4 (white) 0x10197E, # B5 F4 - decrease background color addition by 4 (white) 0x101981, # B5 F4 - decrease background color addition by 4 (white) 0x101984, # B5 F4 - decrease background color addition by 4 (white) 0x101987, # B5 F4 - decrease background color addition by 4 (white) 0x10198A, # B5 F4 - decrease background color addition by 4 (white) 0x10198D, # B5 F4 - decrease background color addition by 4 (white) 0x101990, # B5 F4 - decrease background color addition by 4 (white) ], "Fire 3": [ 0x1019FA, # B0 9F - set background color addition to 31 (red) 0x101A1C, # B5 94 - decrease background color addition by 4 (red) ], "Sleep": [ 0x101A23, # AF E0 - set background color subtraction to 0 (black) 0x101A29, # B6 E1 - increase background color subtraction by 1 (black) 0x101A33, # B6 F1 - decrease background color subtraction by 1 (black) ], "7-Flush": [ 0x101B43, # AF E0 - set background color subtraction to 0 (black) 0x101B47, # B6 61 - increase background color subtraction by 1 (red) 0x101B4D, # B6 51 - decrease background color subtraction by 1 (magenta) 0x101B53, # B6 81 - increase background color subtraction by 1 (cyan) 0x101B59, # B6 31 - decrease background color subtraction by 1 (yellow) 0x101B5F, # B6 41 - increase background color subtraction by 1 (magenta) 0x101B65, # B6 91 - decrease background color subtraction by 1 (cyan) 0x101B6B, # B6 51 - decrease background color subtraction by 1 (magenta) ], "H-Bomb": [ 0x101BC5, # B0 E0 - set background color addition to 0 (white) 0x101BC9, # B5 E1 - increase background color addition by 1 (white) 0x101C13, # B5 F1 - decrease background color addition by 1 (white) ], "Revenger": [ 0x101C62, # AF E0 - set background color subtraction to 0 (black) 0x101C66, # B6 81 - increase background color subtraction by 1 (cyan) 0x101C6C, # B6 41 - increase background color subtraction by 1 (magenta) 0x101C72, # B6 91 - decrease background color subtraction by 1 (cyan) 0x101C78, # B6 21 - increase background color subtraction by 1 (yellow) 0x101C7E, # B6 51 - decrease background color subtraction by 1 (magenta) 0x101C84, # B6 81 - increase background color subtraction by 1 (cyan) 0x101C86, # B6 31 - decrease background color subtraction by 1 (yellow) 0x101C8C, # B6 91 - decrease background color subtraction by 1 (cyan) ], "Phantasm": [ 0x101DFD, # AF E0 - set background color subtraction to 0 (black) 0x101E03, # B6 E1 - increase background color subtraction by 1 (black) 0x101E07, # B0 FF - set background color addition to 31 (white) 0x101E0D, # B5 F4 - decrease background color addition by 4 (white) 0x101E15, # B6 E2 - increase background color subtraction by 2 (black) 0x101E1F, # B0 FF - set background color addition to 31 (white) 0x101E27, # B5 F4 - decrease background color addition by 4 (white) 0x101E2F, # B6 E2 - increase background color subtraction by 2 (black) 0x101E3B, # B6 F1 - decrease background color subtraction by 1 (black) ], "TigerBreak": [ 0x10240D, # B0 FF - set background color addition to 31 (white) 0x102411, # B5 F2 - decrease background color addition by 2 (white) 0x102416, # B5 F2 - decrease background color addition by 2 (white) ], "Metamorph": [ 0x102595, # AF E0 - set background color subtraction to 0 (black) 0x102599, # B6 61 - increase background color subtraction by 1 (red) 0x1025AF, # B6 71 - decrease background color subtraction by 1 (red) ], "Cat Rain": [ 0x102677, # B0 FF - set background color addition to 31 (white) 0x10267B, # B5 F1 - decrease background color addition by 1 (white) ], "Charm": [ 0x1026EE, # B0 FF - set background color addition to 31 (white) 0x1026FB, # B5 F1 - decrease background color addition by 1 (white) ], "Mirager": [ 0x102791, # B0 FF - set background color addition to 31 (white) 0x102795, # B5 F2 - decrease background color addition by 2 (white) ], "SabreSoul": [ 0x1027D3, # B0 FF - set background color addition to 31 (white) 0x1027DA, # B5 F2 - decrease background color addition by 2 (white) ], "Back Blade": [ 0x1028D3, # AF FF - set background color subtraction to 31 (black) 0x1028DF, # B6 F4 - decrease background color subtraction by 4 (black) ], "RoyalShock": [ 0x102967, # B0 FF - set background color addition to 31 (white) 0x10296B, # B5 F2 - decrease background color addition by 2 (white) 0x102973, # B5 F2 - decrease background color addition by 2 (white) ], "Overcast": [ 0x102C3A, # AF E0 - set background color subtraction to 0 (black) 0x102C55, # B6 E1 - increase background color subtraction by 1 (black) 0x102C8D, # B6 F1 - decrease background color subtraction by 1 (black) 0x102C91, # B6 F1 - decrease background color subtraction by 1 (black) ], "Disaster": [ 0x102CEE, # AF E0 - set background color subtraction to 0 (black) 0x102CF2, # B6 E1 - increase background color subtraction by 1 (black) 0x102D19, # B6 F1 - decrease background color subtraction by 1 (black) ], "ForceField": [ 0x102D3A, # B0 E0 - set background color addition to 0 (white) 0x102D48, # B5 E1 - increase background color addition by 1 (white) 0x102D64, # B5 F1 - decrease background color addition by 1 (white) ], "Terra/Tritoch Lightning": [ 0x102E05, # B0 E0 - set background color addition to 0 (white) 0x102E09, # B5 81 - increase background color addition by 1 (red) 0x102E24, # B5 61 - increase background color addition by 1 (cyan) ], "S. Cross": [ 0x102EDA, # AF E0 - set background color subtraction to 0 (black) 0x102EDE, # B6 E2 - increase background color subtraction by 2 (black) 0x102FA8, # B6 F2 - decrease background color subtraction by 2 (black) 0x102FB1, # B0 E0 - set background color addition to 0 (white) 0x102FBE, # B5 E2 - increase background color addition by 2 (white) 0x102FD9, # B5 F2 - decrease background color addition by 2 (white) ], "Mind Blast": [ 0x102FED, # B0 E0 - set background color addition to 0 (white) 0x102FF1, # B5 81 - increase background color addition by 1 (red) 0x102FF7, # B5 91 - decrease background color addition by 1 (red) 0x102FF9, # B5 21 - increase background color addition by 1 (blue) 0x102FFF, # B5 31 - decrease background color addition by 1 (blue) 0x103001, # B5 C1 - increase background color addition by 1 (yellow) 0x103007, # B5 91 - decrease background color addition by 1 (red) 0x10300D, # B5 51 - decrease background color addition by 1 (green) 0x103015, # B5 E2 - increase background color addition by 2 (white) 0x10301F, # B5 F1 - decrease background color addition by 1 (white) ], "Flare Star": [ 0x1030F5, # B0 E0 - set background color addition to 0 (white) 0x103106, # B5 81 - increase background color addition by 1 (red) 0x10310D, # B5 E2 - increase background color addition by 2 (white) 0x103123, # B5 71 - decrease background color addition by 1 (cyan) 0x10312E, # B5 91 - decrease background color addition by 1 (red) ], "Quasar": [ 0x1031D2, # AF E0 - set background color subtraction to 0 (black) 0x1031D6, # B6 E1 - increase background color subtraction by 1 (black) 0x1031FA, # B6 F1 - decrease background color subtraction by 1 (black) ], "R.Polarity": [ 0x10328B, # B0 FF - set background color addition to 31 (white) 0x103292, # B5 F1 - decrease background color addition by 1 (white) ], "Rippler": [ 0x1033C6, # B0 FF - set background color addition to 31 (white) 0x1033CA, # B5 F1 - decrease background color addition by 1 (white) ], "Step Mine": [ 0x1034D9, # B0 FF - set background color addition to 31 (white) 0x1034E0, # B5 F4 - decrease background color addition by 4 (white) ], "L.5 Doom": [ 0x1035E6, # B0 FF - set background color addition to 31 (white) 0x1035F6, # B5 F4 - decrease background color addition by 4 (white) ], "Megazerk": [ 0x103757, # B0 80 - set background color addition to 0 (red) 0x103761, # B5 82 - increase background color addition by 2 (red) 0x10378F, # B5 92 - decrease background color addition by 2 (red) 0x103795, # B5 92 - decrease background color addition by 2 (red) 0x10379B, # B5 92 - decrease background color addition by 2 (red) 0x1037A1, # B5 92 - decrease background color addition by 2 (red) 0x1037A7, # B5 92 - decrease background color addition by 2 (red) 0x1037AD, # B5 92 - decrease background color addition by 2 (red) 0x1037B3, # B5 92 - decrease background color addition by 2 (red) 0x1037B9, # B5 92 - decrease background color addition by 2 (red) 0x1037C0, # B5 92 - decrease background color addition by 2 (red) ], "Schiller": [ 0x103819, # B0 FF - set background color addition to 31 (white) 0x10381D, # B5 F4 - decrease background color addition by 4 (white) ], "WallChange": [ 0x10399E, # B0 FF - set background color addition to 31 (white) 0x1039A3, # B5 F2 - decrease background color addition by 2 (white) 0x1039A9, # B5 F2 - decrease background color addition by 2 (white) 0x1039AF, # B5 F2 - decrease background color addition by 2 (white) 0x1039B5, # B5 F2 - decrease background color addition by 2 (white) 0x1039BB, # B5 F2 - decrease background color addition by 2 (white) 0x1039C1, # B5 F2 - decrease background color addition by 2 (white) 0x1039C7, # B5 F2 - decrease background color addition by 2 (white) 0x1039CD, # B5 F2 - decrease background color addition by 2 (white) 0x1039D4, # B5 F2 - decrease background color addition by 2 (white) ], "Ultima": [ 0x1056CB, # AF 60 - set background color subtraction to 0 (red) 0x1056CF, # B6 C2 - increase background color subtraction by 2 (blue) 0x1056ED, # B0 FF - set background color addition to 31 (white) 0x1056F5, # B5 F1 - decrease background color addition by 1 (white) ], "Bolt 3": [ # Also Giga Volt 0x10588E, # B0 FF - set background color addition to 31 (white) 0x105893, # B5 F4 - decrease background color addition by 4 (white) 0x105896, # B5 F4 - decrease background color addition by 4 (white) 0x105899, # B5 F4 - decrease background color addition by 4 (white) 0x10589C, # B5 F4 - decrease background color addition by 4 (white) 0x1058A1, # B5 F4 - decrease background color addition by 4 (white) 0x1058A6, # B5 F4 - decrease background color addition by 4 (white) 0x1058AB, # B5 F4 - decrease background color addition by 4 (white) 0x1058B0, # B5 F4 - decrease background color addition by 4 (white) ], "X-Zone": [ 0x105A5D, # B0 FF - set background color addition to 31 (white) 0x105A6A, # B5 F2 - decrease background color addition by 2 (white) 0x105A79, # B5 F2 - decrease background color addition by 2 (white) ], "Dispel": [ 0x105DC2, # B0 FF - set background color addition to 31 (white) 0x105DC9, # B5 F1 - decrease background color addition by 1 (white) 0x105DD2, # B5 F1 - decrease background color addition by 1 (white) 0x105DDB, # B5 F1 - decrease background color addition by 1 (white) 0x105DE4, # B5 F1 - decrease background color addition by 1 (white) 0x105DED, # B5 F1 - decrease background color addition by 1 (white) ], "Muddle": [ # Also L.3 Muddle, Confusion 0x1060EA, # B0 FF - set background color addition to 31 (white) 0x1060EE, # B5 F1 - decrease background color addition by 1 (white) ], "Shock": [ 0x1068BE, # B0 FF - set background color addition to 31 (white) 0x1068D0, # B5 F1 - decrease background color addition by 1 (white) ], "Bum Rush": [ 0x106C3E, # B0 E0 - set background color addition to 0 (white) 0x106C47, # B0 E0 - set background color addition to 0 (white) 0x106C53, # B0 E0 - set background color addition to 0 (white) 0x106C7E, # B0 FF - set background color addition to 31 (white) 0x106C87, # B0 E0 - set background color addition to 0 (white) 0x106C95, # B0 FF - set background color addition to 31 (white) 0x106C9E, # B0 E0 - set background color addition to 0 (white) ], "Stunner": [ 0x1071BA, # B0 20 - set background color addition to 0 (blue) 0x1071C1, # B5 24 - increase background color addition by 4 (blue) 0x1071CA, # B5 24 - increase background color addition by 4 (blue) 0x1071D5, # B5 24 - increase background color addition by 4 (blue) 0x1071DE, # B5 24 - increase background color addition by 4 (blue) 0x1071E9, # B5 24 - increase background color addition by 4 (blue) 0x1071F2, # B5 24 - increase background color addition by 4 (blue) 0x1071FD, # B5 24 - increase background color addition by 4 (blue) 0x107206, # B5 24 - increase background color addition by 4 (blue) 0x107211, # B5 24 - increase background color addition by 4 (blue) 0x10721A, # B5 24 - increase background color addition by 4 (blue) 0x10725A, # B5 32 - decrease background color addition by 2 (blue) ], "Quadra Slam": [ # Also Quadra Slice 0x1073DC, # B0 FF - set background color addition to 31 (white) 0x1073EE, # B5 F2 - decrease background color addition by 2 (white) 0x1073F3, # B5 F2 - decrease background color addition by 2 (white) 0x107402, # B0 5F - set background color addition to 31 (green) 0x107424, # B5 54 - decrease background color addition by 4 (green) 0x107429, # B5 54 - decrease background color addition by 4 (green) 0x107436, # B0 3F - set background color addition to 31 (blue) 0x107458, # B5 34 - decrease background color addition by 4 (blue) 0x10745D, # B5 34 - decrease background color addition by 4 (blue) 0x107490, # B0 9F - set background color addition to 31 (red) 0x1074B2, # B5 94 - decrease background color addition by 4 (red) 0x1074B7, # B5 94 - decrease background color addition by 4 (red) ], "Slash": [ 0x1074F4, # B0 FF - set background color addition to 31 (white) 0x1074FD, # B5 F2 - decrease background color addition by 2 (white) 0x107507, # B5 F2 - decrease background color addition by 2 (white) ], "Flash": [ 0x107850, # B0 FF - set background color addition to 31 (white) 0x10785C, # B5 F1 - decrease background color addition by 1 (white) ] }
battle_animation_flashes = {'Goner': [1048712, 1048716, 1048722, 1048728, 1048737, 1048739, 1048787, 1048799, 1048946], 'Final KEFKA Death': [1049146, 1049152, 1049160, 1049166], 'Atom Edge': [1049552, 1049565, 1049574, 1049675, 1049687], 'Boss Death': [1049718, 1049724, 1049732, 1049751], 'Transform into Magicite': [1052464, 1052479, 1052494], 'Purifier': [1053504, 1053512, 1053568, 1053578], 'Wall': [1054587, 1054591, 1054600, 1054609, 1054618, 1054627, 1054636, 1054645], 'Pearl': [1054990, 1054995, 1055006, 1055038], 'Ice 3': [1055096, 1055099, 1055102, 1055105, 1055108, 1055111, 1055114, 1055117, 1055120], 'Fire 3': [1055226, 1055260], 'Sleep': [1055267, 1055273, 1055283], '7-Flush': [1055555, 1055559, 1055565, 1055571, 1055577, 1055583, 1055589, 1055595], 'H-Bomb': [1055685, 1055689, 1055763], 'Revenger': [1055842, 1055846, 1055852, 1055858, 1055864, 1055870, 1055876, 1055878, 1055884], 'Phantasm': [1056253, 1056259, 1056263, 1056269, 1056277, 1056287, 1056295, 1056303, 1056315], 'TigerBreak': [1057805, 1057809, 1057814], 'Metamorph': [1058197, 1058201, 1058223], 'Cat Rain': [1058423, 1058427], 'Charm': [1058542, 1058555], 'Mirager': [1058705, 1058709], 'SabreSoul': [1058771, 1058778], 'Back Blade': [1059027, 1059039], 'RoyalShock': [1059175, 1059179, 1059187], 'Overcast': [1059898, 1059925, 1059981, 1059985], 'Disaster': [1060078, 1060082, 1060121], 'ForceField': [1060154, 1060168, 1060196], 'Terra/Tritoch Lightning': [1060357, 1060361, 1060388], 'S. Cross': [1060570, 1060574, 1060776, 1060785, 1060798, 1060825], 'Mind Blast': [1060845, 1060849, 1060855, 1060857, 1060863, 1060865, 1060871, 1060877, 1060885, 1060895], 'Flare Star': [1061109, 1061126, 1061133, 1061155, 1061166], 'Quasar': [1061330, 1061334, 1061370], 'R.Polarity': [1061515, 1061522], 'Rippler': [1061830, 1061834], 'Step Mine': [1062105, 1062112], 'L.5 Doom': [1062374, 1062390], 'Megazerk': [1062743, 1062753, 1062799, 1062805, 1062811, 1062817, 1062823, 1062829, 1062835, 1062841, 1062848], 'Schiller': [1062937, 1062941], 'WallChange': [1063326, 1063331, 1063337, 1063343, 1063349, 1063355, 1063361, 1063367, 1063373, 1063380], 'Ultima': [1070795, 1070799, 1070829, 1070837], 'Bolt 3': [1071246, 1071251, 1071254, 1071257, 1071260, 1071265, 1071270, 1071275, 1071280], 'X-Zone': [1071709, 1071722, 1071737], 'Dispel': [1072578, 1072585, 1072594, 1072603, 1072612, 1072621], 'Muddle': [1073386, 1073390], 'Shock': [1075390, 1075408], 'Bum Rush': [1076286, 1076295, 1076307, 1076350, 1076359, 1076373, 1076382], 'Stunner': [1077690, 1077697, 1077706, 1077717, 1077726, 1077737, 1077746, 1077757, 1077766, 1077777, 1077786, 1077850], 'Quadra Slam': [1078236, 1078254, 1078259, 1078274, 1078308, 1078313, 1078326, 1078360, 1078365, 1078416, 1078450, 1078455], 'Slash': [1078516, 1078525, 1078535], 'Flash': [1079376, 1079388]}
class Solution: def maxEnvelopes(self, envelopes: List[List[int]]) -> int: if not envelopes: return 0 pairs = sorted(envelopes, key=lambda x: (x[0], -x[1])) result = [] for pair in pairs: height = pair[1] if len(result) == 0 or height > result[-1]: result.append(height) else: index = bisect.bisect_left(result, height) result[index] = height return len(result)
class Solution: def max_envelopes(self, envelopes: List[List[int]]) -> int: if not envelopes: return 0 pairs = sorted(envelopes, key=lambda x: (x[0], -x[1])) result = [] for pair in pairs: height = pair[1] if len(result) == 0 or height > result[-1]: result.append(height) else: index = bisect.bisect_left(result, height) result[index] = height return len(result)
# -*- coding: utf-8 -*- # This file is made to configure every file number at one place # Choose the place you are training at # AWS : 0, Own PC : 1 PC = 1 path_list = ["/jet/prs/workspace/", "."] url = path_list[PC] clothes = ['shirt', 'jeans', 'blazer', 'chino-pants', 'jacket', 'coat', 'hoody', 'training-pants', 't-shirt', 'polo-shirt', 'knit', 'slacks', 'sweat-shirt'] schedule = ['party', 'trip', 'sport', 'work', 'speech', 'daily', 'school', 'date'] weather = ['snow', 'sunny', 'cloudy', 'rain']
pc = 1 path_list = ['/jet/prs/workspace/', '.'] url = path_list[PC] clothes = ['shirt', 'jeans', 'blazer', 'chino-pants', 'jacket', 'coat', 'hoody', 'training-pants', 't-shirt', 'polo-shirt', 'knit', 'slacks', 'sweat-shirt'] schedule = ['party', 'trip', 'sport', 'work', 'speech', 'daily', 'school', 'date'] weather = ['snow', 'sunny', 'cloudy', 'rain']
def test_rm_long_opt_help(pycred): pycred('rm --help') def test_rm_short_opt_help(pycred): pycred('rm -h') def test_rm_none_existing_store_gives_exit_code_2(pycred, workspace): with workspace(): pycred('rm non-existing-store user', expected_exit_code=2)
def test_rm_long_opt_help(pycred): pycred('rm --help') def test_rm_short_opt_help(pycred): pycred('rm -h') def test_rm_none_existing_store_gives_exit_code_2(pycred, workspace): with workspace(): pycred('rm non-existing-store user', expected_exit_code=2)
# Application definition INSTALLED_APPS = [ 'django.contrib.staticfiles', 'django.contrib.sessions', 'authenticate', ] ROOT_URLCONF = 'auth_service.urls' WSGI_APPLICATION = 'auth_service.wsgi.application' # Use a non database session engine SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_SECURE = False
installed_apps = ['django.contrib.staticfiles', 'django.contrib.sessions', 'authenticate'] root_urlconf = 'auth_service.urls' wsgi_application = 'auth_service.wsgi.application' session_engine = 'django.contrib.sessions.backends.signed_cookies' session_cookie_secure = False
s=[] for i in range(int(input())): s.append(input()) cnt=0 while s: flag=True for i in range(len(s)//2): if s[i]<s[-(i+1)]: print(s[0],end='') s.pop(0) flag=False break elif s[-(i+1)]<s[i]: print(s[-1],end='') s.pop() flag=False break if flag: print(s[-1],end='') s.pop() cnt+=1 if cnt%80==0: print()
s = [] for i in range(int(input())): s.append(input()) cnt = 0 while s: flag = True for i in range(len(s) // 2): if s[i] < s[-(i + 1)]: print(s[0], end='') s.pop(0) flag = False break elif s[-(i + 1)] < s[i]: print(s[-1], end='') s.pop() flag = False break if flag: print(s[-1], end='') s.pop() cnt += 1 if cnt % 80 == 0: print()
cars=100 cars_in_space=5 drivers=20 pasengers=70 car_not_driven=cars-drivers cars_driven=drivers carpool_capacity=cars_driven*space_in_a_car average_passengers_percar=passengers/cars_driven print("There are", cars,"cars availble") print("There are only",drivers,"drivers availble") print("There will be",car_not_driven,"empty cars today") print("There are",cars_in_space,"space availble in car") print("We can transport",carpool_capacity,"peopletoday.") print("We have", passengers,"to carpool today.") print("We need to put about", average_passengers_per_car,"in each car.")
cars = 100 cars_in_space = 5 drivers = 20 pasengers = 70 car_not_driven = cars - drivers cars_driven = drivers carpool_capacity = cars_driven * space_in_a_car average_passengers_percar = passengers / cars_driven print('There are', cars, 'cars availble') print('There are only', drivers, 'drivers availble') print('There will be', car_not_driven, 'empty cars today') print('There are', cars_in_space, 'space availble in car') print('We can transport', carpool_capacity, 'peopletoday.') print('We have', passengers, 'to carpool today.') print('We need to put about', average_passengers_per_car, 'in each car.')
# AUTOGENERATED! DO NOT EDIT! File to edit: dataset.ipynb (unless otherwise specified). __all__ = ['load_mp3', 'get_sample_label', 'preprocess_file', 'pad_by_zeros', 'split_file_by_window_size', 'wrapper_split_file_by_window_size', 'create_dataset_fixed_size', 'get_spectrogram', 'add_channel_dim'] # Cell def load_mp3(file): sample = tf.io.read_file(file) sample_audio = tfio.audio.decode_mp3(sample) return sample_audio # Cell def get_sample_label(file): sample = load_mp3(file) label = tf.argmax(tf.strings.split(file, '/')[1] == np.array(ebirds)) return sample, label # Cell def preprocess_file(sample_audio, label): # Only look at the first channel sample_audio = sample_audio[:,0] sample_audio_scaled = (sample_audio - tf.math.reduce_min(sample_audio))/(tf.math.reduce_max(sample_audio) - tf.math.reduce_min(sample_audio)) sample_audio_scaled = 2*(sample_audio_scaled - 0.5) return sample_audio_scaled, label # Cell def pad_by_zeros(sample, min_file_size, last_sample_size): padding_size = min_file_size - last_sample_size sample_padded = tf.pad(sample, paddings=[[tf.constant(0), padding_size]]) return sample_padded # Cell def split_file_by_window_size(sample, label): # number of subsamples given none overlapping window size. subsample_count = int(np.round(sample.shape[0]/min_file_size)) # ignore extremely long files for now subsample_limit = 75 if subsample_count <= subsample_limit: # if the last sample is at least half the window size, then pad it, if not, clip it. last_sample_size = sample.shape[0]%min_file_size if last_sample_size/min_file_size > 0.5: sample = pad_by_zeros(sample, min_file_size, last_sample_size) else: sample = sample[:subsample_count*min_file_size] sample = tf.reshape(sample, shape=[subsample_count, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, subsample_count-1]], constant_values=label.numpy()) else: sample = tf.reshape(sample[:subsample_limit*min_file_size], shape=[subsample_limit, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, 74]], constant_values=label.numpy()) return sample, label # Cell def wrapper_split_file_by_window_size(sample, label): sample, label = tf.py_function(split_file_by_window_size, inp=(sample, label), Tout=(sample.dtype, label.dtype)) return sample, label # Cell def create_dataset_fixed_size(ds): iterator = iter(ds) sample, label = iterator.next() samples_all = tf.unstack(sample) labels_all = tf.unstack(label) while True: try: sample, label = iterator.next() sample = tf.unstack(sample) label = tf.unstack(label) samples_all = tf.concat([samples_all, sample], axis=0) labels_all = tf.concat([labels_all, label], axis=0) except: break return samples_all, labels_all # Cell def get_spectrogram(sample, label): spectrogram = tfio.experimental.audio.spectrogram(sample, nfft=512, window=512, stride=256) return spectrogram, label # Cell def add_channel_dim(sample, label): sample = tf.expand_dims(sample, axis=-1) return sample, label
__all__ = ['load_mp3', 'get_sample_label', 'preprocess_file', 'pad_by_zeros', 'split_file_by_window_size', 'wrapper_split_file_by_window_size', 'create_dataset_fixed_size', 'get_spectrogram', 'add_channel_dim'] def load_mp3(file): sample = tf.io.read_file(file) sample_audio = tfio.audio.decode_mp3(sample) return sample_audio def get_sample_label(file): sample = load_mp3(file) label = tf.argmax(tf.strings.split(file, '/')[1] == np.array(ebirds)) return (sample, label) def preprocess_file(sample_audio, label): sample_audio = sample_audio[:, 0] sample_audio_scaled = (sample_audio - tf.math.reduce_min(sample_audio)) / (tf.math.reduce_max(sample_audio) - tf.math.reduce_min(sample_audio)) sample_audio_scaled = 2 * (sample_audio_scaled - 0.5) return (sample_audio_scaled, label) def pad_by_zeros(sample, min_file_size, last_sample_size): padding_size = min_file_size - last_sample_size sample_padded = tf.pad(sample, paddings=[[tf.constant(0), padding_size]]) return sample_padded def split_file_by_window_size(sample, label): subsample_count = int(np.round(sample.shape[0] / min_file_size)) subsample_limit = 75 if subsample_count <= subsample_limit: last_sample_size = sample.shape[0] % min_file_size if last_sample_size / min_file_size > 0.5: sample = pad_by_zeros(sample, min_file_size, last_sample_size) else: sample = sample[:subsample_count * min_file_size] sample = tf.reshape(sample, shape=[subsample_count, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, subsample_count - 1]], constant_values=label.numpy()) else: sample = tf.reshape(sample[:subsample_limit * min_file_size], shape=[subsample_limit, min_file_size]) label = tf.pad(tf.expand_dims(label, axis=0), paddings=[[0, 74]], constant_values=label.numpy()) return (sample, label) def wrapper_split_file_by_window_size(sample, label): (sample, label) = tf.py_function(split_file_by_window_size, inp=(sample, label), Tout=(sample.dtype, label.dtype)) return (sample, label) def create_dataset_fixed_size(ds): iterator = iter(ds) (sample, label) = iterator.next() samples_all = tf.unstack(sample) labels_all = tf.unstack(label) while True: try: (sample, label) = iterator.next() sample = tf.unstack(sample) label = tf.unstack(label) samples_all = tf.concat([samples_all, sample], axis=0) labels_all = tf.concat([labels_all, label], axis=0) except: break return (samples_all, labels_all) def get_spectrogram(sample, label): spectrogram = tfio.experimental.audio.spectrogram(sample, nfft=512, window=512, stride=256) return (spectrogram, label) def add_channel_dim(sample, label): sample = tf.expand_dims(sample, axis=-1) return (sample, label)
a = int(input()) b = int(input()) if a >=b*12: print("Buy it!") else: print("Try again")
a = int(input()) b = int(input()) if a >= b * 12: print('Buy it!') else: print('Try again')
# [weight, value] I = [[4, 8], [4, 7], [6, 14]] k = 8 def knapRecursive(I, k): return knapRecursiveAux(I, k, len(I) - 1) def knapRecursiveAux(I, k, hi): # final element if hi == 0: # too big for sack if I[hi][0] > k: return 0 # fits else: return I[hi][1] else: # too big for sack if I[hi][0] > k: return knapRecursiveAux(I, k, hi - 1) # fits else: # don't include it s1 = knapRecursiveAux(I, k, hi - 1) # include it s2 = I[hi][1] + knapRecursiveAux(I, k - I[hi][0], hi - 1) return max(s1, s2) print(knapRecursive(I, k))
i = [[4, 8], [4, 7], [6, 14]] k = 8 def knap_recursive(I, k): return knap_recursive_aux(I, k, len(I) - 1) def knap_recursive_aux(I, k, hi): if hi == 0: if I[hi][0] > k: return 0 else: return I[hi][1] elif I[hi][0] > k: return knap_recursive_aux(I, k, hi - 1) else: s1 = knap_recursive_aux(I, k, hi - 1) s2 = I[hi][1] + knap_recursive_aux(I, k - I[hi][0], hi - 1) return max(s1, s2) print(knap_recursive(I, k))
class Piece(object): def __init__(self, is_tall: bool = True, is_dark: bool = True, is_square: bool = True, is_solid: bool = True, string: str = None): if string: self.is_tall = (string[0] == "1") self.is_dark = (string[1] == "1") self.is_square = (string[2] == "1") self.is_solid = (string[3] == "1") else: self.is_tall = is_tall self.is_dark = is_dark self.is_square = is_square self.is_solid = is_solid def __str__(self): return "{0}{1}{2}{3}".format( '1' if self.is_tall else '0', '1' if self.is_dark else '0', '1' if self.is_square else '0', '1' if self.is_solid else '0' ) def __hash__(self): res = 0 res += 1 if self.is_tall else 0 res += 2 if self.is_dark else 0 res += 4 if self.is_square else 0 res += 8 if self.is_solid else 0 return res def __eq__(self, other_piece): if not isinstance(other_piece, type(self)): return False return self.__hash__() == other_piece.__hash__() def has_in_common_with(self, *other_pieces): all_pieces_are_as_tall = True all_pieces_are_as_dark = True all_pieces_are_as_square = True all_pieces_are_as_solid = True for p in other_pieces: if not(self.is_tall == p.is_tall): all_pieces_are_as_tall = False if not(self.is_dark == p.is_dark): all_pieces_are_as_dark = False if not(self.is_square == p.is_square): all_pieces_are_as_square = False if not(self.is_solid == p.is_solid): all_pieces_are_as_solid = False return (all_pieces_are_as_tall or all_pieces_are_as_dark or all_pieces_are_as_square or all_pieces_are_as_solid) if __name__ == "__main__": pass
class Piece(object): def __init__(self, is_tall: bool=True, is_dark: bool=True, is_square: bool=True, is_solid: bool=True, string: str=None): if string: self.is_tall = string[0] == '1' self.is_dark = string[1] == '1' self.is_square = string[2] == '1' self.is_solid = string[3] == '1' else: self.is_tall = is_tall self.is_dark = is_dark self.is_square = is_square self.is_solid = is_solid def __str__(self): return '{0}{1}{2}{3}'.format('1' if self.is_tall else '0', '1' if self.is_dark else '0', '1' if self.is_square else '0', '1' if self.is_solid else '0') def __hash__(self): res = 0 res += 1 if self.is_tall else 0 res += 2 if self.is_dark else 0 res += 4 if self.is_square else 0 res += 8 if self.is_solid else 0 return res def __eq__(self, other_piece): if not isinstance(other_piece, type(self)): return False return self.__hash__() == other_piece.__hash__() def has_in_common_with(self, *other_pieces): all_pieces_are_as_tall = True all_pieces_are_as_dark = True all_pieces_are_as_square = True all_pieces_are_as_solid = True for p in other_pieces: if not self.is_tall == p.is_tall: all_pieces_are_as_tall = False if not self.is_dark == p.is_dark: all_pieces_are_as_dark = False if not self.is_square == p.is_square: all_pieces_are_as_square = False if not self.is_solid == p.is_solid: all_pieces_are_as_solid = False return all_pieces_are_as_tall or all_pieces_are_as_dark or all_pieces_are_as_square or all_pieces_are_as_solid if __name__ == '__main__': pass
x = int(input('Podaj pierwsza liczbe calkowita: ')) y = int(input('Podaj druga liczbe calkowita: ')) z = int(input('Podaj trzecia liczbe calkowita: ')) print() if x > 10: print(x) if y > 10: print(y) if z > 10: print(z)
x = int(input('Podaj pierwsza liczbe calkowita: ')) y = int(input('Podaj druga liczbe calkowita: ')) z = int(input('Podaj trzecia liczbe calkowita: ')) print() if x > 10: print(x) if y > 10: print(y) if z > 10: print(z)
while True: try: dados = [] matriz = [] n = int(input()) for linha in range(0, n): for coluna in range(0, n): dados.append(0) matriz.append(dados[:]) dados.clear() # Numeros na diagonal for diagonal_principal in range(0, n): matriz[diagonal_principal][diagonal_principal] = 2 for diagonal_secundaria in range(0, n): matriz[diagonal_secundaria][n - 1 - diagonal_secundaria] = 3 # Matriz do numero 1 for linha in range(n // 3, n - n // 3): for coluna in range(n // 3, n - n // 3): matriz[linha][coluna] = 1 # Matriz do numero 4 matriz[n // 2][n // 2] = 4 # Print da Matriz completa for linha in range(0, len(matriz)): for coluna in range(0, len(matriz)): if coluna == 0: print(f"{matriz[linha][coluna]}", end="") else: print(f"{matriz[linha][coluna]}", end="") print() print() except EOFError: break
while True: try: dados = [] matriz = [] n = int(input()) for linha in range(0, n): for coluna in range(0, n): dados.append(0) matriz.append(dados[:]) dados.clear() for diagonal_principal in range(0, n): matriz[diagonal_principal][diagonal_principal] = 2 for diagonal_secundaria in range(0, n): matriz[diagonal_secundaria][n - 1 - diagonal_secundaria] = 3 for linha in range(n // 3, n - n // 3): for coluna in range(n // 3, n - n // 3): matriz[linha][coluna] = 1 matriz[n // 2][n // 2] = 4 for linha in range(0, len(matriz)): for coluna in range(0, len(matriz)): if coluna == 0: print(f'{matriz[linha][coluna]}', end='') else: print(f'{matriz[linha][coluna]}', end='') print() print() except EOFError: break
# query_strings.py ''' Since Sqlite queries are inserted as string in Python code, the queries can be stored here to save space in the modules where they are used. ''' delete_color_scheme = ''' DELETE FROM color_scheme WHERE color_scheme_id = ? ''' insert_color_scheme = ''' INSERT INTO color_scheme VALUES (null, ?, ?, ?, ?, 0, 0) ''' select_all_color_schemes = ''' SELECT bg, highlight_bg, head_bg, fg FROM color_scheme ''' select_all_color_schemes_plus = ''' SELECT bg, highlight_bg, head_bg, fg, built_in, color_scheme_id FROM color_scheme ''' select_color_scheme_current = ''' SELECT bg, highlight_bg, head_bg, fg FROM format WHERE format_id = 1 ''' select_current_database = ''' SELECT current_database FROM closing_state WHERE closing_state_id = 1 ''' select_font_scheme = ''' SELECT font_size, output_font, input_font FROM format WHERE format_id = 1 ''' select_opening_settings = ''' SELECT bg, highlight_bg, head_bg, fg, output_font, input_font, font_size, default_bg, default_highlight_bg, default_head_bg, default_fg, default_output_font, default_input_font, default_font_size FROM format WHERE format_id = 1 ''' update_color_scheme_null = ''' UPDATE format SET (bg, highlight_bg, head_bg, fg) = (null, null, null, null) WHERE format_id = 1 ''' update_current_database = ''' UPDATE closing_state SET current_database = ? WHERE closing_state_id = 1 ''' update_format_color_scheme = ''' UPDATE format SET (bg, highlight_bg, head_bg, fg) = (?, ?, ?, ?) WHERE format_id = 1 ''' update_format_fonts = ''' UPDATE format SET (font_size, output_font, input_font) = (?, ?, ?) WHERE format_id = 1 '''
""" Since Sqlite queries are inserted as string in Python code, the queries can be stored here to save space in the modules where they are used. """ delete_color_scheme = '\n DELETE FROM color_scheme \n WHERE color_scheme_id = ?\n' insert_color_scheme = '\n INSERT INTO color_scheme \n VALUES (null, ?, ?, ?, ?, 0, 0)\n' select_all_color_schemes = '\n SELECT bg, highlight_bg, head_bg, fg \n FROM color_scheme\n' select_all_color_schemes_plus = '\n SELECT bg, highlight_bg, head_bg, fg, built_in, color_scheme_id \n FROM color_scheme\n' select_color_scheme_current = '\n SELECT bg, highlight_bg, head_bg, fg \n FROM format \n WHERE format_id = 1\n' select_current_database = '\n SELECT current_database \n FROM closing_state \n WHERE closing_state_id = 1\n' select_font_scheme = '\n SELECT font_size, output_font, input_font\n FROM format\n WHERE format_id = 1\n' select_opening_settings = '\n SELECT \n bg,\n highlight_bg,\n head_bg, \n fg,\n output_font,\n input_font, \n font_size,\n default_bg,\n default_highlight_bg,\n default_head_bg, \n default_fg,\n default_output_font,\n default_input_font, \n default_font_size \n FROM format\n WHERE format_id = 1\n' update_color_scheme_null = '\n UPDATE format \n SET (bg, highlight_bg, head_bg, fg) = \n (null, null, null, null) \n WHERE format_id = 1\n' update_current_database = '\n UPDATE closing_state \n SET current_database = ? \n WHERE closing_state_id = 1\n' update_format_color_scheme = '\n UPDATE format \n SET (bg, highlight_bg, head_bg, fg) = (?, ?, ?, ?) \n WHERE format_id = 1 \n' update_format_fonts = '\n UPDATE format \n SET (font_size, output_font, input_font) = (?, ?, ?) \n WHERE format_id = 1\n'
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'gfx', 'type': '<(component)', 'dependencies': [ '<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/third_party/libpng/libpng.gyp:libpng', '<(DEPTH)/third_party/zlib/zlib.gyp:zlib', '<(DEPTH)/url/url.gyp:url_lib', ], # text_elider.h includes ICU headers. 'export_dependent_settings': [ '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', ], 'defines': [ 'GFX_IMPLEMENTATION', ], 'sources': [ 'android/device_display_info.cc', 'android/device_display_info.h', 'android/gfx_jni_registrar.cc', 'android/gfx_jni_registrar.h', 'android/java_bitmap.cc', 'android/java_bitmap.h', 'android/shared_device_display_info.cc', 'android/shared_device_display_info.h', 'animation/animation.cc', 'animation/animation.h', 'animation/animation_container.cc', 'animation/animation_container.h', 'animation/animation_container_element.h', 'animation/animation_container_observer.h', 'animation/animation_delegate.h', 'animation/linear_animation.cc', 'animation/linear_animation.h', 'animation/multi_animation.cc', 'animation/multi_animation.h', 'animation/slide_animation.cc', 'animation/slide_animation.h', 'animation/throb_animation.cc', 'animation/throb_animation.h', 'animation/tween.cc', 'animation/tween.h', 'blit.cc', 'blit.h', 'box_f.cc', 'box_f.h', 'break_list.h', 'canvas.cc', 'canvas.h', 'canvas_android.cc', 'canvas_paint_gtk.cc', 'canvas_paint_gtk.h', 'canvas_paint_mac.h', 'canvas_paint_mac.mm', 'canvas_paint_win.cc', 'canvas_paint_win.h', 'canvas_skia.cc', 'canvas_skia_paint.h', 'codec/jpeg_codec.cc', 'codec/jpeg_codec.h', 'codec/png_codec.cc', 'codec/png_codec.h', 'color_analysis.cc', 'color_analysis.h', 'color_profile.cc', 'color_profile.h', 'color_profile_mac.cc', 'color_profile_win.cc', 'color_utils.cc', 'color_utils.h', 'display.cc', 'display.h', 'display_observer.cc', 'display_observer.h', 'favicon_size.cc', 'favicon_size.h', 'frame_time.h', 'font.cc', 'font.h', 'font_fallback_win.cc', 'font_fallback_win.h', 'font_list.cc', 'font_list.h', 'font_render_params_android.cc', 'font_render_params_linux.cc', 'font_render_params_linux.h', 'font_smoothing_win.cc', 'font_smoothing_win.h', 'gfx_export.h', 'gfx_paths.cc', 'gfx_paths.h', 'gpu_memory_buffer.cc', 'gpu_memory_buffer.h', 'image/canvas_image_source.cc', 'image/canvas_image_source.h', 'image/image.cc', 'image/image.h', 'image/image_family.cc', 'image/image_family.h', 'image/image_ios.mm', 'image/image_mac.mm', 'image/image_png_rep.cc', 'image/image_png_rep.h', 'image/image_skia.cc', 'image/image_skia.h', 'image/image_skia_operations.cc', 'image/image_skia_operations.h', 'image/image_skia_rep.cc', 'image/image_skia_rep.h', 'image/image_skia_source.h', 'image/image_skia_util_ios.h', 'image/image_skia_util_ios.mm', 'image/image_skia_util_mac.h', 'image/image_skia_util_mac.mm', 'image/image_util.cc', 'image/image_util.h', 'image/image_util_ios.mm', 'insets.cc', 'insets.h', 'insets_base.h', 'insets_f.cc', 'insets_f.h', 'interpolated_transform.cc', 'interpolated_transform.h', 'mac/scoped_ns_disable_screen_updates.h', 'matrix3_f.cc', 'matrix3_f.h', 'native_widget_types.h', 'ozone/dri/dri_skbitmap.cc', 'ozone/dri/dri_skbitmap.h', 'ozone/dri/dri_surface.cc', 'ozone/dri/dri_surface.h', 'ozone/dri/dri_surface_factory.cc', 'ozone/dri/dri_surface_factory.h', 'ozone/dri/dri_wrapper.cc', 'ozone/dri/dri_wrapper.h', 'ozone/dri/hardware_display_controller.cc', 'ozone/dri/hardware_display_controller.h', 'ozone/impl/file_surface_factory.cc', 'ozone/impl/file_surface_factory.h', 'ozone/surface_factory_ozone.cc', 'ozone/surface_factory_ozone.h', 'pango_util.cc', 'pango_util.h', 'path.cc', 'path.h', 'path_aura.cc', 'path_gtk.cc', 'path_win.cc', 'path_win.h', 'path_x11.cc', 'path_x11.h', 'platform_font.h', 'platform_font_android.cc', 'platform_font_ios.h', 'platform_font_ios.mm', 'platform_font_mac.h', 'platform_font_mac.mm', 'platform_font_ozone.cc', 'platform_font_pango.cc', 'platform_font_pango.h', 'platform_font_win.cc', 'platform_font_win.h', 'point.cc', 'point.h', 'point3_f.cc', 'point3_f.h', 'point_base.h', 'point_conversions.cc', 'point_conversions.h', 'point_f.cc', 'point_f.h', 'quad_f.cc', 'quad_f.h', 'range/range.cc', 'range/range.h', 'range/range_mac.mm', 'range/range_win.cc', 'rect.cc', 'rect.h', 'rect_base.h', 'rect_base_impl.h', 'rect_conversions.cc', 'rect_conversions.h', 'rect_f.cc', 'rect_f.h', 'render_text.cc', 'render_text.h', 'render_text_mac.cc', 'render_text_mac.h', 'render_text_ozone.cc', 'render_text_pango.cc', 'render_text_pango.h', 'render_text_win.cc', 'render_text_win.h', 'safe_integer_conversions.h', 'scoped_canvas.h', 'scoped_cg_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.mm', 'scoped_ui_graphics_push_context_ios.h', 'scoped_ui_graphics_push_context_ios.mm', 'screen.cc', 'screen.h', 'screen_android.cc', 'screen_aura.cc', 'screen_gtk.cc', 'screen_ios.mm', 'screen_mac.mm', 'screen_win.cc', 'screen_win.h', 'scrollbar_size.cc', 'scrollbar_size.h', 'selection_model.cc', 'selection_model.h', 'sequential_id_generator.cc', 'sequential_id_generator.h', 'shadow_value.cc', 'shadow_value.h', 'size.cc', 'size.h', 'size_base.h', 'size_conversions.cc', 'size_conversions.h', 'size_f.cc', 'size_f.h', 'skbitmap_operations.cc', 'skbitmap_operations.h', 'skia_util.cc', 'skia_util.h', 'skia_utils_gtk.cc', 'skia_utils_gtk.h', 'switches.cc', 'switches.h', 'sys_color_change_listener.cc', 'sys_color_change_listener.h', 'text_constants.h', 'text_elider.cc', 'text_elider.h', 'text_utils.cc', 'text_utils.h', 'text_utils_android.cc', 'text_utils_ios.mm', 'text_utils_skia.cc', 'transform.cc', 'transform.h', 'transform_util.cc', 'transform_util.h', 'utf16_indexing.cc', 'utf16_indexing.h', 'vector2d.cc', 'vector2d.h', 'vector2d_conversions.cc', 'vector2d_conversions.h', 'vector2d_f.cc', 'vector2d_f.h', 'vector3d_f.cc', 'vector3d_f.h', 'win/dpi.cc', 'win/dpi.h', 'win/hwnd_util.cc', 'win/hwnd_util.h', 'win/scoped_set_map_mode.h', 'win/singleton_hwnd.cc', 'win/singleton_hwnd.h', 'win/window_impl.cc', 'win/window_impl.h', 'x/x11_atom_cache.cc', 'x/x11_atom_cache.h', 'x/x11_types.cc', 'x/x11_types.h', ], 'conditions': [ ['OS=="ios"', { # iOS only uses a subset of UI. 'sources/': [ ['exclude', '^codec/jpeg_codec\\.cc$'], ], }, { 'dependencies': [ '<(libjpeg_gyp_path):libjpeg', ], }], # TODO(asvitkine): Switch all platforms to use canvas_skia.cc. # http://crbug.com/105550 ['use_canvas_skia==1', { 'sources!': [ 'canvas_android.cc', ], }, { # use_canvas_skia!=1 'sources!': [ 'canvas_skia.cc', ], }], ['toolkit_uses_gtk == 1', { 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:gtk', ], 'sources': [ 'gtk_native_view_id_manager.cc', 'gtk_native_view_id_manager.h', 'gtk_preserve_window.cc', 'gtk_preserve_window.h', 'gdk_compat.h', 'gtk_compat.h', 'gtk_util.cc', 'gtk_util.h', 'image/cairo_cached_surface.cc', 'image/cairo_cached_surface.h', 'scoped_gobject.h', ], }], ['OS=="win"', { 'sources': [ 'gdi_util.cc', 'gdi_util.h', 'icon_util.cc', 'icon_util.h', ], # TODO(jschuh): C4267: http://crbug.com/167187 size_t -> int # C4324 is structure was padded due to __declspec(align()), which is # uninteresting. 'msvs_disabled_warnings': [ 4267, 4324 ], }], ['OS=="android"', { 'sources!': [ 'animation/throb_animation.cc', 'display_observer.cc', 'path.cc', 'selection_model.cc', ], 'dependencies': [ 'gfx_jni_headers', ], 'link_settings': { 'libraries': [ '-landroid', '-ljnigraphics', ], }, }], ['OS=="android" and android_webview_build==0', { 'dependencies': [ '<(DEPTH)/base/base.gyp:base_java', ], }], ['OS=="android" or OS=="ios"', { 'sources!': [ 'render_text.cc', 'render_text.h', 'text_utils_skia.cc', ], }], ['use_pango==1', { 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:pangocairo', ], }], ['ozone_platform_dri==1', { 'dependencies': [ '<(DEPTH)/build/linux/system.gyp:dridrm', ], }], ], 'target_conditions': [ # Need 'target_conditions' to override default filename_rules to include # the file on iOS. ['OS == "ios"', { 'sources/': [ ['include', '^scoped_cg_context_save_gstate_mac\\.h$'], ], }], ], } ], 'conditions': [ ['OS=="android"' , { 'targets': [ { 'target_name': 'gfx_jni_headers', 'type': 'none', 'direct_dependent_settings': { 'include_dirs': [ '<(SHARED_INTERMEDIATE_DIR)/ui/gfx', ], }, 'sources': [ '../android/java/src/org/chromium/ui/gfx/BitmapHelper.java', '../android/java/src/org/chromium/ui/gfx/DeviceDisplayInfo.java', ], 'variables': { 'jni_gen_package': 'ui/gfx', 'jni_generator_ptr_type': 'long', }, 'includes': [ '../../build/jni_generator.gypi' ], }, ], }], ], }
{'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'gfx', 'type': '<(component)', 'dependencies': ['<(DEPTH)/base/base.gyp:base', '<(DEPTH)/base/base.gyp:base_i18n', '<(DEPTH)/base/base.gyp:base_static', '<(DEPTH)/base/third_party/dynamic_annotations/dynamic_annotations.gyp:dynamic_annotations', '<(DEPTH)/net/net.gyp:net', '<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc', '<(DEPTH)/third_party/libpng/libpng.gyp:libpng', '<(DEPTH)/third_party/zlib/zlib.gyp:zlib', '<(DEPTH)/url/url.gyp:url_lib'], 'export_dependent_settings': ['<(DEPTH)/skia/skia.gyp:skia', '<(DEPTH)/third_party/icu/icu.gyp:icui18n', '<(DEPTH)/third_party/icu/icu.gyp:icuuc'], 'defines': ['GFX_IMPLEMENTATION'], 'sources': ['android/device_display_info.cc', 'android/device_display_info.h', 'android/gfx_jni_registrar.cc', 'android/gfx_jni_registrar.h', 'android/java_bitmap.cc', 'android/java_bitmap.h', 'android/shared_device_display_info.cc', 'android/shared_device_display_info.h', 'animation/animation.cc', 'animation/animation.h', 'animation/animation_container.cc', 'animation/animation_container.h', 'animation/animation_container_element.h', 'animation/animation_container_observer.h', 'animation/animation_delegate.h', 'animation/linear_animation.cc', 'animation/linear_animation.h', 'animation/multi_animation.cc', 'animation/multi_animation.h', 'animation/slide_animation.cc', 'animation/slide_animation.h', 'animation/throb_animation.cc', 'animation/throb_animation.h', 'animation/tween.cc', 'animation/tween.h', 'blit.cc', 'blit.h', 'box_f.cc', 'box_f.h', 'break_list.h', 'canvas.cc', 'canvas.h', 'canvas_android.cc', 'canvas_paint_gtk.cc', 'canvas_paint_gtk.h', 'canvas_paint_mac.h', 'canvas_paint_mac.mm', 'canvas_paint_win.cc', 'canvas_paint_win.h', 'canvas_skia.cc', 'canvas_skia_paint.h', 'codec/jpeg_codec.cc', 'codec/jpeg_codec.h', 'codec/png_codec.cc', 'codec/png_codec.h', 'color_analysis.cc', 'color_analysis.h', 'color_profile.cc', 'color_profile.h', 'color_profile_mac.cc', 'color_profile_win.cc', 'color_utils.cc', 'color_utils.h', 'display.cc', 'display.h', 'display_observer.cc', 'display_observer.h', 'favicon_size.cc', 'favicon_size.h', 'frame_time.h', 'font.cc', 'font.h', 'font_fallback_win.cc', 'font_fallback_win.h', 'font_list.cc', 'font_list.h', 'font_render_params_android.cc', 'font_render_params_linux.cc', 'font_render_params_linux.h', 'font_smoothing_win.cc', 'font_smoothing_win.h', 'gfx_export.h', 'gfx_paths.cc', 'gfx_paths.h', 'gpu_memory_buffer.cc', 'gpu_memory_buffer.h', 'image/canvas_image_source.cc', 'image/canvas_image_source.h', 'image/image.cc', 'image/image.h', 'image/image_family.cc', 'image/image_family.h', 'image/image_ios.mm', 'image/image_mac.mm', 'image/image_png_rep.cc', 'image/image_png_rep.h', 'image/image_skia.cc', 'image/image_skia.h', 'image/image_skia_operations.cc', 'image/image_skia_operations.h', 'image/image_skia_rep.cc', 'image/image_skia_rep.h', 'image/image_skia_source.h', 'image/image_skia_util_ios.h', 'image/image_skia_util_ios.mm', 'image/image_skia_util_mac.h', 'image/image_skia_util_mac.mm', 'image/image_util.cc', 'image/image_util.h', 'image/image_util_ios.mm', 'insets.cc', 'insets.h', 'insets_base.h', 'insets_f.cc', 'insets_f.h', 'interpolated_transform.cc', 'interpolated_transform.h', 'mac/scoped_ns_disable_screen_updates.h', 'matrix3_f.cc', 'matrix3_f.h', 'native_widget_types.h', 'ozone/dri/dri_skbitmap.cc', 'ozone/dri/dri_skbitmap.h', 'ozone/dri/dri_surface.cc', 'ozone/dri/dri_surface.h', 'ozone/dri/dri_surface_factory.cc', 'ozone/dri/dri_surface_factory.h', 'ozone/dri/dri_wrapper.cc', 'ozone/dri/dri_wrapper.h', 'ozone/dri/hardware_display_controller.cc', 'ozone/dri/hardware_display_controller.h', 'ozone/impl/file_surface_factory.cc', 'ozone/impl/file_surface_factory.h', 'ozone/surface_factory_ozone.cc', 'ozone/surface_factory_ozone.h', 'pango_util.cc', 'pango_util.h', 'path.cc', 'path.h', 'path_aura.cc', 'path_gtk.cc', 'path_win.cc', 'path_win.h', 'path_x11.cc', 'path_x11.h', 'platform_font.h', 'platform_font_android.cc', 'platform_font_ios.h', 'platform_font_ios.mm', 'platform_font_mac.h', 'platform_font_mac.mm', 'platform_font_ozone.cc', 'platform_font_pango.cc', 'platform_font_pango.h', 'platform_font_win.cc', 'platform_font_win.h', 'point.cc', 'point.h', 'point3_f.cc', 'point3_f.h', 'point_base.h', 'point_conversions.cc', 'point_conversions.h', 'point_f.cc', 'point_f.h', 'quad_f.cc', 'quad_f.h', 'range/range.cc', 'range/range.h', 'range/range_mac.mm', 'range/range_win.cc', 'rect.cc', 'rect.h', 'rect_base.h', 'rect_base_impl.h', 'rect_conversions.cc', 'rect_conversions.h', 'rect_f.cc', 'rect_f.h', 'render_text.cc', 'render_text.h', 'render_text_mac.cc', 'render_text_mac.h', 'render_text_ozone.cc', 'render_text_pango.cc', 'render_text_pango.h', 'render_text_win.cc', 'render_text_win.h', 'safe_integer_conversions.h', 'scoped_canvas.h', 'scoped_cg_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.h', 'scoped_ns_graphics_context_save_gstate_mac.mm', 'scoped_ui_graphics_push_context_ios.h', 'scoped_ui_graphics_push_context_ios.mm', 'screen.cc', 'screen.h', 'screen_android.cc', 'screen_aura.cc', 'screen_gtk.cc', 'screen_ios.mm', 'screen_mac.mm', 'screen_win.cc', 'screen_win.h', 'scrollbar_size.cc', 'scrollbar_size.h', 'selection_model.cc', 'selection_model.h', 'sequential_id_generator.cc', 'sequential_id_generator.h', 'shadow_value.cc', 'shadow_value.h', 'size.cc', 'size.h', 'size_base.h', 'size_conversions.cc', 'size_conversions.h', 'size_f.cc', 'size_f.h', 'skbitmap_operations.cc', 'skbitmap_operations.h', 'skia_util.cc', 'skia_util.h', 'skia_utils_gtk.cc', 'skia_utils_gtk.h', 'switches.cc', 'switches.h', 'sys_color_change_listener.cc', 'sys_color_change_listener.h', 'text_constants.h', 'text_elider.cc', 'text_elider.h', 'text_utils.cc', 'text_utils.h', 'text_utils_android.cc', 'text_utils_ios.mm', 'text_utils_skia.cc', 'transform.cc', 'transform.h', 'transform_util.cc', 'transform_util.h', 'utf16_indexing.cc', 'utf16_indexing.h', 'vector2d.cc', 'vector2d.h', 'vector2d_conversions.cc', 'vector2d_conversions.h', 'vector2d_f.cc', 'vector2d_f.h', 'vector3d_f.cc', 'vector3d_f.h', 'win/dpi.cc', 'win/dpi.h', 'win/hwnd_util.cc', 'win/hwnd_util.h', 'win/scoped_set_map_mode.h', 'win/singleton_hwnd.cc', 'win/singleton_hwnd.h', 'win/window_impl.cc', 'win/window_impl.h', 'x/x11_atom_cache.cc', 'x/x11_atom_cache.h', 'x/x11_types.cc', 'x/x11_types.h'], 'conditions': [['OS=="ios"', {'sources/': [['exclude', '^codec/jpeg_codec\\.cc$']]}, {'dependencies': ['<(libjpeg_gyp_path):libjpeg']}], ['use_canvas_skia==1', {'sources!': ['canvas_android.cc']}, {'sources!': ['canvas_skia.cc']}], ['toolkit_uses_gtk == 1', {'dependencies': ['<(DEPTH)/build/linux/system.gyp:gtk'], 'sources': ['gtk_native_view_id_manager.cc', 'gtk_native_view_id_manager.h', 'gtk_preserve_window.cc', 'gtk_preserve_window.h', 'gdk_compat.h', 'gtk_compat.h', 'gtk_util.cc', 'gtk_util.h', 'image/cairo_cached_surface.cc', 'image/cairo_cached_surface.h', 'scoped_gobject.h']}], ['OS=="win"', {'sources': ['gdi_util.cc', 'gdi_util.h', 'icon_util.cc', 'icon_util.h'], 'msvs_disabled_warnings': [4267, 4324]}], ['OS=="android"', {'sources!': ['animation/throb_animation.cc', 'display_observer.cc', 'path.cc', 'selection_model.cc'], 'dependencies': ['gfx_jni_headers'], 'link_settings': {'libraries': ['-landroid', '-ljnigraphics']}}], ['OS=="android" and android_webview_build==0', {'dependencies': ['<(DEPTH)/base/base.gyp:base_java']}], ['OS=="android" or OS=="ios"', {'sources!': ['render_text.cc', 'render_text.h', 'text_utils_skia.cc']}], ['use_pango==1', {'dependencies': ['<(DEPTH)/build/linux/system.gyp:pangocairo']}], ['ozone_platform_dri==1', {'dependencies': ['<(DEPTH)/build/linux/system.gyp:dridrm']}]], 'target_conditions': [['OS == "ios"', {'sources/': [['include', '^scoped_cg_context_save_gstate_mac\\.h$']]}]]}], 'conditions': [['OS=="android"', {'targets': [{'target_name': 'gfx_jni_headers', 'type': 'none', 'direct_dependent_settings': {'include_dirs': ['<(SHARED_INTERMEDIATE_DIR)/ui/gfx']}, 'sources': ['../android/java/src/org/chromium/ui/gfx/BitmapHelper.java', '../android/java/src/org/chromium/ui/gfx/DeviceDisplayInfo.java'], 'variables': {'jni_gen_package': 'ui/gfx', 'jni_generator_ptr_type': 'long'}, 'includes': ['../../build/jni_generator.gypi']}]}]]}
__all__ = ( 'LIST', 'GET', 'CREATE', 'UPDATE', 'REPLACE', 'DELETE', 'ALL', 'get_http_methods' ) LIST = 'list' GET = 'get' CREATE = 'create' REPLACE = 'replace' UPDATE = 'update' DELETE = 'delete' ALL = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE) _http_methods = { LIST: ('get',), GET: ('get',), CREATE: ('post',), REPLACE: ('put',), UPDATE: ('patch',), DELETE: ('delete',) } def get_http_methods(method): return _http_methods[method]
__all__ = ('LIST', 'GET', 'CREATE', 'UPDATE', 'REPLACE', 'DELETE', 'ALL', 'get_http_methods') list = 'list' get = 'get' create = 'create' replace = 'replace' update = 'update' delete = 'delete' all = (LIST, GET, CREATE, UPDATE, REPLACE, DELETE) _http_methods = {LIST: ('get',), GET: ('get',), CREATE: ('post',), REPLACE: ('put',), UPDATE: ('patch',), DELETE: ('delete',)} def get_http_methods(method): return _http_methods[method]
#!/usr/bin/env python3 if __name__ == '__main__': # Python can represent integers. Here are a couple of ways to create an integer variable. Notice the truncation, # rather than rounding, in the assignment of d. a = 5 b = int() c = int(4) d = int(3.84) print(a, b, c, d) # Integers have the usual math operations. Note that division will return a float, but others will preserve the # integer type. The type() function can tell you the type of a variable. You should try to avoid using this # function in your code. print('\ndivision') a = 10 b = 10 / 5 print(b, type(b)) # We can force integer division with //. Note that this will truncate results. print('\nInteger division') a = 10 b = 10 // 5 print(b, type(b)) a = 10 b = 10 // 3 print(b, type(b)) # We can also calculate the remainder n = 10 m = 3 div = n // m rem = n % m print('\n{0} = {1} * {2} + {3}'.format(n, div, m, rem))
if __name__ == '__main__': a = 5 b = int() c = int(4) d = int(3.84) print(a, b, c, d) print('\ndivision') a = 10 b = 10 / 5 print(b, type(b)) print('\nInteger division') a = 10 b = 10 // 5 print(b, type(b)) a = 10 b = 10 // 3 print(b, type(b)) n = 10 m = 3 div = n // m rem = n % m print('\n{0} = {1} * {2} + {3}'.format(n, div, m, rem))
def test(): obj = { 'xxx1': 1, 'xxx2': 2, 'xxx3': 4, 'xxx4': 4, 'foo': 123 } i = 0 while i < 1e7: obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 i += 1 test()
def test(): obj = {'xxx1': 1, 'xxx2': 2, 'xxx3': 4, 'xxx4': 4, 'foo': 123} i = 0 while i < 10000000.0: obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 obj['foo'] = 234 i += 1 test()
counter_name = 'I0_PIN' Size = wx.Size(1007, 726) logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log' average_count = 1 max_value = 11 min_value = 0 start_fraction = 0.401 reject_outliers = False outlier_cutoff = 2.5 show_statistics = True time_window = 172800
counter_name = 'I0_PIN' size = wx.Size(1007, 726) logfile = '/net/helix/data/anfinrud_1502/Logfiles/I0_PIN-2.log' average_count = 1 max_value = 11 min_value = 0 start_fraction = 0.401 reject_outliers = False outlier_cutoff = 2.5 show_statistics = True time_window = 172800
print("I will now count my chickens:") print ("Hens",25+30/6) print ("Roosters",100-25*3%4) print("How I will count the eggs:") print(3+2+1-5+4%2-1/4+6) print("Is it true that 3+2<5-7?") print(3+2<5-7) print("What is 3+2?", 3+2) print("What is 5-7?", 5-7) print("Oh,that's why it's false") print("How about some more.") print("Is it greater?",5>-2) print("Is it greater or equal?",5>=-2) print("Is it less or equal?",5<=-2)
print('I will now count my chickens:') print('Hens', 25 + 30 / 6) print('Roosters', 100 - 25 * 3 % 4) print('How I will count the eggs:') print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) print('Is it true that 3+2<5-7?') print(3 + 2 < 5 - 7) print('What is 3+2?', 3 + 2) print('What is 5-7?', 5 - 7) print("Oh,that's why it's false") print('How about some more.') print('Is it greater?', 5 > -2) print('Is it greater or equal?', 5 >= -2) print('Is it less or equal?', 5 <= -2)
def wordPower(word): num = dict(zip(string.ascii_lowercase, range(1,27))) return sum([num[ch] for ch in word])
def word_power(word): num = dict(zip(string.ascii_lowercase, range(1, 27))) return sum([num[ch] for ch in word])
s = input().strip() res = [c for c in set(s.lower()) if c.isalpha()] if len(res) == 26: print("pangram") else: print("not pangram")
s = input().strip() res = [c for c in set(s.lower()) if c.isalpha()] if len(res) == 26: print('pangram') else: print('not pangram')
x = input("Enter sentence: ") count={"Uppercase":0, "Lowercase":0} for i in x: if i.isupper(): count["Uppercase"]+=1 elif i.islower(): count["Lowercase"]+=1 else: pass print ("There is:", count["Uppercase"], "uppercases.") print ("There is:", count["Lowercase"], "lowercases.")
x = input('Enter sentence: ') count = {'Uppercase': 0, 'Lowercase': 0} for i in x: if i.isupper(): count['Uppercase'] += 1 elif i.islower(): count['Lowercase'] += 1 else: pass print('There is:', count['Uppercase'], 'uppercases.') print('There is:', count['Lowercase'], 'lowercases.')
file = open("13") sum = 0 for numbers in file: #print(numbers.rstrip()) numbers = int(numbers) sum += numbers; print(sum) sum = str(sum) print(sum[:10])
file = open('13') sum = 0 for numbers in file: numbers = int(numbers) sum += numbers print(sum) sum = str(sum) print(sum[:10])
variable1 = "variable original" def variable_global(): global variable1 variable1 = "variable global modificada" print(variable1) #variable original variable_global() print(variable1) #variable global modificada
variable1 = 'variable original' def variable_global(): global variable1 variable1 = 'variable global modificada' print(variable1) variable_global() print(variable1)
TIMEOUT=100 def GenerateWriteCommand(i2cAddress, ID, writeLocation, data): i = 0 TIMEOUT = 100 command = bytearray(len(data)+15) while (i < 4): command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 2 command[8] = writeLocation command[9] = len(data) command[(10 + len(data))] = 255 i = 0 while (i < len(data)): command[(10 + i)] = data[i] i += 1 i = 0 while (i < 4): command[(11 + i) + len(data)] = 254 i += 1 return command def GenerateReadCommand(i2cAddress, ID, readLocation, numToRead): command = bytearray(16) i = 0 TIMEOUT = 100 while (i < 4): command[i] = 0xFF i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 0x01 command[8] = readLocation command[9] = numToRead command[10] = 0xFF i = 0 while (i < 4): command[(11 + i)] = 0xFE i += 1 return command def GenerateToggleCommand(i2cAddress, ID, writeLocation, data): i = 0 command = bytearray(16 + 15) while (i < 4): command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 3 command[8] = data command[9] = 16 command[(10 + 16)] = 255 i = 0 while (i < 16): command[(10 + i)] = 7 i += 1 i = 0 while (i < 4): command[((11 + i) + 16)] = 254 i += 1 return command
timeout = 100 def generate_write_command(i2cAddress, ID, writeLocation, data): i = 0 timeout = 100 command = bytearray(len(data) + 15) while i < 4: command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 2 command[8] = writeLocation command[9] = len(data) command[10 + len(data)] = 255 i = 0 while i < len(data): command[10 + i] = data[i] i += 1 i = 0 while i < 4: command[11 + i + len(data)] = 254 i += 1 return command def generate_read_command(i2cAddress, ID, readLocation, numToRead): command = bytearray(16) i = 0 timeout = 100 while i < 4: command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 1 command[8] = readLocation command[9] = numToRead command[10] = 255 i = 0 while i < 4: command[11 + i] = 254 i += 1 return command def generate_toggle_command(i2cAddress, ID, writeLocation, data): i = 0 command = bytearray(16 + 15) while i < 4: command[i] = 255 i += 1 command[4] = i2cAddress command[5] = TIMEOUT command[6] = ID command[7] = 3 command[8] = data command[9] = 16 command[10 + 16] = 255 i = 0 while i < 16: command[10 + i] = 7 i += 1 i = 0 while i < 4: command[11 + i + 16] = 254 i += 1 return command
class AveragingBucketUpkeep: def __init__(self): self.numer = 0.0 self.denom = 0 def add_cost(self, cost): self.numer += cost self.denom += 1 return self.numer / self.denom def rem_cost(self, cost): self.numer -= cost self.denom -= 1 if self.denom == 0: return 0 return self.numer / self.denom
class Averagingbucketupkeep: def __init__(self): self.numer = 0.0 self.denom = 0 def add_cost(self, cost): self.numer += cost self.denom += 1 return self.numer / self.denom def rem_cost(self, cost): self.numer -= cost self.denom -= 1 if self.denom == 0: return 0 return self.numer / self.denom
sqlqueries = { 'WeatherForecast':"select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr, to_char(f.forecasted_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day, f.zipcode zip, min(f.temp_avg) low, max(f.temp_avg) high, max(f.wind_speed) wind, max(f.humidity) humidity from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(f.forecasted_timestamp, 'YY'), to_char(f.forecasted_timestamp, 'MON'), to_char(f.forecasted_timestamp, 'DD'), f.zipcode;", 'WeatherActDesc':"select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, o.weather_description descripion from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON'), to_char(o.observation_timestamp, 'DD'), o.zipcode, o.weather_description order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherActual':"select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, min(o.temp_avg) low, max(o.temp_avg) high, max(o.wind_speed) wind, max(o.humidity) humidity from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON') , to_char(o.observation_timestamp, 'DD') , o.zipcode order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherDescription':"select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr , to_char(f.forecasted_timestamp, 'MON') Fiscal_mth , concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day , f.zipcode zip , f.weather_description descripion from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(forecasted_timestamp, 'YY') , to_char(f.forecasted_timestamp, 'MON') , to_char(f.forecasted_timestamp, 'DD') , f.zipcode , f.weather_description;" }
sqlqueries = {'WeatherForecast': "select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr, to_char(f.forecasted_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day, f.zipcode zip, min(f.temp_avg) low, max(f.temp_avg) high, max(f.wind_speed) wind, max(f.humidity) humidity from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(f.forecasted_timestamp, 'YY'), to_char(f.forecasted_timestamp, 'MON'), to_char(f.forecasted_timestamp, 'DD'), f.zipcode;", 'WeatherActDesc': "select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, o.weather_description descripion from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON'), to_char(o.observation_timestamp, 'DD'), o.zipcode, o.weather_description order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherActual': "select concat ('FY', to_char(o.observation_timestamp, 'YY')) Fiscal_yr, to_char(o.observation_timestamp, 'MON') Fiscal_mth, concat ('Day_', to_char(o.observation_timestamp, 'DD')) Fiscal_day, o.zipcode zip, min(o.temp_avg) low, max(o.temp_avg) high, max(o.wind_speed) wind, max(o.humidity) humidity from observations o group by to_char(o.observation_timestamp, 'YY'), to_char(o.observation_timestamp, 'MON') , to_char(o.observation_timestamp, 'DD') , o.zipcode order by fiscal_yr, fiscal_mth, fiscal_day, zip;", 'WeatherDescription': "select concat ('FY', to_char(f.forecasted_timestamp, 'YY')) Fiscal_yr , to_char(f.forecasted_timestamp, 'MON') Fiscal_mth , concat ('Day_', to_char(f.forecasted_timestamp, 'DD')) Fiscal_day , f.zipcode zip , f.weather_description descripion from forecast f where to_char(forecast_timestamp, 'YYYY-MM-DD HH24') = (select max(to_char(forecast_timestamp, 'YYYY-MM-DD HH24')) from forecast) group by to_char(forecasted_timestamp, 'YY') , to_char(f.forecasted_timestamp, 'MON') , to_char(f.forecasted_timestamp, 'DD') , f.zipcode , f.weather_description;"}
mock_dbcli_config = { 'exports_from': { 'lpass': { 'pull_lastpass_from': "{{ lastpass_entry }}", }, 'lpass_user_and_pass_only': { 'pull_lastpass_username_password_from': "{{ lastpass_entry }}", }, 'my-json-script': { 'json_script': [ 'some-custom-json-script' ] }, 'invalid-method': { }, }, 'dbs': { 'baz': { 'exports_from': 'my-json-script', }, 'bing': { 'exports_from': 'invalid-method', }, 'bazzle': { 'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name' }, 'bazzle-bing': { 'exports_from': 'lpass', 'lastpass_entry': 'different lpass entry name' }, 'frazzle': { 'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name' }, 'frink': { 'exports_from': 'lpass_user_and_pass_only', 'lastpass_entry': 'lpass entry name', 'jinja_context_name': 'standard', 'exports': { 'some_additional': 'export', 'a_numbered_export': 123 }, }, 'gaggle': { 'jinja_context_name': [ 'env', 'base64', ], 'exports': { 'type': 'bigquery', 'protocol': 'bigquery', 'bq_account': 'bq_itest', 'bq_service_account_json': "{{ env('ITEST_BIGQUERY_SERVICE_ACCOUNT_JSON_BASE64') | b64decode }}", 'bq_default_project_id': 'bluelabs-tools-dev', 'bq_default_dataset_id': 'bq_itest', }, }, }, 'orgs': { 'myorg': { 'full_name': 'MyOrg', }, }, }
mock_dbcli_config = {'exports_from': {'lpass': {'pull_lastpass_from': '{{ lastpass_entry }}'}, 'lpass_user_and_pass_only': {'pull_lastpass_username_password_from': '{{ lastpass_entry }}'}, 'my-json-script': {'json_script': ['some-custom-json-script']}, 'invalid-method': {}}, 'dbs': {'baz': {'exports_from': 'my-json-script'}, 'bing': {'exports_from': 'invalid-method'}, 'bazzle': {'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name'}, 'bazzle-bing': {'exports_from': 'lpass', 'lastpass_entry': 'different lpass entry name'}, 'frazzle': {'exports_from': 'lpass', 'lastpass_entry': 'lpass entry name'}, 'frink': {'exports_from': 'lpass_user_and_pass_only', 'lastpass_entry': 'lpass entry name', 'jinja_context_name': 'standard', 'exports': {'some_additional': 'export', 'a_numbered_export': 123}}, 'gaggle': {'jinja_context_name': ['env', 'base64'], 'exports': {'type': 'bigquery', 'protocol': 'bigquery', 'bq_account': 'bq_itest', 'bq_service_account_json': "{{ env('ITEST_BIGQUERY_SERVICE_ACCOUNT_JSON_BASE64') | b64decode }}", 'bq_default_project_id': 'bluelabs-tools-dev', 'bq_default_dataset_id': 'bq_itest'}}}, 'orgs': {'myorg': {'full_name': 'MyOrg'}}}
with open('./8/input_a.txt', 'r') as f: input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f] num = sum([sum([1 if len(a) in {2,3,4,7} else 0 for a in o[1]]) for o in input ]) print(f'Part A: Number of 1,4,7 or 8s in output - {num}') def getoutput(i): nums = ['0','1','2','3','4','5','6','7','8','9'] nums[1] = [a for a in i[0] if len(a) == 2][0] nums[4] = [a for a in i[0] if len(a) == 4][0] nums[7] = [a for a in i[0] if len(a) == 3][0] nums[8] = [a for a in i[0] if len(a) == 7][0] nums[9] = [a for a in i[0] if len(a) == 6 and set(nums[4]).issubset(set(a))][0] nums[0] = [a for a in i[0] if len(a) == 6 and set(nums[1]).issubset(set(a)) and a not in nums][0] nums[6] = [a for a in i[0] if len(a) == 6 and a not in nums][0] nums[3] = [a for a in i[0] if len(a) == 5 and set(nums[1]).issubset(set(a))][0] nums[5] = [a for a in i[0] if len(a) == 5 and (set(nums[4]) - set(nums[1])).issubset(set(a)) and a not in nums][0] nums[2] = [a for a in i[0] if len(a) == 5 and a not in nums][0] return int(''.join([str(nums.index([n for n in nums if set(n) == set(a)][0])) for a in i[1]])) print(f'Part B: total output sum value - {sum([getoutput(a) for a in input])}')
with open('./8/input_a.txt', 'r') as f: input = [[a.strip().split(' | ')[0].split(' '), a.strip().split(' | ')[1].split(' ')] for a in f] num = sum([sum([1 if len(a) in {2, 3, 4, 7} else 0 for a in o[1]]) for o in input]) print(f'Part A: Number of 1,4,7 or 8s in output - {num}') def getoutput(i): nums = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'] nums[1] = [a for a in i[0] if len(a) == 2][0] nums[4] = [a for a in i[0] if len(a) == 4][0] nums[7] = [a for a in i[0] if len(a) == 3][0] nums[8] = [a for a in i[0] if len(a) == 7][0] nums[9] = [a for a in i[0] if len(a) == 6 and set(nums[4]).issubset(set(a))][0] nums[0] = [a for a in i[0] if len(a) == 6 and set(nums[1]).issubset(set(a)) and (a not in nums)][0] nums[6] = [a for a in i[0] if len(a) == 6 and a not in nums][0] nums[3] = [a for a in i[0] if len(a) == 5 and set(nums[1]).issubset(set(a))][0] nums[5] = [a for a in i[0] if len(a) == 5 and (set(nums[4]) - set(nums[1])).issubset(set(a)) and (a not in nums)][0] nums[2] = [a for a in i[0] if len(a) == 5 and a not in nums][0] return int(''.join([str(nums.index([n for n in nums if set(n) == set(a)][0])) for a in i[1]])) print(f'Part B: total output sum value - {sum([getoutput(a) for a in input])}')
class Node: def __init__(self, data): self.data = data self.next = None def sumLinkedListNodes(list1, list2): value1, value2 = "", "" head1, head2 = list1, list2 while head1: value1 += str(head1.data) head1 = head1.next while head2: value2 += str(head2.data) head2 = head2.next total = str(int(value1) + int(value2)) totalList = list(total) list3 = {"head": Node(int(totalList[0]))} current = list3["head"] for i in range(1, len(totalList)): current.next = Node(int(totalList[i])) current = current.next return list3 list1 = Node(5) list1.next = Node(6) list1.next.next = Node(3) list2 = Node(8) list2.next = Node(4) list2.next.next = Node(2) sumLinkedListNodes(list1, list2)
class Node: def __init__(self, data): self.data = data self.next = None def sum_linked_list_nodes(list1, list2): (value1, value2) = ('', '') (head1, head2) = (list1, list2) while head1: value1 += str(head1.data) head1 = head1.next while head2: value2 += str(head2.data) head2 = head2.next total = str(int(value1) + int(value2)) total_list = list(total) list3 = {'head': node(int(totalList[0]))} current = list3['head'] for i in range(1, len(totalList)): current.next = node(int(totalList[i])) current = current.next return list3 list1 = node(5) list1.next = node(6) list1.next.next = node(3) list2 = node(8) list2.next = node(4) list2.next.next = node(2) sum_linked_list_nodes(list1, list2)
class Stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 def isEmpty(self): if(self.top == -1): return True else: return False def isFull(self): if(self.top == self.max -1): return True else: return False def push(self, data): if(self.isFull()): print("Stack Overflow") return else: self.top += 1 self.array.append(data) def pop(self): if(self.isEmpty()): print("Stack Underflow") return else: self.top -= 1 return(self.array.pop()) class SpecialStack(Stack): def __init__(self): super().__init__() self.Min = Stack() def push(self, x): if(self.isEmpty): super().push(x) self.Min.push(x) else: super().push(x) y = self.Min.pop() self.Min.push(y) if(x <= y): self.Min.push(x) else: self.Min.push(y) def pop(self): x = super().pop() self.Min.pop() return x def getMin(self): x = self.Min.pop() self.Min.push(x) return x if __name__ == "__main__": s = SpecialStack() s.push(10) s.push(20) s.push(30) print(s.getMin()) s.push(5) print(s.getMin())
class Stack: def __init__(self): self.array = [] self.top = -1 self.max = 100 def is_empty(self): if self.top == -1: return True else: return False def is_full(self): if self.top == self.max - 1: return True else: return False def push(self, data): if self.isFull(): print('Stack Overflow') return else: self.top += 1 self.array.append(data) def pop(self): if self.isEmpty(): print('Stack Underflow') return else: self.top -= 1 return self.array.pop() class Specialstack(Stack): def __init__(self): super().__init__() self.Min = stack() def push(self, x): if self.isEmpty: super().push(x) self.Min.push(x) else: super().push(x) y = self.Min.pop() self.Min.push(y) if x <= y: self.Min.push(x) else: self.Min.push(y) def pop(self): x = super().pop() self.Min.pop() return x def get_min(self): x = self.Min.pop() self.Min.push(x) return x if __name__ == '__main__': s = special_stack() s.push(10) s.push(20) s.push(30) print(s.getMin()) s.push(5) print(s.getMin())
#---------------------------------------------------------------------- # Basis Set Exchange # Version v0.8.13 # https://www.basissetexchange.org #---------------------------------------------------------------------- # Basis set: STO-3G # Description: STO-3G Minimal Basis (3 functions/AO) # Role: orbital # Version: 1 (Data from Gaussian09) #---------------------------------------------------------------------- # BASIS "ao basis" PRINT # #BASIS SET: (3s) -> [1s] # H S # 0.3425250914E+01 0.1543289673E+00 # 0.6239137298E+00 0.5353281423E+00 # 0.1688554040E+00 0.4446345422E+00 # END A_LIST = [3.425250914 , 0.6239137298, 0.1688554040] D_LIST = [0.1543289673, 0.5353281423, 0.4446345422]
a_list = [3.425250914, 0.6239137298, 0.168855404] d_list = [0.1543289673, 0.5353281423, 0.4446345422]
{ "cells": [ { "cell_type": "code", "execution_count": null, "id": "001887f2", "metadata": {}, "outputs": [], "source": [ "# import os modules to create path across operating system to load csv file\n", "import os\n", "# module for reading csv files\n", "import csv" ] }, { "cell_type": "code", "execution_count": null, "id": "77c0f7d8", "metadata": {}, "outputs": [], "source": [ "# read csv data and load to budgetDB\n", "csvpath = os.path.join(\"Resources\",\"budget_data.csv\")" ] }, { "cell_type": "code", "execution_count": null, "id": "b2da0e1e", "metadata": {}, "outputs": [], "source": [ "# creat a txt file to hold the analysis\n", "outputfile = os.path.join(\"Analysis\",\"budget_analysis.txt\")" ] }, { "cell_type": "code", "execution_count": null, "id": "f3c0fd89", "metadata": {}, "outputs": [], "source": [ "# set var and initialize to zero\n", "totalMonths = 0 \n", "totalBudget = 0" ] }, { "cell_type": "code", "execution_count": null, "id": "4f807576", "metadata": {}, "outputs": [], "source": [ "# set list to store all of the monthly changes\n", "monthChange = [] \n", "months = []" ] }, { "cell_type": "code", "execution_count": null, "id": "ad264653", "metadata": {}, "outputs": [], "source": [ "# use csvreader object to import the csv library with csvreader object\n", "with open(csvpath, newline = \"\") as csvfile:\n", "# # create a csv reader object\n", " csvreader = csv.reader(csvfile, delimiter=\",\")\n", " \n", " # skip the first row since it has all of the column information\n", " #next(csvreader)\n", " \n", "#header: date, profit/losses\n", "print(csvreader)" ] }, { "cell_type": "code", "execution_count": null, "id": "27fc81c1", "metadata": {}, "outputs": [], "source": [ "for p in csvreader:\n", " print(\"date: \" + p[0])\n", " print(\"profit: \" + p[1])" ] }, { "cell_type": "code", "execution_count": null, "id": "83749f03", "metadata": {}, "outputs": [], "source": [ "# read the header row\n", "header = next(csvreader)\n", "print(f\"csv header:{header}\")" ] }, { "cell_type": "code", "execution_count": null, "id": "3b441a20", "metadata": {}, "outputs": [], "source": [ "# move to the next row (first row)\n", "firstRow = next(csvreader)\n", "totalMonths = (len(f\"[csvfile.index(months)][csvfile]\"))" ] }, { "cell_type": "code", "execution_count": null, "id": "a815e200", "metadata": {}, "outputs": [], "source": [ "output = (\n", " f\"Financial Anaylsis \\n\"\n", " f\"------------------------- \\n\"\n", " f\"Total Months: {totalMonths} \\n\")\n", "print(output)" ] }, { "cell_type": "code", "execution_count": null, "id": "6bf35c14", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 5 }
{'cells': [{'cell_type': 'code', 'execution_count': null, 'id': '001887f2', 'metadata': {}, 'outputs': [], 'source': ['# import os modules to create path across operating system to load csv file\n', 'import os\n', '# module for reading csv files\n', 'import csv']}, {'cell_type': 'code', 'execution_count': null, 'id': '77c0f7d8', 'metadata': {}, 'outputs': [], 'source': ['# read csv data and load to budgetDB\n', 'csvpath = os.path.join("Resources","budget_data.csv")']}, {'cell_type': 'code', 'execution_count': null, 'id': 'b2da0e1e', 'metadata': {}, 'outputs': [], 'source': ['# creat a txt file to hold the analysis\n', 'outputfile = os.path.join("Analysis","budget_analysis.txt")']}, {'cell_type': 'code', 'execution_count': null, 'id': 'f3c0fd89', 'metadata': {}, 'outputs': [], 'source': ['# set var and initialize to zero\n', 'totalMonths = 0 \n', 'totalBudget = 0']}, {'cell_type': 'code', 'execution_count': null, 'id': '4f807576', 'metadata': {}, 'outputs': [], 'source': ['# set list to store all of the monthly changes\n', 'monthChange = [] \n', 'months = []']}, {'cell_type': 'code', 'execution_count': null, 'id': 'ad264653', 'metadata': {}, 'outputs': [], 'source': ['# use csvreader object to import the csv library with csvreader object\n', 'with open(csvpath, newline = "") as csvfile:\n', '# # create a csv reader object\n', ' csvreader = csv.reader(csvfile, delimiter=",")\n', ' \n', ' # skip the first row since it has all of the column information\n', ' #next(csvreader)\n', ' \n', '#header: date, profit/losses\n', 'print(csvreader)']}, {'cell_type': 'code', 'execution_count': null, 'id': '27fc81c1', 'metadata': {}, 'outputs': [], 'source': ['for p in csvreader:\n', ' print("date: " + p[0])\n', ' print("profit: " + p[1])']}, {'cell_type': 'code', 'execution_count': null, 'id': '83749f03', 'metadata': {}, 'outputs': [], 'source': ['# read the header row\n', 'header = next(csvreader)\n', 'print(f"csv header:{header}")']}, {'cell_type': 'code', 'execution_count': null, 'id': '3b441a20', 'metadata': {}, 'outputs': [], 'source': ['# move to the next row (first row)\n', 'firstRow = next(csvreader)\n', 'totalMonths = (len(f"[csvfile.index(months)][csvfile]"))']}, {'cell_type': 'code', 'execution_count': null, 'id': 'a815e200', 'metadata': {}, 'outputs': [], 'source': ['output = (\n', ' f"Financial Anaylsis \\n"\n', ' f"------------------------- \\n"\n', ' f"Total Months: {totalMonths} \\n")\n', 'print(output)']}, {'cell_type': 'code', 'execution_count': null, 'id': '6bf35c14', 'metadata': {}, 'outputs': [], 'source': []}], 'metadata': {'kernelspec': {'display_name': 'Python 3', 'language': 'python', 'name': 'python3'}, 'language_info': {'codemirror_mode': {'name': 'ipython', 'version': 3}, 'file_extension': '.py', 'mimetype': 'text/x-python', 'name': 'python', 'nbconvert_exporter': 'python', 'pygments_lexer': 'ipython3', 'version': '3.8.8'}}, 'nbformat': 4, 'nbformat_minor': 5}
# https://www.beecrowd.com.br/judge/en/problems/view/1017 car_efficiency = 12 # Km/L time = int(input()) average_speed = int(input()) liters = (time * average_speed) / car_efficiency print(f"{liters:.3f}")
car_efficiency = 12 time = int(input()) average_speed = int(input()) liters = time * average_speed / car_efficiency print(f'{liters:.3f}')
preference_list_of_user=[] def give(def_list): Def=def_list global preference_list_of_user preference_list_of_user=Def return Def def give_to_model(): return preference_list_of_user
preference_list_of_user = [] def give(def_list): def = def_list global preference_list_of_user preference_list_of_user = Def return Def def give_to_model(): return preference_list_of_user
def is_leap(year): leap = False # Write your logic here # The year can be evenly divided by 4, is a leap year, unless: # The year can be evenly divided by 100, it is NOT a leap year, unless: # The year is also evenly divisible by 400. Then it is a leap year. leap = (year % 4 == 0 and (year % 400 == 0 or year % 100 != 0)) return leap year = int(input()) print(is_leap(year))
def is_leap(year): leap = False leap = year % 4 == 0 and (year % 400 == 0 or year % 100 != 0) return leap year = int(input()) print(is_leap(year))
# Set random number generator np.random.seed(2020) # Initialize step_end, n, t_range, v and i step_end = int(t_max / dt) n = 50 t_range = np.linspace(0, t_max, num=step_end) v_n = el * np.ones([n, step_end]) i = i_mean * (1 + 0.1 * (t_max / dt)**(0.5) * (2 * np.random.random([n, step_end]) - 1)) # Loop for step_end - 1 steps for step in range(1, step_end): # Compute v_n v_n[:, step] = v_n[:, step - 1] + (dt / tau) * (el - v_n[:, step - 1] + r * i[:, step]) # Plot figure with plt.xkcd(): plt.figure() plt.title('Multiple realizations of $V_m$') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') plt.plot(t_range, v_n.T, 'k', alpha=0.3) plt.show()
np.random.seed(2020) step_end = int(t_max / dt) n = 50 t_range = np.linspace(0, t_max, num=step_end) v_n = el * np.ones([n, step_end]) i = i_mean * (1 + 0.1 * (t_max / dt) ** 0.5 * (2 * np.random.random([n, step_end]) - 1)) for step in range(1, step_end): v_n[:, step] = v_n[:, step - 1] + dt / tau * (el - v_n[:, step - 1] + r * i[:, step]) with plt.xkcd(): plt.figure() plt.title('Multiple realizations of $V_m$') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') plt.plot(t_range, v_n.T, 'k', alpha=0.3) plt.show()
class PaginatorOptions: def __init__( self, page_number: int, page_size: int, sort_column: str = None, sort_descending: bool = None ): self.sort_column = sort_column self.sort_descending = sort_descending self.page_number = page_number self.page_size = page_size assert (page_number is not None and page_size) \ or (page_number is not None and not page_size), \ 'Specify both page_number and page_size' if not sort_column: self.sort_column = 'id' self.sort_descending = True __all__ = ['PaginatorOptions']
class Paginatoroptions: def __init__(self, page_number: int, page_size: int, sort_column: str=None, sort_descending: bool=None): self.sort_column = sort_column self.sort_descending = sort_descending self.page_number = page_number self.page_size = page_size assert page_number is not None and page_size or (page_number is not None and (not page_size)), 'Specify both page_number and page_size' if not sort_column: self.sort_column = 'id' self.sort_descending = True __all__ = ['PaginatorOptions']
property_setter = { "dt": "Property Setter", "filters": [ ["name", "in", [ 'Purchase Order-read_only_onload', 'Purchase Order-default_print_format', 'Purchase Invoice-naming_series-options', 'Purchase Invoice-naming_series-default', 'Delivery Note-naming_series-options', 'Delivery Note-naming_series-default', 'Sales Order-naming_series-options', 'Sales Order-naming_series-default', 'Purchase Receipt-naming_series-options', 'Purchase Receipt-naming_series-default', 'Production Order-naming_series-options', 'Production Order-naming_series-default', 'Stock Entry-naming_series-options', 'Stock Entry-naming_series-default', 'Purchase Order-naming_series-options', 'Purchase Order-naming_series-default', 'Sales Invoice-naming_series-options', 'Sales Invoice-naming_series-default', 'Purchase Invoice-read_only_onload', 'Stock Reconciliation-read_only_onload', 'Delivery Note-read_only_onload', 'Stock Entry-read_only_onload', 'Sales Invoice-po_no-read_only', 'Sales Invoice-read_only_onload', 'Purchase Receipt Item-read_only_onload', 'Custom Field-fieldname-width', 'Custom Field-dt-width', 'Sales Invoice Item-read_only_onload', 'Sales Invoice Item-warehouse-default', 'Sales Order-po_no-read_only', 'Sales Order-read_only_onload', 'Item-read_only_onload', 'User-read_only_onload', 'User-sort_field', 'Asset Maintenance Task-periodicity-options', 'Asset Maintenance Task-read_only_onload', 'Asset-read_only_onload', 'Sales Invoice Item-customer_item_code-print_hide', 'Sales Invoice Item-customer_item_code-hidden', 'Sales Order Item-read_only_onload', 'BOM-with_operations-default', 'BOM-read_only_onload', 'Stock Entry-default_print_format', 'Purchase Receipt-read_only_onload', 'Production Order-skip_transfer-default', 'Production Order-skip_transfer-read_only', 'Production Order-use_multi_level_bom-default', 'Production Order-use_multi_level_bom-read_only', 'Production Order-read_only_onload', 'Purchase Order Item-amount-precision', 'Purchase Order Item-read_only_onload', 'Purchase Order Item-rate-precision', 'Stock Entry-use_multi_level_bom-default', 'Stock Entry-use_multi_level_bom-read_only', 'Stock Entry-from_bom-read_only', 'Stock Entry-from_bom-default', 'Stock Entry Detail-barcode-read_only', 'Stock Entry Detail-read_only_onload', 'Stock Entry-to_warehouse-read_only', 'Stock Entry-from_warehouse-read_only', 'Stock Entry-remarks-reqd', 'Purchase Receipt-in_words-print_hide', 'Purchase Receipt-in_words-hidden', 'Purchase Invoice-in_words-print_hide', 'Purchase Invoice-in_words-hidden', 'Purchase Order-in_words-print_hide', 'Purchase Order-in_words-hidden', 'Supplier Quotation-in_words-print_hide', 'Supplier Quotation-in_words-hidden', 'Delivery Note-in_words-print_hide', 'Delivery Note-in_words-hidden', 'Sales Invoice-in_words-print_hide', 'Sales Invoice-in_words-hidden', 'Sales Order-in_words-print_hide', 'Sales Order-in_words-hidden', 'Quotation-in_words-print_hide', 'Quotation-in_words-hidden', 'Purchase Order-rounded_total-print_hide', 'Purchase Order-rounded_total-hidden', 'Purchase Order-base_rounded_total-print_hide', 'Purchase Order-base_rounded_total-hidden', 'Supplier Quotation-rounded_total-print_hide', 'Supplier Quotation-rounded_total-hidden', 'Supplier Quotation-base_rounded_total-print_hide', 'Supplier Quotation-base_rounded_total-hidden', 'Delivery Note-rounded_total-print_hide', 'Delivery Note-rounded_total-hidden', 'Delivery Note-base_rounded_total-print_hide', 'Delivery Note-base_rounded_total-hidden', 'Sales Invoice-rounded_total-print_hide', 'Sales Invoice-rounded_total-hidden', 'Sales Invoice-base_rounded_total-print_hide', 'Sales Invoice-base_rounded_total-hidden', 'Sales Order-rounded_total-print_hide', 'Sales Order-rounded_total-hidden', 'Sales Order-base_rounded_total-print_hide', 'Sales Order-base_rounded_total-hidden', 'Quotation-rounded_total-print_hide', 'Quotation-rounded_total-hidden', 'Quotation-base_rounded_total-print_hide', 'Quotation-base_rounded_total-hidden', 'Dropbox Settings-dropbox_setup_via_site_config-hidden', 'Dropbox Settings-read_only_onload', 'Dropbox Settings-dropbox_access_token-hidden', 'Activity Log-subject-width', 'Employee-employee_number-hidden', 'Employee-employee_number-reqd', 'Employee-naming_series-reqd', 'Employee-naming_series-hidden', 'Supplier-naming_series-hidden', 'Supplier-naming_series-reqd', 'Delivery Note-tax_id-print_hide', 'Delivery Note-tax_id-hidden', 'Sales Invoice-tax_id-print_hide', 'Sales Invoice-tax_id-hidden', 'Sales Order-tax_id-print_hide', 'Sales Order-tax_id-hidden', 'Customer-naming_series-hidden', 'Customer-naming_series-reqd', 'Stock Entry Detail-barcode-hidden', 'Stock Reconciliation Item-barcode-hidden', 'Item-barcode-hidden', 'Delivery Note Item-barcode-hidden', 'Sales Invoice Item-barcode-hidden', 'Purchase Receipt Item-barcode-hidden', 'Item-item_code-reqd', 'Item-item_code-hidden', 'Item-naming_series-hidden', 'Item-naming_series-reqd', 'Item-manufacturing-collapsible_depends_on', 'Purchase Invoice-payment_schedule-print_hide', 'Purchase Invoice-due_date-print_hide', 'Purchase Order-payment_schedule-print_hide', 'Purchase Order-due_date-print_hide', 'Sales Invoice-payment_schedule-print_hide', 'Sales Invoice-due_date-print_hide', 'Sales Order-payment_schedule-print_hide', 'Sales Order-due_date-print_hide', 'Journal Entry Account-sort_order', 'Journal Entry Account-account_currency-print_hide', 'Sales Invoice-taxes_and_charges-reqd', 'Sales Taxes and Charges-sort_order', 'Sales Invoice Item-customer_item_code-label', 'Sales Invoice-default_print_format', 'Purchase Taxes and Charges Template-sort_order', 'Serial No-company-in_standard_filter', 'Serial No-amc_expiry_date-in_standard_filter', 'Serial No-warranty_expiry_date-in_standard_filter', 'Serial No-maintenance_status-in_standard_filter', 'Serial No-customer_name-in_standard_filter', 'Serial No-customer_name-bold', 'Serial No-customer-in_standard_filter', 'Serial No-delivery_document_no-in_standard_filter', 'Serial No-delivery_document_type-in_standard_filter', 'Serial No-supplier_name-bold', 'Serial No-supplier_name-in_standard_filter', 'Serial No-supplier-in_standard_filter', 'Serial No-purchase_date-in_standard_filter', 'Serial No-description-in_standard_filter', 'Delivery Note-section_break1-hidden', 'Delivery Note-sales_team_section_break-hidden', 'Delivery Note-project-hidden', 'Delivery Note-taxes-hidden', 'Delivery Note-taxes_and_charges-hidden', 'Delivery Note-taxes_section-hidden', 'Delivery Note-posting_time-print_hide', 'Delivery Note-posting_time-description', 'Delivery Note Item-warehouse-default', 'Item-income_account-default', 'Item-income_account-depends_on', 'Purchase Receipt-remarks-reqd', 'Purchase Receipt-taxes-hidden', 'Purchase Receipt-taxes_and_charges-hidden', 'Purchase Receipt Item-base_rate-fieldtype', 'Purchase Receipt Item-amount-in_list_view', 'Purchase Receipt Item-rate-fieldtype', 'Purchase Receipt Item-base_price_list_rate-fieldtype', 'Purchase Receipt Item-price_list_rate-fieldtype', 'Purchase Receipt Item-qty-in_list_view', 'Stock Entry-title_field', 'Stock Entry-search_fields', 'Stock Entry-project-hidden', 'Stock Entry-supplier-in_list_view', 'Stock Entry-from_warehouse-in_list_view', 'Stock Entry-to_warehouse-in_list_view', 'Stock Entry-purpose-default', 'ToDo-sort_order', 'Currency Exchange-sort_order', 'Company-abbr-in_list_view', 'Stock Reconciliation-expense_account-in_standard_filter', 'Stock Reconciliation-expense_account-depends_on', 'Sales Order-taxes-hidden', 'Warehouse-sort_order', 'Address-fax-hidden', 'Address-fax-read_only', 'Address-phone-hidden', 'Address-email_id-hidden', 'Address-city-reqd', 'BOM Operation-sort_order', 'BOM Item-scrap-read_only', 'BOM-operations_section-read_only', 'BOM-operations-read_only', 'BOM-rm_cost_as_per-reqd', 'Journal Entry-pay_to_recd_from-allow_on_submit', 'Journal Entry-remark-in_global_search', 'Journal Entry-total_amount-bold', 'Journal Entry-total_amount-print_hide', 'Journal Entry-total_amount-in_list_view', 'Journal Entry-total_credit-print_hide', 'Journal Entry-total_debit-print_hide', 'Journal Entry-total_debit-in_list_view', 'Journal Entry-user_remark-print_hide', 'Stock Entry-to_warehouse-hidden', 'Purchase Order Item-rate-fieldtype', 'Journal Entry Account-exchange_rate-print_hide', 'Sales Invoice Item-item_code-label', 'BOM-rm_cost_as_per-options', 'Purchase Order Item-price_list_rate-fieldtype', 'Reconciliation-expense_account-read_only', 'Customer-tax_id-read_only', 'Purchase Order Item-amount-fieldtype', 'Stock Entry-project-hidden' ] ] ] }
property_setter = {'dt': 'Property Setter', 'filters': [['name', 'in', ['Purchase Order-read_only_onload', 'Purchase Order-default_print_format', 'Purchase Invoice-naming_series-options', 'Purchase Invoice-naming_series-default', 'Delivery Note-naming_series-options', 'Delivery Note-naming_series-default', 'Sales Order-naming_series-options', 'Sales Order-naming_series-default', 'Purchase Receipt-naming_series-options', 'Purchase Receipt-naming_series-default', 'Production Order-naming_series-options', 'Production Order-naming_series-default', 'Stock Entry-naming_series-options', 'Stock Entry-naming_series-default', 'Purchase Order-naming_series-options', 'Purchase Order-naming_series-default', 'Sales Invoice-naming_series-options', 'Sales Invoice-naming_series-default', 'Purchase Invoice-read_only_onload', 'Stock Reconciliation-read_only_onload', 'Delivery Note-read_only_onload', 'Stock Entry-read_only_onload', 'Sales Invoice-po_no-read_only', 'Sales Invoice-read_only_onload', 'Purchase Receipt Item-read_only_onload', 'Custom Field-fieldname-width', 'Custom Field-dt-width', 'Sales Invoice Item-read_only_onload', 'Sales Invoice Item-warehouse-default', 'Sales Order-po_no-read_only', 'Sales Order-read_only_onload', 'Item-read_only_onload', 'User-read_only_onload', 'User-sort_field', 'Asset Maintenance Task-periodicity-options', 'Asset Maintenance Task-read_only_onload', 'Asset-read_only_onload', 'Sales Invoice Item-customer_item_code-print_hide', 'Sales Invoice Item-customer_item_code-hidden', 'Sales Order Item-read_only_onload', 'BOM-with_operations-default', 'BOM-read_only_onload', 'Stock Entry-default_print_format', 'Purchase Receipt-read_only_onload', 'Production Order-skip_transfer-default', 'Production Order-skip_transfer-read_only', 'Production Order-use_multi_level_bom-default', 'Production Order-use_multi_level_bom-read_only', 'Production Order-read_only_onload', 'Purchase Order Item-amount-precision', 'Purchase Order Item-read_only_onload', 'Purchase Order Item-rate-precision', 'Stock Entry-use_multi_level_bom-default', 'Stock Entry-use_multi_level_bom-read_only', 'Stock Entry-from_bom-read_only', 'Stock Entry-from_bom-default', 'Stock Entry Detail-barcode-read_only', 'Stock Entry Detail-read_only_onload', 'Stock Entry-to_warehouse-read_only', 'Stock Entry-from_warehouse-read_only', 'Stock Entry-remarks-reqd', 'Purchase Receipt-in_words-print_hide', 'Purchase Receipt-in_words-hidden', 'Purchase Invoice-in_words-print_hide', 'Purchase Invoice-in_words-hidden', 'Purchase Order-in_words-print_hide', 'Purchase Order-in_words-hidden', 'Supplier Quotation-in_words-print_hide', 'Supplier Quotation-in_words-hidden', 'Delivery Note-in_words-print_hide', 'Delivery Note-in_words-hidden', 'Sales Invoice-in_words-print_hide', 'Sales Invoice-in_words-hidden', 'Sales Order-in_words-print_hide', 'Sales Order-in_words-hidden', 'Quotation-in_words-print_hide', 'Quotation-in_words-hidden', 'Purchase Order-rounded_total-print_hide', 'Purchase Order-rounded_total-hidden', 'Purchase Order-base_rounded_total-print_hide', 'Purchase Order-base_rounded_total-hidden', 'Supplier Quotation-rounded_total-print_hide', 'Supplier Quotation-rounded_total-hidden', 'Supplier Quotation-base_rounded_total-print_hide', 'Supplier Quotation-base_rounded_total-hidden', 'Delivery Note-rounded_total-print_hide', 'Delivery Note-rounded_total-hidden', 'Delivery Note-base_rounded_total-print_hide', 'Delivery Note-base_rounded_total-hidden', 'Sales Invoice-rounded_total-print_hide', 'Sales Invoice-rounded_total-hidden', 'Sales Invoice-base_rounded_total-print_hide', 'Sales Invoice-base_rounded_total-hidden', 'Sales Order-rounded_total-print_hide', 'Sales Order-rounded_total-hidden', 'Sales Order-base_rounded_total-print_hide', 'Sales Order-base_rounded_total-hidden', 'Quotation-rounded_total-print_hide', 'Quotation-rounded_total-hidden', 'Quotation-base_rounded_total-print_hide', 'Quotation-base_rounded_total-hidden', 'Dropbox Settings-dropbox_setup_via_site_config-hidden', 'Dropbox Settings-read_only_onload', 'Dropbox Settings-dropbox_access_token-hidden', 'Activity Log-subject-width', 'Employee-employee_number-hidden', 'Employee-employee_number-reqd', 'Employee-naming_series-reqd', 'Employee-naming_series-hidden', 'Supplier-naming_series-hidden', 'Supplier-naming_series-reqd', 'Delivery Note-tax_id-print_hide', 'Delivery Note-tax_id-hidden', 'Sales Invoice-tax_id-print_hide', 'Sales Invoice-tax_id-hidden', 'Sales Order-tax_id-print_hide', 'Sales Order-tax_id-hidden', 'Customer-naming_series-hidden', 'Customer-naming_series-reqd', 'Stock Entry Detail-barcode-hidden', 'Stock Reconciliation Item-barcode-hidden', 'Item-barcode-hidden', 'Delivery Note Item-barcode-hidden', 'Sales Invoice Item-barcode-hidden', 'Purchase Receipt Item-barcode-hidden', 'Item-item_code-reqd', 'Item-item_code-hidden', 'Item-naming_series-hidden', 'Item-naming_series-reqd', 'Item-manufacturing-collapsible_depends_on', 'Purchase Invoice-payment_schedule-print_hide', 'Purchase Invoice-due_date-print_hide', 'Purchase Order-payment_schedule-print_hide', 'Purchase Order-due_date-print_hide', 'Sales Invoice-payment_schedule-print_hide', 'Sales Invoice-due_date-print_hide', 'Sales Order-payment_schedule-print_hide', 'Sales Order-due_date-print_hide', 'Journal Entry Account-sort_order', 'Journal Entry Account-account_currency-print_hide', 'Sales Invoice-taxes_and_charges-reqd', 'Sales Taxes and Charges-sort_order', 'Sales Invoice Item-customer_item_code-label', 'Sales Invoice-default_print_format', 'Purchase Taxes and Charges Template-sort_order', 'Serial No-company-in_standard_filter', 'Serial No-amc_expiry_date-in_standard_filter', 'Serial No-warranty_expiry_date-in_standard_filter', 'Serial No-maintenance_status-in_standard_filter', 'Serial No-customer_name-in_standard_filter', 'Serial No-customer_name-bold', 'Serial No-customer-in_standard_filter', 'Serial No-delivery_document_no-in_standard_filter', 'Serial No-delivery_document_type-in_standard_filter', 'Serial No-supplier_name-bold', 'Serial No-supplier_name-in_standard_filter', 'Serial No-supplier-in_standard_filter', 'Serial No-purchase_date-in_standard_filter', 'Serial No-description-in_standard_filter', 'Delivery Note-section_break1-hidden', 'Delivery Note-sales_team_section_break-hidden', 'Delivery Note-project-hidden', 'Delivery Note-taxes-hidden', 'Delivery Note-taxes_and_charges-hidden', 'Delivery Note-taxes_section-hidden', 'Delivery Note-posting_time-print_hide', 'Delivery Note-posting_time-description', 'Delivery Note Item-warehouse-default', 'Item-income_account-default', 'Item-income_account-depends_on', 'Purchase Receipt-remarks-reqd', 'Purchase Receipt-taxes-hidden', 'Purchase Receipt-taxes_and_charges-hidden', 'Purchase Receipt Item-base_rate-fieldtype', 'Purchase Receipt Item-amount-in_list_view', 'Purchase Receipt Item-rate-fieldtype', 'Purchase Receipt Item-base_price_list_rate-fieldtype', 'Purchase Receipt Item-price_list_rate-fieldtype', 'Purchase Receipt Item-qty-in_list_view', 'Stock Entry-title_field', 'Stock Entry-search_fields', 'Stock Entry-project-hidden', 'Stock Entry-supplier-in_list_view', 'Stock Entry-from_warehouse-in_list_view', 'Stock Entry-to_warehouse-in_list_view', 'Stock Entry-purpose-default', 'ToDo-sort_order', 'Currency Exchange-sort_order', 'Company-abbr-in_list_view', 'Stock Reconciliation-expense_account-in_standard_filter', 'Stock Reconciliation-expense_account-depends_on', 'Sales Order-taxes-hidden', 'Warehouse-sort_order', 'Address-fax-hidden', 'Address-fax-read_only', 'Address-phone-hidden', 'Address-email_id-hidden', 'Address-city-reqd', 'BOM Operation-sort_order', 'BOM Item-scrap-read_only', 'BOM-operations_section-read_only', 'BOM-operations-read_only', 'BOM-rm_cost_as_per-reqd', 'Journal Entry-pay_to_recd_from-allow_on_submit', 'Journal Entry-remark-in_global_search', 'Journal Entry-total_amount-bold', 'Journal Entry-total_amount-print_hide', 'Journal Entry-total_amount-in_list_view', 'Journal Entry-total_credit-print_hide', 'Journal Entry-total_debit-print_hide', 'Journal Entry-total_debit-in_list_view', 'Journal Entry-user_remark-print_hide', 'Stock Entry-to_warehouse-hidden', 'Purchase Order Item-rate-fieldtype', 'Journal Entry Account-exchange_rate-print_hide', 'Sales Invoice Item-item_code-label', 'BOM-rm_cost_as_per-options', 'Purchase Order Item-price_list_rate-fieldtype', 'Reconciliation-expense_account-read_only', 'Customer-tax_id-read_only', 'Purchase Order Item-amount-fieldtype', 'Stock Entry-project-hidden']]]}
# We can transition on native options using this # //command_line_option:<option-name> syntax _BUILD_SETTING = "//command_line_option:test_arg" def _test_arg_transition_impl(settings, attr): _ignore = (settings, attr) return {_BUILD_SETTING: ["new arg"]} _test_arg_transition = transition( implementation = _test_arg_transition_impl, inputs = [], outputs = [_BUILD_SETTING], ) def _test_transition_rule_impl(ctx): # We need to copy the executable because starlark doesn't allow # providing an executable not created by the rule executable_src = ctx.executable.actual_test executable_dst = ctx.actions.declare_file(ctx.label.name) ctx.actions.run_shell( tools = [executable_src], outputs = [executable_dst], command = "cp %s %s" % (executable_src.path, executable_dst.path), ) runfiles = ctx.attr.actual_test[0][DefaultInfo].default_runfiles return [DefaultInfo(runfiles = runfiles, executable = executable_dst)] transition_rule_test = rule( implementation = _test_transition_rule_impl, attrs = { "actual_test": attr.label(cfg = _test_arg_transition, executable = True), "_allowlist_function_transition": attr.label( default = "@bazel_tools//tools/allowlists/function_transition_allowlist", ), }, test = True, ) def test_arg_cc_test(name, **kwargs): cc_test_name = name + "_native_test" transition_rule_test( name = name, actual_test = ":%s" % cc_test_name, ) native.cc_test(name = cc_test_name, **kwargs)
_build_setting = '//command_line_option:test_arg' def _test_arg_transition_impl(settings, attr): _ignore = (settings, attr) return {_BUILD_SETTING: ['new arg']} _test_arg_transition = transition(implementation=_test_arg_transition_impl, inputs=[], outputs=[_BUILD_SETTING]) def _test_transition_rule_impl(ctx): executable_src = ctx.executable.actual_test executable_dst = ctx.actions.declare_file(ctx.label.name) ctx.actions.run_shell(tools=[executable_src], outputs=[executable_dst], command='cp %s %s' % (executable_src.path, executable_dst.path)) runfiles = ctx.attr.actual_test[0][DefaultInfo].default_runfiles return [default_info(runfiles=runfiles, executable=executable_dst)] transition_rule_test = rule(implementation=_test_transition_rule_impl, attrs={'actual_test': attr.label(cfg=_test_arg_transition, executable=True), '_allowlist_function_transition': attr.label(default='@bazel_tools//tools/allowlists/function_transition_allowlist')}, test=True) def test_arg_cc_test(name, **kwargs): cc_test_name = name + '_native_test' transition_rule_test(name=name, actual_test=':%s' % cc_test_name) native.cc_test(name=cc_test_name, **kwargs)
balance = 700 papers=[100, 50, 10, 5,4,3,2,1] def withdraw(balance, request): if balance < request : print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print ('your balance >>', balance) orgnal_request = request while request > 0: for i in papers: while request >= i: print('give', i) request-=i balance -= orgnal_request return balance def withdraw1(balance, request): give = 0 if balance < request : print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print ('your balance >>', balance) balance -= request while request > 0: if request >= 100: give = 100 elif request >= 50: give = 50 elif request >= 10: give = 10 elif request >= 5: give = 5 else : give = request print('give',give) request -= give return balance balance = withdraw(balance, 777) balance = withdraw(balance, 276) balance = withdraw1(balance, 276) balance = withdraw(balance, 34) balance = withdraw1(balance, 5) balance = withdraw1(balance, 500)
balance = 700 papers = [100, 50, 10, 5, 4, 3, 2, 1] def withdraw(balance, request): if balance < request: print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print('your balance >>', balance) orgnal_request = request while request > 0: for i in papers: while request >= i: print('give', i) request -= i balance -= orgnal_request return balance def withdraw1(balance, request): give = 0 if balance < request: print('Sorry, you are try withdraw: {0}, but Your balance just : {1}'.format(request, balance)) else: print('your balance >>', balance) balance -= request while request > 0: if request >= 100: give = 100 elif request >= 50: give = 50 elif request >= 10: give = 10 elif request >= 5: give = 5 else: give = request print('give', give) request -= give return balance balance = withdraw(balance, 777) balance = withdraw(balance, 276) balance = withdraw1(balance, 276) balance = withdraw(balance, 34) balance = withdraw1(balance, 5) balance = withdraw1(balance, 500)
arr_1 = ["1","2","3","4","5","6","7"] arr_2 = [] for n in arr_1: arr_2.insert(0,n) print(arr_2)
arr_1 = ['1', '2', '3', '4', '5', '6', '7'] arr_2 = [] for n in arr_1: arr_2.insert(0, n) print(arr_2)
n=int(input("Nhap vao mot so:")) d=dict() for i in range(1, n+1): d[i]=i*i print(d)
n = int(input('Nhap vao mot so:')) d = dict() for i in range(1, n + 1): d[i] = i * i print(d)
#!/usr/bin/env python # Copyright 2008-2010 Isaac Gouy # Copyright (c) 2013, 2014, Regents of the University of California # Copyright (c) 2017, 2018, Oracle and/or its affiliates. # All rights reserved. # # Revised BSD license # # This is a specific instance of the Open Source Initiative (OSI) BSD license # template http://www.opensource.org/licenses/bsd-license.php # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # Neither the name of "The Computer Language Benchmarks Game" nor the name of # "The Computer Language Shootout Benchmarks" nor the name "nanobench" nor the # name "bencher" nor the names of its contributors may be used to endorse or # promote products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #runas solve() #unittest.skip recursive generator #pythran export solve() # 01/08/14 modified for benchmarking by Wei Zhang COINS = [1, 2, 5, 10, 20, 50, 100, 200] # test def _sum(iterable): sum = None for i in iterable: if sum is None: sum = i else: sum += i return sum def balance(pattern): return _sum(COINS[x]*pattern[x] for x in range(0, len(pattern))) def gen(pattern, coinnum, num): coin = COINS[coinnum] for p in range(0, num//coin + 1): newpat = pattern[:coinnum] + (p,) bal = balance(newpat) if bal > num: return elif bal == num: yield newpat elif coinnum < len(COINS)-1: for pat in gen(newpat, coinnum+1, num): yield pat def solve(total): ''' In England the currency is made up of pound, P, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, P1 (100p) and P2 (200p). It is possible to make P2 in the following way: 1 P1 + 1 50p + 2 20p + 1 5p + 1 2p + 3 1p How many different ways can P2 be made using any number of coins? ''' return _sum(1 for pat in gen((), 0, total)) def measure(num): result = solve(num) print('total number of different ways: ', result) def __benchmark__(num=200): measure(num)
coins = [1, 2, 5, 10, 20, 50, 100, 200] def _sum(iterable): sum = None for i in iterable: if sum is None: sum = i else: sum += i return sum def balance(pattern): return _sum((COINS[x] * pattern[x] for x in range(0, len(pattern)))) def gen(pattern, coinnum, num): coin = COINS[coinnum] for p in range(0, num // coin + 1): newpat = pattern[:coinnum] + (p,) bal = balance(newpat) if bal > num: return elif bal == num: yield newpat elif coinnum < len(COINS) - 1: for pat in gen(newpat, coinnum + 1, num): yield pat def solve(total): """ In England the currency is made up of pound, P, and pence, p, and there are eight coins in general circulation: 1p, 2p, 5p, 10p, 20p, 50p, P1 (100p) and P2 (200p). It is possible to make P2 in the following way: 1 P1 + 1 50p + 2 20p + 1 5p + 1 2p + 3 1p How many different ways can P2 be made using any number of coins? """ return _sum((1 for pat in gen((), 0, total))) def measure(num): result = solve(num) print('total number of different ways: ', result) def __benchmark__(num=200): measure(num)
# ---------------------------------------------------------------------------- # CLASSES: nightly # # Test Case: missingdata.py # # Tests: missing data # # Programmer: Brad Whitlock # Date: Thu Jan 19 09:49:15 PST 2012 # # Modifications: # # ---------------------------------------------------------------------------- def SetTheView(): v = GetView2D() v.viewportCoords = (0.02, 0.98, 0.25, 1) SetView2D(v) def test0(datapath): TestSection("Missing data") OpenDatabase(pjoin(datapath,"earth.nc")) AddPlot("Pseudocolor", "height") DrawPlots() SetTheView() Test("missingdata_0_00") ChangeActivePlotsVar("carbon_particulates") Test("missingdata_0_01") ChangeActivePlotsVar("seatemp") Test("missingdata_0_02") ChangeActivePlotsVar("population") Test("missingdata_0_03") # Pick on higher zone numbers to make sure pick works. PickByNode(domain=0, element=833621) TestText("missingdata_0_04", GetPickOutput()) DeleteAllPlots() def test1(datapath): TestSection("Expressions and missing data") OpenDatabase(pjoin(datapath,"earth.nc")) DefineScalarExpression("meaningless", "carbon_particulates + seatemp") AddPlot("Pseudocolor", "meaningless") DrawPlots() SetTheView() Test("missingdata_1_00") DeleteAllPlots() DefineVectorExpression("color", "color(red,green,blue)") AddPlot("Truecolor", "color") DrawPlots() ResetView() SetTheView() Test("missingdata_1_01") DefineVectorExpression("color2", "color(population*0.364,green,blue)") ChangeActivePlotsVar("color2") v1 = GetView2D() v1.viewportCoords = (0.02, 0.98, 0.02, 0.98) v1.windowCoords = (259.439, 513.299, 288.93, 540) #25.466) SetView2D(v1) Test("missingdata_1_02") def main(): datapath = data_path("netcdf_test_data") test0(datapath) test1(datapath) main() Exit()
def set_the_view(): v = get_view2_d() v.viewportCoords = (0.02, 0.98, 0.25, 1) set_view2_d(v) def test0(datapath): test_section('Missing data') open_database(pjoin(datapath, 'earth.nc')) add_plot('Pseudocolor', 'height') draw_plots() set_the_view() test('missingdata_0_00') change_active_plots_var('carbon_particulates') test('missingdata_0_01') change_active_plots_var('seatemp') test('missingdata_0_02') change_active_plots_var('population') test('missingdata_0_03') pick_by_node(domain=0, element=833621) test_text('missingdata_0_04', get_pick_output()) delete_all_plots() def test1(datapath): test_section('Expressions and missing data') open_database(pjoin(datapath, 'earth.nc')) define_scalar_expression('meaningless', 'carbon_particulates + seatemp') add_plot('Pseudocolor', 'meaningless') draw_plots() set_the_view() test('missingdata_1_00') delete_all_plots() define_vector_expression('color', 'color(red,green,blue)') add_plot('Truecolor', 'color') draw_plots() reset_view() set_the_view() test('missingdata_1_01') define_vector_expression('color2', 'color(population*0.364,green,blue)') change_active_plots_var('color2') v1 = get_view2_d() v1.viewportCoords = (0.02, 0.98, 0.02, 0.98) v1.windowCoords = (259.439, 513.299, 288.93, 540) set_view2_d(v1) test('missingdata_1_02') def main(): datapath = data_path('netcdf_test_data') test0(datapath) test1(datapath) main() exit()
class SerialNumber: def __init__(self, serialNumber): if not (len(serialNumber) == 6): raise ValueError('Serial Number must be 6 digits long') self._serialNumber = serialNumber def __str__(self): return 'S/N: {}'.format(self._serialNumber) def __repr__(self): return 'SerialNumber: {}'.format(self._serialNumber) def getSerialNumber(self): return self._serialNumber def containsVowel(self): VOWELS = ['a', 'e', 'i', 'o', 'u'] for character in self._serialNumber: if character in VOWELS: return True return False def lastDigitOdd(self): try: lastDigitValue = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 1 def lastDigitEven(self): try: lastDigitValue = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 0
class Serialnumber: def __init__(self, serialNumber): if not len(serialNumber) == 6: raise value_error('Serial Number must be 6 digits long') self._serialNumber = serialNumber def __str__(self): return 'S/N: {}'.format(self._serialNumber) def __repr__(self): return 'SerialNumber: {}'.format(self._serialNumber) def get_serial_number(self): return self._serialNumber def contains_vowel(self): vowels = ['a', 'e', 'i', 'o', 'u'] for character in self._serialNumber: if character in VOWELS: return True return False def last_digit_odd(self): try: last_digit_value = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 1 def last_digit_even(self): try: last_digit_value = int(self._serialNumber[-1]) except ValueError: return False return lastDigitValue % 2 == 0
# # BitBake Graphical GTK User Interface # # Copyright (C) 2012 Intel Corporation # # Authored by Shane Wang <[email protected]> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License version 2 as # published by the Free Software Foundation. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. class HobColors: WHITE = "#ffffff" PALE_GREEN = "#aaffaa" ORANGE = "#eb8e68" PALE_RED = "#ffaaaa" GRAY = "#aaaaaa" LIGHT_GRAY = "#dddddd" SLIGHT_DARK = "#5f5f5f" DARK = "#3c3b37" BLACK = "#000000" PALE_BLUE = "#53b8ff" DEEP_RED = "#aa3e3e" KHAKI = "#fff68f" OK = WHITE RUNNING = PALE_GREEN WARNING = ORANGE ERROR = PALE_RED
class Hobcolors: white = '#ffffff' pale_green = '#aaffaa' orange = '#eb8e68' pale_red = '#ffaaaa' gray = '#aaaaaa' light_gray = '#dddddd' slight_dark = '#5f5f5f' dark = '#3c3b37' black = '#000000' pale_blue = '#53b8ff' deep_red = '#aa3e3e' khaki = '#fff68f' ok = WHITE running = PALE_GREEN warning = ORANGE error = PALE_RED
'''input 4 8 3 4 5 6 7 8 3 8 2 3 4 7 8 2 9 100 2 3 4 5 6 7 8 9 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem B if __name__ == '__main__': a, b, k = list(map(int, input().split())) if (b - a + 1) <= 2 * k: for i in range(a, b + 1): print(i) else: for j in range(a, a + k): print(j) for j in range(b - k + 1, b + 1): print(j)
"""input 4 8 3 4 5 6 7 8 3 8 2 3 4 7 8 2 9 100 2 3 4 5 6 7 8 9 """ if __name__ == '__main__': (a, b, k) = list(map(int, input().split())) if b - a + 1 <= 2 * k: for i in range(a, b + 1): print(i) else: for j in range(a, a + k): print(j) for j in range(b - k + 1, b + 1): print(j)
class Authenticator(object): def authenticate(self, credentials): raise NotImplementedError()
class Authenticator(object): def authenticate(self, credentials): raise not_implemented_error()
class Node(): def __init__(self, id: int, value = None, right: 'Node' = None, left: 'Node' = None): self.id = id self.value = value self.right = right self.left = left self.parent: 'Node' = None def add(self, node: 'Node'): if not node: raise ValueError('node value invalid') if node.id == self.id: raise ValueError('The id sent is alredy on the tree') if node.id > self.id: if not self.right: node.parent = self self.right = node else: self.right.add(node) if node.id < self.id: if not self.left: node.parent = self self.left = node else: self.left.add(node) def get_size(self): size_l = self.left.get_size() if self.left else 0 size_r = self.right.get_size() if self.right else 0 return 1 + size_l + size_r def get_height(self): h_l = self.left.get_height() if self.left else 0 h_r = self.right.get_height() if self.right else 0 if h_r > h_l: return 1 + h_r return 1 + h_l def get_node(self, id: int): if self.id == id: return self if id > self.id: if self.right: return self.right.get_node(id) if id < self.id: if self.left: return self.left.get_node(id) return None def get_min_node(self): if not self.left: return self return self.left.get_min_node() def get_max_node(self): if not self.right: return self return self.right.get_max_node() def get_sorted_list(self, max_size: int=None, ascending: bool=True): if max_size == None: return self.__get_list(ascending) return self.__get_list_by_size(max_size, ascending) def __get_list(self, ascending: bool): list_e = self.left.__get_list(ascending) if self.left else [] list_d = self.right.__get_list(ascending) if self.right else [] if ascending: return list_e + [self.id] + list_d return list_d + [self.id] + list_e def __get_list_by_size(self, max_size: int, ascending: bool): if ascending: st = 'left' fi = 'right' else: st = 'right' fi = 'left' list_st = self[st].__get_list_by_size(max_size=max_size, ascending=ascending) if self[st] else [] if max_size <= len(list_st): return list_st elif max_size <= len(list_st) + 1: return list_st + [self.id] else: curr_size = len(list_st) + 1 list_fi = self[fi].__get_list_by_size(max_size=max_size-curr_size, ascending=ascending) if self[fi] else [] return list_st + [self.id] + list_fi def __getitem__(self, name): return getattr(self, name) def __setitem__(self, name, value): return setattr(self, name, value) def __str__(self): str_e = self.left.__str__() if self.left else None str_d = self.right.__str__() if self.right else None if not (str_e or str_d): return f'[({self.id})]' return f'[({self.id}) {str_e}, {str_d}]'
class Node: def __init__(self, id: int, value=None, right: 'Node'=None, left: 'Node'=None): self.id = id self.value = value self.right = right self.left = left self.parent: 'Node' = None def add(self, node: 'Node'): if not node: raise value_error('node value invalid') if node.id == self.id: raise value_error('The id sent is alredy on the tree') if node.id > self.id: if not self.right: node.parent = self self.right = node else: self.right.add(node) if node.id < self.id: if not self.left: node.parent = self self.left = node else: self.left.add(node) def get_size(self): size_l = self.left.get_size() if self.left else 0 size_r = self.right.get_size() if self.right else 0 return 1 + size_l + size_r def get_height(self): h_l = self.left.get_height() if self.left else 0 h_r = self.right.get_height() if self.right else 0 if h_r > h_l: return 1 + h_r return 1 + h_l def get_node(self, id: int): if self.id == id: return self if id > self.id: if self.right: return self.right.get_node(id) if id < self.id: if self.left: return self.left.get_node(id) return None def get_min_node(self): if not self.left: return self return self.left.get_min_node() def get_max_node(self): if not self.right: return self return self.right.get_max_node() def get_sorted_list(self, max_size: int=None, ascending: bool=True): if max_size == None: return self.__get_list(ascending) return self.__get_list_by_size(max_size, ascending) def __get_list(self, ascending: bool): list_e = self.left.__get_list(ascending) if self.left else [] list_d = self.right.__get_list(ascending) if self.right else [] if ascending: return list_e + [self.id] + list_d return list_d + [self.id] + list_e def __get_list_by_size(self, max_size: int, ascending: bool): if ascending: st = 'left' fi = 'right' else: st = 'right' fi = 'left' list_st = self[st].__get_list_by_size(max_size=max_size, ascending=ascending) if self[st] else [] if max_size <= len(list_st): return list_st elif max_size <= len(list_st) + 1: return list_st + [self.id] else: curr_size = len(list_st) + 1 list_fi = self[fi].__get_list_by_size(max_size=max_size - curr_size, ascending=ascending) if self[fi] else [] return list_st + [self.id] + list_fi def __getitem__(self, name): return getattr(self, name) def __setitem__(self, name, value): return setattr(self, name, value) def __str__(self): str_e = self.left.__str__() if self.left else None str_d = self.right.__str__() if self.right else None if not (str_e or str_d): return f'[({self.id})]' return f'[({self.id}) {str_e}, {str_d}]'
# -*- coding: utf-8 -*- __author__ = 'lundberg' class EduIDGroupDBError(Exception): pass class VersionMismatch(EduIDGroupDBError): pass class MultipleReturnedError(EduIDGroupDBError): pass class MultipleUsersReturned(MultipleReturnedError): pass class MultipleGroupsReturned(MultipleReturnedError): pass
__author__ = 'lundberg' class Eduidgroupdberror(Exception): pass class Versionmismatch(EduIDGroupDBError): pass class Multiplereturnederror(EduIDGroupDBError): pass class Multipleusersreturned(MultipleReturnedError): pass class Multiplegroupsreturned(MultipleReturnedError): pass
string_input = "amazing" vowels = "aeiou" answer = [char for char in string_input if char not in vowels] print(answer)
string_input = 'amazing' vowels = 'aeiou' answer = [char for char in string_input if char not in vowels] print(answer)
class Solution(object): def deleteDuplicates(self, head): initial = head while head: if head.next and head.val == head.next.val: head.next = head.next.next else: head = head.next head = initial return head
class Solution(object): def delete_duplicates(self, head): initial = head while head: if head.next and head.val == head.next.val: head.next = head.next.next else: head = head.next head = initial return head
# set random number generator np.random.seed(2020) # initialize step_end and v step_end = int(t_max / dt) v = el t = 0 with plt.xkcd(): # initialize the figure plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel(r'$V_m$ (V)') # loop for step_end steps for step in range(step_end): t = step * dt plt.plot(t, v, 'k.') i = i_mean * (1 + 0.1 * (t_max / dt)**(0.5) * (2 * np.random.random() - 1)) v = v + (dt / tau) * (el - v + r * i) plt.show()
np.random.seed(2020) step_end = int(t_max / dt) v = el t = 0 with plt.xkcd(): plt.figure() plt.title('$V_m$ with random I(t)') plt.xlabel('time (s)') plt.ylabel('$V_m$ (V)') for step in range(step_end): t = step * dt plt.plot(t, v, 'k.') i = i_mean * (1 + 0.1 * (t_max / dt) ** 0.5 * (2 * np.random.random() - 1)) v = v + dt / tau * (el - v + r * i) plt.show()
#author SANKALP SAXENA def arrays(arr): arr.reverse() l = numpy.array(arr, float) return l
def arrays(arr): arr.reverse() l = numpy.array(arr, float) return l
def get_ts_struct(ts): y=ts&0x3f ts=ts>>6 m=ts&0xf ts=ts>>4 d=ts&0x1f ts=ts>>5 hh=ts&0x1f ts=ts>>5 mm=ts&0x3f ts=ts>>6 ss=ts&0x3f ts=ts>>6 wd=ts&0x8 ts=ts>>3 yd=ts&0x1ff ts=ts>>9 ms=ts&0x3ff ts=ts>>10 pid=ts&0x3ff return y,m,d,hh,mm,ss,wd,yd,ms,pid
def get_ts_struct(ts): y = ts & 63 ts = ts >> 6 m = ts & 15 ts = ts >> 4 d = ts & 31 ts = ts >> 5 hh = ts & 31 ts = ts >> 5 mm = ts & 63 ts = ts >> 6 ss = ts & 63 ts = ts >> 6 wd = ts & 8 ts = ts >> 3 yd = ts & 511 ts = ts >> 9 ms = ts & 1023 ts = ts >> 10 pid = ts & 1023 return (y, m, d, hh, mm, ss, wd, yd, ms, pid)
class DispositivoEntrada: def __init__(self, marca, tipo_entrada): self._marca = marca self.tipo_entrada = tipo_entrada
class Dispositivoentrada: def __init__(self, marca, tipo_entrada): self._marca = marca self.tipo_entrada = tipo_entrada
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/) # # 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. LIMIT_EXCEEDED_ERROR_MASSAGE = 'Instance limit exceeded. A new one will be launched as soon as free space will be available.' LIMIT_EXCEEDED_EXIT_CODE = 6 class AbstractInstanceProvider(object): def run_instance(self, is_spot, bid_price, ins_type, ins_hdd, ins_img, ins_key, run_id, kms_encyr_key_id, num_rep, time_rep, kube_ip, kubeadm_token): pass def find_and_tag_instance(self, old_id, new_id): pass def verify_run_id(self, run_id): pass def check_instance(self, ins_id, run_id, num_rep, time_rep): pass def get_instance_names(self, ins_id): pass def find_instance(self, run_id): pass def terminate_instance(self, ins_id): pass def terminate_instance_by_ip(self, node_internal_ip, node_name): pass def find_nodes_with_run_id(self, run_id): instance = self.find_instance(run_id) return [instance] if instance is not None else []
limit_exceeded_error_massage = 'Instance limit exceeded. A new one will be launched as soon as free space will be available.' limit_exceeded_exit_code = 6 class Abstractinstanceprovider(object): def run_instance(self, is_spot, bid_price, ins_type, ins_hdd, ins_img, ins_key, run_id, kms_encyr_key_id, num_rep, time_rep, kube_ip, kubeadm_token): pass def find_and_tag_instance(self, old_id, new_id): pass def verify_run_id(self, run_id): pass def check_instance(self, ins_id, run_id, num_rep, time_rep): pass def get_instance_names(self, ins_id): pass def find_instance(self, run_id): pass def terminate_instance(self, ins_id): pass def terminate_instance_by_ip(self, node_internal_ip, node_name): pass def find_nodes_with_run_id(self, run_id): instance = self.find_instance(run_id) return [instance] if instance is not None else []
c = float(input("Enter Amount Between 0-99 :")) print(c // 20, "Twenties") c = c % 20 print(c // 10, "Tens") c = c % 10 print(c // 5, "Fives") c = c % 5 print(c // 1, "Ones") c = c % 1 print(c // 0.25, "Quarters") c = c % 0.25 print(c // 0.1, "Dimes") c = c % 0.1 print(c // 0.05, "Nickles") c = c % 0.05 print(c // 0.01, "Pennies")
c = float(input('Enter Amount Between 0-99 :')) print(c // 20, 'Twenties') c = c % 20 print(c // 10, 'Tens') c = c % 10 print(c // 5, 'Fives') c = c % 5 print(c // 1, 'Ones') c = c % 1 print(c // 0.25, 'Quarters') c = c % 0.25 print(c // 0.1, 'Dimes') c = c % 0.1 print(c // 0.05, 'Nickles') c = c % 0.05 print(c // 0.01, 'Pennies')
class Cita: def __init__(self,id,solicitante,fecha,hora,motivo,estado,doctor): self.id = id self.solicitante = solicitante self.fecha = fecha self.hora = hora self.motivo = motivo self.estado = estado self.doctor = doctor def getId(self): return self.id def getSolicitante(self): return self.solicitante def getFecha(self): return self.fecha def getHora(self): return self.hora def getMotivo(self): return self.motivo def getEstado(self): return self.estado def getDoctor(self): return self.doctor def setSolicitante(self,solicitante): self.solicitante = solicitante def setFecha(self,fecha): self.fecha = fecha def setHora(self,hora): self.hora = hora def setMotivo(self,motivo): self.motivo = motivo def setEstado(self,estado): self.estado = estado def setDoctor(self,doctor): self.doctor = doctor
class Cita: def __init__(self, id, solicitante, fecha, hora, motivo, estado, doctor): self.id = id self.solicitante = solicitante self.fecha = fecha self.hora = hora self.motivo = motivo self.estado = estado self.doctor = doctor def get_id(self): return self.id def get_solicitante(self): return self.solicitante def get_fecha(self): return self.fecha def get_hora(self): return self.hora def get_motivo(self): return self.motivo def get_estado(self): return self.estado def get_doctor(self): return self.doctor def set_solicitante(self, solicitante): self.solicitante = solicitante def set_fecha(self, fecha): self.fecha = fecha def set_hora(self, hora): self.hora = hora def set_motivo(self, motivo): self.motivo = motivo def set_estado(self, estado): self.estado = estado def set_doctor(self, doctor): self.doctor = doctor
class Calculator: def add(self,a,b): return a+b def subtract(self,a,b): return a-b def multiply(self,a,b): return a*b def divide(self,a,b): return a/b
class Calculator: def add(self, a, b): return a + b def subtract(self, a, b): return a - b def multiply(self, a, b): return a * b def divide(self, a, b): return a / b
start = '''You wake up one morning and find yourself in a big crisis. Trouble has arised and your worst fears have come true. Zoom is out to destroy the world for good. However, a castrophe has happened and now the love of your life is in danger. Which do you decide to save today?''' print(start) done = False print(" Type 'Flash to save the world' or 'Flash to save the love of his life' ") user_input = input() while not done: if user_input == "world": print (" Flash has to fight zoom to save the world. ") done = True print("Should Flash use lightening to attack Zoom or read his mind?") user_input = input() if user_input == "lightening": print("Flash defeats Zoom and saves the world!") done = True elif user_input == "mind": print("Flash might be able to defeat Zoom, but is still a disadvantage. ") done = True print("Flash is able to save the world.") elif user_input == "love": print ("In order to save the love of his life, Flash has to choose between two options. ") done = True print("Should Flash give up his power or his life in order to save the love of his life?") user_input = input() if user_input == "power": print("The Flash's speed is gone. But he is given the love of his life back into his hands. ") done = True elif user_input == "life": print("The Flash will die, but he sees that the love of his life is no longer in danger.") done = True print("No matter the circumstances, Flash is still alive. ")
start = 'You wake up one morning and find yourself in a big crisis. \nTrouble has arised and your worst fears have come true. Zoom is out to destroy\nthe world for good. However, a castrophe has happened and now the love of \nyour life is in danger. Which do you decide to save today?' print(start) done = False print(" Type 'Flash to save the world' or 'Flash to save the love of his life' ") user_input = input() while not done: if user_input == 'world': print(' Flash has to fight zoom to save the world. ') done = True print('Should Flash use lightening to attack Zoom or read his mind?') user_input = input() if user_input == 'lightening': print('Flash defeats Zoom and saves the world!') done = True elif user_input == 'mind': print('Flash might be able to defeat Zoom, but is still a disadvantage. ') done = True print('Flash is able to save the world.') elif user_input == 'love': print('In order to save the love of his life, Flash has to choose between two options. ') done = True print('Should Flash give up his power or his life in order to save the love of his life?') user_input = input() if user_input == 'power': print("The Flash's speed is gone. But he is given the love of his life back into his hands. ") done = True elif user_input == 'life': print('The Flash will die, but he sees that the love of his life is no longer in danger.') done = True print('No matter the circumstances, Flash is still alive. ')
{'application':{'type':'Application', 'name':'codeEditor', 'backgrounds': [ {'type':'Background', 'name':'bgCodeEditor', 'title':'Code Editor R PythonCard Application', 'size':(400, 300), 'statusBar':1, 'visible':0, 'style':['resizeable'], 'visible':0, 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', 'name':'menuFile', 'label':'&File', 'items': [ {'type':'MenuItem', 'name':'menuFileNewWindow', 'label':'New Window', }, {'type':'MenuItem', 'name':'menuFileNew', 'label':'&New\tCtrl+N', }, {'type':'MenuItem', 'name':'menuFileOpen', 'label':'&Open\tCtrl+O', }, {'type':'MenuItem', 'name':'menuFileSave', 'label':'&Save\tCtrl+S', }, {'type':'MenuItem', 'name':'menuFileSaveAs', 'label':'Save &As...', }, {'type':'MenuItem', 'name':'fileSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuFileCheckSyntax', 'label':'&Check Syntax (Module)\tAlt+F5', 'command':'checkSyntax', }, {'type':'MenuItem', 'name':'menuFileRun', 'label':'&Run\tCtrl+R', 'command':'fileRun', }, {'type':'MenuItem', 'name':'menuFileRunWithInterpreter', 'label':'Run with &interpreter\tCtrl+Shift+R', 'command':'fileRunWithInterpreter', }, {'type':'MenuItem', 'name':'menuFileRunOptions', 'label':'Run Options...', 'command':'fileRunOptions', }, {'type':'MenuItem', 'name':'fileSep2', 'label':'-', }, {'type':'MenuItem', 'name':'menuFilePageSetup', 'label':'Page Set&up...', }, {'type':'MenuItem', 'name':'menuFilePrint', 'label':'&Print...\tCtrl+P', }, {'type':'MenuItem', 'name':'menuFilePrintPreview', 'label':'Print Pre&view', }, {'type':'MenuItem', 'name':'fileSep2', 'label':'-', }, {'type':'MenuItem', 'name':'menuFileExit', 'label':'E&xit\tAlt+X', 'command':'exit', }, ] }, {'type':'Menu', 'name':'Edit', 'label':'&Edit', 'items': [ {'type':'MenuItem', 'name':'menuEditUndo', 'label':'&Undo\tCtrl+Z', }, {'type':'MenuItem', 'name':'menuEditRedo', 'label':'&Redo\tCtrl+Y', }, {'type':'MenuItem', 'name':'editSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuEditCut', 'label':'Cu&t\tCtrl+X', }, {'type':'MenuItem', 'name':'menuEditCopy', 'label':'&Copy\tCtrl+C', }, {'type':'MenuItem', 'name':'menuEditPaste', 'label':'&Paste\tCtrl+V', }, {'type':'MenuItem', 'name':'editSep2', 'label':'-', }, {'type':'MenuItem', 'name':'menuEditFind', 'label':'&Find...\tCtrl+F', 'command':'doEditFind', }, {'type':'MenuItem', 'name':'menuEditFindNext', 'label':'&Find Next\tF3', 'command':'doEditFindNext', }, {'type':'MenuItem', 'name':'menuEditFindFiles', 'label':'Find in Files...\tAlt+F3', 'command':'findFiles', }, {'type':'MenuItem', 'name':'menuEditReplace', 'label':'&Replace...\tCtrl+H', 'command':'doEditFindReplace', }, {'type':'MenuItem', 'name':'menuEditGoTo', 'label':'&Go To...\tCtrl+G', 'command':'doEditGoTo', }, {'type':'MenuItem', 'name':'editSep3', 'label':'-', }, {'type':'MenuItem', 'name':'menuEditReplaceTabs', 'label':'&Replace tabs with spaces', 'command':'doEditReplaceTabs', }, {'type':'MenuItem', 'name':'editSep3', 'label':'-', }, {'type':'MenuItem', 'name':'menuEditClear', 'label':'Cle&ar\tDel', }, {'type':'MenuItem', 'name':'menuEditSelectAll', 'label':'Select A&ll\tCtrl+A', }, {'type':'MenuItem', 'name':'editSep4', 'label':'-', }, {'type':'MenuItem', 'name':'menuEditIndentRegion', 'label':'&Indent Region', 'command':'indentRegion', }, {'type':'MenuItem', 'name':'menuEditDedentRegion', 'label':'&Dedent Region', 'command':'dedentRegion', }, {'type':'MenuItem', 'name':'menuEditCommentRegion', 'label':'Comment &out region\tAlt+3', 'command':'commentRegion', }, {'type':'MenuItem', 'name':'menuEditUncommentRegion', 'label':'U&ncomment region\tShift+Alt+3', 'command':'uncommentRegion', }, ] }, {'type':'Menu', 'name':'menuView', 'label':'&View', 'items': [ {'type':'MenuItem', 'name':'menuViewWhitespace', 'label':'&Whitespace', 'checkable':1, }, {'type':'MenuItem', 'name':'menuViewIndentationGuides', 'label':'Indentation &guides', 'checkable':1, }, {'type':'MenuItem', 'name':'menuViewRightEdgeIndicator', 'label':'&Right edge indicator', 'checkable':1, }, {'type':'MenuItem', 'name':'menuViewEndOfLineMarkers', 'label':'&End-of-line markers', 'checkable':1, }, {'type':'MenuItem', 'name':'menuViewFixedFont', 'label':'&Fixed Font', 'enabled':0, 'checkable':1, }, {'type':'MenuItem', 'name':'viewSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuViewLineNumbers', 'label':'&Line Numbers', 'checkable':1, 'checked':1, }, {'type':'MenuItem', 'name':'menuViewCodeFolding', 'label':'&Code Folding', 'checkable':1, 'checked':0, }, ] }, {'type':'Menu', 'name':'menuFormat', 'label':'F&ormat', 'items': [ {'type':'MenuItem', 'name':'menuFormatStyles', 'label':'&Styles...', 'command':'doSetStyles', }, {'type':'MenuItem', 'name':'menuFormatWrap', 'label':'&Wrap Lines', 'checkable':1, }, ] }, {'type':'Menu', 'name':'menuScriptlet', 'label':'&Shell', 'items': [ {'type':'MenuItem', 'name':'menuScriptletShell', 'label':'&Shell Window\tF5', }, {'type':'MenuItem', 'name':'menuScriptletNamespace', 'label':'&Namespace Window\tF6', }, {'type':'MenuItem', 'name':'scriptletSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuScriptletSaveShellSelection', 'label':'Save Shell Selection...', }, {'type':'MenuItem', 'name':'menuScriptletRunScriptlet', 'label':'Run Scriptlet...', }, ] }, {'type':'Menu', 'name':'menuHelp', 'label':'&Help', 'items': [ {'type':'MenuItem', 'name':'menuShellDocumentation', 'label':'&Shell Documentation...', 'command':'showShellDocumentation', }, {'type':'MenuItem', 'name':'menuPythonCardDocumentation', 'label':'&PythonCard Documentation...\tF1', 'command':'showPythonCardDocumentation', }, {'type':'MenuItem', 'name':'menuPythonDocumentation', 'label':'Python &Documentation...', 'command':'showPythonDocumentation', }, {'type':'MenuItem', 'name':'helpSep1', 'label':'-', }, {'type':'MenuItem', 'name':'menuHelpAbout', 'label':'&About codeEditor...', 'command':'doHelpAbout', }, ] }, ] }, 'strings': { 'saveAs':'Save As', 'about':'About codeEditor...', 'saveAsWildcard':'All files (*.*)|*.*|Python scripts (*.py;*.pyw)|*.pyw;*.PY;*.PYW;*.py|Text files (*.txt;*.text)|*.text;*.TXT;*.TEXT;*.txt|HTML and XML files (*.htm;*.html;*.xml)|*.htm;*.xml;*.HTM;*.HTML;*.XML;*.html', 'chars':'chars', 'gotoLine':'Goto line', 'lines':'lines', 'gotoLineNumber':'Goto line number:', 'documentChangedPrompt':'The text in the %s file has changed.\n\nDo you want to save the changes?', 'untitled':'Untitled', 'sample':'codeEditor sample', 'codeEditor':'codeEditor', 'replaced':'Replaced %d occurances', 'words':'words', 'openFile':'Open file', 'scriptletWildcard':'Python files (*.py)|*.py|All Files (*.*)|*.*', 'document':'Document', }, 'components': [ {'type':'Choice', 'name':'popComponentNames', }, {'type':'Choice', 'name':'popComponentEvents', }, {'type':'CodeEditor', 'name':'document', 'position':(0, 0), 'size':(250, 100), }, ] # end components } # end background ] # end backgrounds } }
{'application': {'type': 'Application', 'name': 'codeEditor', 'backgrounds': [{'type': 'Background', 'name': 'bgCodeEditor', 'title': 'Code Editor R PythonCard Application', 'size': (400, 300), 'statusBar': 1, 'visible': 0, 'style': ['resizeable'], 'visible': 0, 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'menuFile', 'label': '&File', 'items': [{'type': 'MenuItem', 'name': 'menuFileNewWindow', 'label': 'New Window'}, {'type': 'MenuItem', 'name': 'menuFileNew', 'label': '&New\tCtrl+N'}, {'type': 'MenuItem', 'name': 'menuFileOpen', 'label': '&Open\tCtrl+O'}, {'type': 'MenuItem', 'name': 'menuFileSave', 'label': '&Save\tCtrl+S'}, {'type': 'MenuItem', 'name': 'menuFileSaveAs', 'label': 'Save &As...'}, {'type': 'MenuItem', 'name': 'fileSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuFileCheckSyntax', 'label': '&Check Syntax (Module)\tAlt+F5', 'command': 'checkSyntax'}, {'type': 'MenuItem', 'name': 'menuFileRun', 'label': '&Run\tCtrl+R', 'command': 'fileRun'}, {'type': 'MenuItem', 'name': 'menuFileRunWithInterpreter', 'label': 'Run with &interpreter\tCtrl+Shift+R', 'command': 'fileRunWithInterpreter'}, {'type': 'MenuItem', 'name': 'menuFileRunOptions', 'label': 'Run Options...', 'command': 'fileRunOptions'}, {'type': 'MenuItem', 'name': 'fileSep2', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuFilePageSetup', 'label': 'Page Set&up...'}, {'type': 'MenuItem', 'name': 'menuFilePrint', 'label': '&Print...\tCtrl+P'}, {'type': 'MenuItem', 'name': 'menuFilePrintPreview', 'label': 'Print Pre&view'}, {'type': 'MenuItem', 'name': 'fileSep2', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuFileExit', 'label': 'E&xit\tAlt+X', 'command': 'exit'}]}, {'type': 'Menu', 'name': 'Edit', 'label': '&Edit', 'items': [{'type': 'MenuItem', 'name': 'menuEditUndo', 'label': '&Undo\tCtrl+Z'}, {'type': 'MenuItem', 'name': 'menuEditRedo', 'label': '&Redo\tCtrl+Y'}, {'type': 'MenuItem', 'name': 'editSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditCut', 'label': 'Cu&t\tCtrl+X'}, {'type': 'MenuItem', 'name': 'menuEditCopy', 'label': '&Copy\tCtrl+C'}, {'type': 'MenuItem', 'name': 'menuEditPaste', 'label': '&Paste\tCtrl+V'}, {'type': 'MenuItem', 'name': 'editSep2', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditFind', 'label': '&Find...\tCtrl+F', 'command': 'doEditFind'}, {'type': 'MenuItem', 'name': 'menuEditFindNext', 'label': '&Find Next\tF3', 'command': 'doEditFindNext'}, {'type': 'MenuItem', 'name': 'menuEditFindFiles', 'label': 'Find in Files...\tAlt+F3', 'command': 'findFiles'}, {'type': 'MenuItem', 'name': 'menuEditReplace', 'label': '&Replace...\tCtrl+H', 'command': 'doEditFindReplace'}, {'type': 'MenuItem', 'name': 'menuEditGoTo', 'label': '&Go To...\tCtrl+G', 'command': 'doEditGoTo'}, {'type': 'MenuItem', 'name': 'editSep3', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditReplaceTabs', 'label': '&Replace tabs with spaces', 'command': 'doEditReplaceTabs'}, {'type': 'MenuItem', 'name': 'editSep3', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditClear', 'label': 'Cle&ar\tDel'}, {'type': 'MenuItem', 'name': 'menuEditSelectAll', 'label': 'Select A&ll\tCtrl+A'}, {'type': 'MenuItem', 'name': 'editSep4', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuEditIndentRegion', 'label': '&Indent Region', 'command': 'indentRegion'}, {'type': 'MenuItem', 'name': 'menuEditDedentRegion', 'label': '&Dedent Region', 'command': 'dedentRegion'}, {'type': 'MenuItem', 'name': 'menuEditCommentRegion', 'label': 'Comment &out region\tAlt+3', 'command': 'commentRegion'}, {'type': 'MenuItem', 'name': 'menuEditUncommentRegion', 'label': 'U&ncomment region\tShift+Alt+3', 'command': 'uncommentRegion'}]}, {'type': 'Menu', 'name': 'menuView', 'label': '&View', 'items': [{'type': 'MenuItem', 'name': 'menuViewWhitespace', 'label': '&Whitespace', 'checkable': 1}, {'type': 'MenuItem', 'name': 'menuViewIndentationGuides', 'label': 'Indentation &guides', 'checkable': 1}, {'type': 'MenuItem', 'name': 'menuViewRightEdgeIndicator', 'label': '&Right edge indicator', 'checkable': 1}, {'type': 'MenuItem', 'name': 'menuViewEndOfLineMarkers', 'label': '&End-of-line markers', 'checkable': 1}, {'type': 'MenuItem', 'name': 'menuViewFixedFont', 'label': '&Fixed Font', 'enabled': 0, 'checkable': 1}, {'type': 'MenuItem', 'name': 'viewSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuViewLineNumbers', 'label': '&Line Numbers', 'checkable': 1, 'checked': 1}, {'type': 'MenuItem', 'name': 'menuViewCodeFolding', 'label': '&Code Folding', 'checkable': 1, 'checked': 0}]}, {'type': 'Menu', 'name': 'menuFormat', 'label': 'F&ormat', 'items': [{'type': 'MenuItem', 'name': 'menuFormatStyles', 'label': '&Styles...', 'command': 'doSetStyles'}, {'type': 'MenuItem', 'name': 'menuFormatWrap', 'label': '&Wrap Lines', 'checkable': 1}]}, {'type': 'Menu', 'name': 'menuScriptlet', 'label': '&Shell', 'items': [{'type': 'MenuItem', 'name': 'menuScriptletShell', 'label': '&Shell Window\tF5'}, {'type': 'MenuItem', 'name': 'menuScriptletNamespace', 'label': '&Namespace Window\tF6'}, {'type': 'MenuItem', 'name': 'scriptletSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuScriptletSaveShellSelection', 'label': 'Save Shell Selection...'}, {'type': 'MenuItem', 'name': 'menuScriptletRunScriptlet', 'label': 'Run Scriptlet...'}]}, {'type': 'Menu', 'name': 'menuHelp', 'label': '&Help', 'items': [{'type': 'MenuItem', 'name': 'menuShellDocumentation', 'label': '&Shell Documentation...', 'command': 'showShellDocumentation'}, {'type': 'MenuItem', 'name': 'menuPythonCardDocumentation', 'label': '&PythonCard Documentation...\tF1', 'command': 'showPythonCardDocumentation'}, {'type': 'MenuItem', 'name': 'menuPythonDocumentation', 'label': 'Python &Documentation...', 'command': 'showPythonDocumentation'}, {'type': 'MenuItem', 'name': 'helpSep1', 'label': '-'}, {'type': 'MenuItem', 'name': 'menuHelpAbout', 'label': '&About codeEditor...', 'command': 'doHelpAbout'}]}]}, 'strings': {'saveAs': 'Save As', 'about': 'About codeEditor...', 'saveAsWildcard': 'All files (*.*)|*.*|Python scripts (*.py;*.pyw)|*.pyw;*.PY;*.PYW;*.py|Text files (*.txt;*.text)|*.text;*.TXT;*.TEXT;*.txt|HTML and XML files (*.htm;*.html;*.xml)|*.htm;*.xml;*.HTM;*.HTML;*.XML;*.html', 'chars': 'chars', 'gotoLine': 'Goto line', 'lines': 'lines', 'gotoLineNumber': 'Goto line number:', 'documentChangedPrompt': 'The text in the %s file has changed.\n\nDo you want to save the changes?', 'untitled': 'Untitled', 'sample': 'codeEditor sample', 'codeEditor': 'codeEditor', 'replaced': 'Replaced %d occurances', 'words': 'words', 'openFile': 'Open file', 'scriptletWildcard': 'Python files (*.py)|*.py|All Files (*.*)|*.*', 'document': 'Document'}, 'components': [{'type': 'Choice', 'name': 'popComponentNames'}, {'type': 'Choice', 'name': 'popComponentEvents'}, {'type': 'CodeEditor', 'name': 'document', 'position': (0, 0), 'size': (250, 100)}]}]}}
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. class TimexRelativeConvert: @staticmethod def convert_timex_to_string_relative(timex): return ''
class Timexrelativeconvert: @staticmethod def convert_timex_to_string_relative(timex): return ''
#!/bin/python3 h = 0 t = int(input().strip()) for a0 in range(t): n = int(input().strip()) if n%2 == 1: h = 2 ** (int(n/2) + 2) - 2 elif n%2 == 0: h = 2 ** (int(n/2) + 1) - 1 print(h)
h = 0 t = int(input().strip()) for a0 in range(t): n = int(input().strip()) if n % 2 == 1: h = 2 ** (int(n / 2) + 2) - 2 elif n % 2 == 0: h = 2 ** (int(n / 2) + 1) - 1 print(h)
#print ("Hello World") #counties=["Arapahoes","Denver","Jefferson"] #if counties[1]=='Denver': # print(counties[1]) #counties = ["Arapahoe","Denver","Jefferson"] #if "El Paso" in counties: # print("El Paso is in the list of counties.") #else: # print("El Paso is not the list of counties.") #if "Arapahoe" in counties and "El Paso" in counties: # print("Arapahoe and El Paso are in the list of counties.") #else: # print("Arapahoe or El Paso is not in the list of counties.") #if "Arapahoe" in counties or "El Paso" in counties: # print("Arapahoe or El Paso is in the list of counties.") #else: # print("Arapahoe and El Paso are not in the list of counties.") #counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438} #for county in counties: # print(county) #for county in counties_dict.keys(): # print(county) #for voters in counties_dict.values(): # print(voters) #for county in counties_dict: # print(counties_dict[county]) #for county, voters in counties_dict.items(): #print(f"{county} county has {voters} registered voters.") voting_data = [{"county":"Arapahoe", "registered_voters": 422829}, {"county":"Denver", "registered_voters": 463353}, {"county":"Jefferson", "registered_voters": 432438}] #prints as a continuous list #print(voting_data) #prints as a stack. prints 1 under the other #for county_dict in voting_data: #print(county_dict) #3.2.10 says this will iterarte and print the counties. #I understand the for loop but dont understand the print line. #how does the module expect us to know this if we didn't cover it. #['county'] is throwing me off #for i in range(len(voting_data)): #print(voting_data[i]['county']) #for i in range(len(voting_data)): #print(voting_data[i]['registered_voters']) #why doesnt this work with registered_voters_dict. neither_dict are defined #for county_dict in voting_data: #for value in county_dict.values(): #print(value) #candidate_votes = int (input("How many votes did the candidate get in the election?")) #total_votes = int(input("What is the total number of votes in the election?")) #message_to_candidate = ( #f"You received {candidate_votes:,} number of votes. " #f"The total number of votes in the election was {total_votes:,}. " #f"You received {candidate_votes / total_votes * 100:.2f}% of the votes") #print(message_to_candidate) #f'{value:{width},.{precision}}' #width=number of characters #precision=.#'sf where # is the decimal places #skill drill #for county, voters in counties_dict.items(): #print(f"{county} county has {voters:,} registered voters.") #skill drill--need help solving #for county_dict in voting_data: #print(f"{county} county has {voters} registered voters.") for county, voters in voting_data: print (f"{'county'} county has {'voters'} registered voters")
voting_data = [{'county': 'Arapahoe', 'registered_voters': 422829}, {'county': 'Denver', 'registered_voters': 463353}, {'county': 'Jefferson', 'registered_voters': 432438}] for (county, voters) in voting_data: print(f"{'county'} county has {'voters'} registered voters")
#first exercise #This code asks the user for hours and rate for hour, calculate total pay and print it. hrs = input("Enter Hours:") rate = input("Enter Rate:") pay = float(hrs) * float(rate) print("Pay:", pay) #second exercise #This code asks the user for hours and rate for hour, calculate total pay and print it. #If more than 40 hours, the rate is 1.5 the initial rate. hrs = input("Enter Hours:") rate = input("Enter Rate:") try: h = float(hrs) r = float(rate) except: print("Insert numbers") if h>40: p = 40 * r + (((h-40)*1.5)*r) else: p = h * r p= float(p) print(p)
hrs = input('Enter Hours:') rate = input('Enter Rate:') pay = float(hrs) * float(rate) print('Pay:', pay) hrs = input('Enter Hours:') rate = input('Enter Rate:') try: h = float(hrs) r = float(rate) except: print('Insert numbers') if h > 40: p = 40 * r + (h - 40) * 1.5 * r else: p = h * r p = float(p) print(p)
ANGULAR_PACKAGES_CONFIG = [ ("@angular/animations", struct(entry_points = ["browser"])), ("@angular/common", struct(entry_points = ["http/testing", "http", "testing"])), ("@angular/compiler", struct(entry_points = ["testing"])), ("@angular/core", struct(entry_points = ["testing"])), ("@angular/forms", struct(entry_points = [])), ("@angular/platform-browser", struct(entry_points = ["testing", "animations"])), ("@angular/platform-browser-dynamic", struct(entry_points = ["testing"])), ("@angular/router", struct(entry_points = [])), ] ANGULAR_PACKAGES = [ struct( name = name[len("@angular/"):], entry_points = config.entry_points, platform = config.platform if hasattr(config, "platform") else "browser", module_name = name, ) for name, config in ANGULAR_PACKAGES_CONFIG ]
angular_packages_config = [('@angular/animations', struct(entry_points=['browser'])), ('@angular/common', struct(entry_points=['http/testing', 'http', 'testing'])), ('@angular/compiler', struct(entry_points=['testing'])), ('@angular/core', struct(entry_points=['testing'])), ('@angular/forms', struct(entry_points=[])), ('@angular/platform-browser', struct(entry_points=['testing', 'animations'])), ('@angular/platform-browser-dynamic', struct(entry_points=['testing'])), ('@angular/router', struct(entry_points=[]))] angular_packages = [struct(name=name[len('@angular/'):], entry_points=config.entry_points, platform=config.platform if hasattr(config, 'platform') else 'browser', module_name=name) for (name, config) in ANGULAR_PACKAGES_CONFIG]
# Implement a class to hold room information. This should have name and # description attributes. class Room: def __init__(self, number, world, name, description, enemies, enemyHP, enemy_diff, companion=[], item=[] ,enemy_description=[] ): self.number = number self.name = name self.world = world self.description = description self.item = item self.enemies = enemies self.enemyHP = enemyHP self.enemy_description = enemy_description self.enemy_diff = enemy_diff self.companion = companion self.n_to = None self.w_to = None self.e_to = None self.s_to = None self.magic_to = None self.fly_to = None def __str__(self): return str(self.__class__) + ": " + str(self.__dict__) class Monster: def __init__(self, name, ability): self.name = name self.ability = ability def __str__(self): return str(self.__class__) + ": " + str(self.__dict__) class MagicRoom(Room): def __init__(self, name, description, enemies, enemyHP, enemy_diff, companion, item=[] ,enemy_description=[]): super().__init__ (name, description, enemies, enemyHP, enemy_diff, item=[], enemy_description=[] ) self.companion = companion self.n_to = None self.w_to = None self.e_to = None self.s_to = None self.magic_to = None self.fly_to = None Map = { 1: [2,0,0,0,0,0], 2: [3,1,4,0,0, 0], 3: [0,2,0,0,0, 0], 4: [5,0,0,2,0, 0], 5: [6,4,0,0,0, 0], 6: [0,5,7,0,0, 0], \ 7: [0,0,0,6,8, 0], 8: [9,0,10,0,7, 0], 9: [0,8,0,0,0, 11], 10: [0,0,0,8,0, 0], 11: [0,0,12,0,0, 9], 12: [14,0,0,0,13, 0], \ 13: [0,0,0,0,0, 0], 14: [15,12,0,0,0, 0], 15: [16,14,0,0,0, 0], 16: [0,15,0,0,0, 0], 17: [18,0,0,0,0, 0], 18: [0,17,0,0,0, 0]\ }
class Room: def __init__(self, number, world, name, description, enemies, enemyHP, enemy_diff, companion=[], item=[], enemy_description=[]): self.number = number self.name = name self.world = world self.description = description self.item = item self.enemies = enemies self.enemyHP = enemyHP self.enemy_description = enemy_description self.enemy_diff = enemy_diff self.companion = companion self.n_to = None self.w_to = None self.e_to = None self.s_to = None self.magic_to = None self.fly_to = None def __str__(self): return str(self.__class__) + ': ' + str(self.__dict__) class Monster: def __init__(self, name, ability): self.name = name self.ability = ability def __str__(self): return str(self.__class__) + ': ' + str(self.__dict__) class Magicroom(Room): def __init__(self, name, description, enemies, enemyHP, enemy_diff, companion, item=[], enemy_description=[]): super().__init__(name, description, enemies, enemyHP, enemy_diff, item=[], enemy_description=[]) self.companion = companion self.n_to = None self.w_to = None self.e_to = None self.s_to = None self.magic_to = None self.fly_to = None map = {1: [2, 0, 0, 0, 0, 0], 2: [3, 1, 4, 0, 0, 0], 3: [0, 2, 0, 0, 0, 0], 4: [5, 0, 0, 2, 0, 0], 5: [6, 4, 0, 0, 0, 0], 6: [0, 5, 7, 0, 0, 0], 7: [0, 0, 0, 6, 8, 0], 8: [9, 0, 10, 0, 7, 0], 9: [0, 8, 0, 0, 0, 11], 10: [0, 0, 0, 8, 0, 0], 11: [0, 0, 12, 0, 0, 9], 12: [14, 0, 0, 0, 13, 0], 13: [0, 0, 0, 0, 0, 0], 14: [15, 12, 0, 0, 0, 0], 15: [16, 14, 0, 0, 0, 0], 16: [0, 15, 0, 0, 0, 0], 17: [18, 0, 0, 0, 0, 0], 18: [0, 17, 0, 0, 0, 0]}
load("//flatbuffers/internal:string_utils.bzl", "capitalize_first_char") def _include_args_from_depset(includes_depset): # Always include the workspace root. include_args = ["-I", "."] for include in includes_depset.to_list(): include_args.append("-I") include_args.append(include) return include_args def run_flatc( ctx, fbs_toolchain, fbs_lang_toolchain, srcs, srcs_transitive, includes_transitive, outputs): flatc = fbs_toolchain.flatc.files_to_run.executable include_args = _include_args_from_depset(includes_transitive) output_prefix = ctx.genfiles_dir.path + "/" + ctx.label.package mnemonic = "Flatbuffers{}Gen".format(capitalize_first_char(fbs_lang_toolchain.lang_shortname)) progress_message = "Generating flatbuffers {} file for {}:".format( fbs_lang_toolchain.lang_shortname, ctx.label, ) genrule_args = \ fbs_lang_toolchain.flatc_args + \ ["-o", output_prefix] + \ include_args + \ [src.path for src in srcs] ctx.actions.run( inputs = srcs_transitive, outputs = outputs, executable = flatc, tools = [flatc], arguments = genrule_args, mnemonic = mnemonic, progress_message = progress_message, )
load('//flatbuffers/internal:string_utils.bzl', 'capitalize_first_char') def _include_args_from_depset(includes_depset): include_args = ['-I', '.'] for include in includes_depset.to_list(): include_args.append('-I') include_args.append(include) return include_args def run_flatc(ctx, fbs_toolchain, fbs_lang_toolchain, srcs, srcs_transitive, includes_transitive, outputs): flatc = fbs_toolchain.flatc.files_to_run.executable include_args = _include_args_from_depset(includes_transitive) output_prefix = ctx.genfiles_dir.path + '/' + ctx.label.package mnemonic = 'Flatbuffers{}Gen'.format(capitalize_first_char(fbs_lang_toolchain.lang_shortname)) progress_message = 'Generating flatbuffers {} file for {}:'.format(fbs_lang_toolchain.lang_shortname, ctx.label) genrule_args = fbs_lang_toolchain.flatc_args + ['-o', output_prefix] + include_args + [src.path for src in srcs] ctx.actions.run(inputs=srcs_transitive, outputs=outputs, executable=flatc, tools=[flatc], arguments=genrule_args, mnemonic=mnemonic, progress_message=progress_message)
# node class for develping linked list class Node: def __init__(self, data=None, pointer=None): self.data = data self.pointer = pointer def set_data(self, data): self.data = data def get_data(self): return self.data def set_pointer(self, pointer): self.pointer = pointer def get_pointer(self): return self.pointer def __str__(self): return f'(data: {self.data} & pointer: {self.pointer})' class Stack: def __init__(self, buttom=None, top=None): self.buttom = buttom self.top = top # push operation def push(self, data): if self.buttom == None: self.buttom = self.top = Node(data) else: new_node = Node(data, self.top) self.top = new_node return self # pop operation def pop(self): if self.top == None: return None data = self.top.get_data() self.top = self.top.get_pointer() return data # peek operation def peek(self): return self.top.get_data() # returns stack as list def as_list(self): curr_node = self.top stack_list = list() while curr_node.get_pointer() != None: stack_list.append(curr_node.get_data()) curr_node = curr_node.get_pointer() stack_list.append(curr_node.get_data()) return stack_list # returns True if stack empty and False if its not def is_empty(self): if self.top: return False else: return True def __str__(self): return f'top: {self.top} & buttom: {self.buttom}' if __name__ == '__main__': stack = Stack() stack.push('Google') stack.push('Udemy') stack.push('Facebook') # print(stack.peek()) stack.pop() print(stack.peek()) print(stack.as_list())
class Node: def __init__(self, data=None, pointer=None): self.data = data self.pointer = pointer def set_data(self, data): self.data = data def get_data(self): return self.data def set_pointer(self, pointer): self.pointer = pointer def get_pointer(self): return self.pointer def __str__(self): return f'(data: {self.data} & pointer: {self.pointer})' class Stack: def __init__(self, buttom=None, top=None): self.buttom = buttom self.top = top def push(self, data): if self.buttom == None: self.buttom = self.top = node(data) else: new_node = node(data, self.top) self.top = new_node return self def pop(self): if self.top == None: return None data = self.top.get_data() self.top = self.top.get_pointer() return data def peek(self): return self.top.get_data() def as_list(self): curr_node = self.top stack_list = list() while curr_node.get_pointer() != None: stack_list.append(curr_node.get_data()) curr_node = curr_node.get_pointer() stack_list.append(curr_node.get_data()) return stack_list def is_empty(self): if self.top: return False else: return True def __str__(self): return f'top: {self.top} & buttom: {self.buttom}' if __name__ == '__main__': stack = stack() stack.push('Google') stack.push('Udemy') stack.push('Facebook') stack.pop() print(stack.peek()) print(stack.as_list())
print("hello") while True: print("Infinite loop")
print('hello') while True: print('Infinite loop')
def division(a, b): b = float(b) if b == 0: c = 0 print('Cannot divide by 0.') return c else: a = float(a) c = round(a / b, 9) return c
def division(a, b): b = float(b) if b == 0: c = 0 print('Cannot divide by 0.') return c else: a = float(a) c = round(a / b, 9) return c