content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/python3 ## Solution 1: def to_rna(dna_strand): rna = [] for transcription in dna_strand: if transcription == "G": rna.append("C") elif transcription == "C": rna.append("G") elif transcription == "T": rna.append("A") elif transcription == "A": rna.append("U") return "".join(rna) print(to_rna("GCTA")) ## Solution 2: #def to_rna(dna: str) -> str: # """ transcribe a DNA string to RNA and return as another string """ # translate_table = dna.maketrans('GCTA', 'CGAU') # # rna = dna.translate(translate_table) # # return(rna) ## Solution 3: #mapping = {'G': 'C', 'C': 'G', 'T': 'A', 'A': 'U'} # #def to_rna(dna_strand): # return ''.join(mapping[c] for c in dna_strand.upper())
def to_rna(dna_strand): rna = [] for transcription in dna_strand: if transcription == 'G': rna.append('C') elif transcription == 'C': rna.append('G') elif transcription == 'T': rna.append('A') elif transcription == 'A': rna.append('U') return ''.join(rna) print(to_rna('GCTA'))
filepath = 'Prometheus_Unbound.txt' with open(filepath) as fp: line = fp.readline() cnt = 1 while line: print("Line {}: {}".format(cnt, line.strip())) line = fp.readline() cnt += 1
filepath = 'Prometheus_Unbound.txt' with open(filepath) as fp: line = fp.readline() cnt = 1 while line: print('Line {}: {}'.format(cnt, line.strip())) line = fp.readline() cnt += 1
sum = 0 for i in range(1000): if i%3==0 or i%5==0: sum+=i print(sum)
sum = 0 for i in range(1000): if i % 3 == 0 or i % 5 == 0: sum += i print(sum)
# -*- coding: utf-8 -*- """ Created on Fri Feb 28 15:37:22 2020 @author: 766810 """ # Creates a dictionary called 'score' which takes each letter in scrabble as keys and assigns their respective points as values score = {"a": 1 , "b": 3 , "c": 3 , "d": 2 , "e": 1 , "f": 4 , "g": 2 , "h": 4 , "i": 1 , "j": 8 , "k": 5 , "l": 1 , "m": 3 , "n": 1 , "o": 1 , "p": 3 , "q": 10, "r": 1 , "s": 1 , "t": 1 , "u": 1 , "v": 4 , "w": 4 , "x": 8 , "y": 4 , "z": 10} # Creates a function which takes 1 argument def scrabble_score(word): # Initial score is 0 total = 0; # Looks at every letter in 'word' for i in word: # Makes all the letters lowercase (since the dictionary 'score' has no uppercase letters due to laziness) i = i.lower(); # Adds the score of each letter up and putting them into 'total' total = total + score[i]; return total; # Allows you to input a word your_word = input("Enter a word: "); # The score of your word is printed print(scrabble_score(your_word));
""" Created on Fri Feb 28 15:37:22 2020 @author: 766810 """ score = {'a': 1, 'b': 3, 'c': 3, 'd': 2, 'e': 1, 'f': 4, 'g': 2, 'h': 4, 'i': 1, 'j': 8, 'k': 5, 'l': 1, 'm': 3, 'n': 1, 'o': 1, 'p': 3, 'q': 10, 'r': 1, 's': 1, 't': 1, 'u': 1, 'v': 4, 'w': 4, 'x': 8, 'y': 4, 'z': 10} def scrabble_score(word): total = 0 for i in word: i = i.lower() total = total + score[i] return total your_word = input('Enter a word: ') print(scrabble_score(your_word))
""" Write a Python function to reverses a string if it's length is a multiple of 4. """ def reverse_string(str1): if len(str1) % 4 == 0: return "".join(reversed(str1)) return str1 print(reverse_string("Python")) print(reverse_string("abcd"))
""" Write a Python function to reverses a string if it's length is a multiple of 4. """ def reverse_string(str1): if len(str1) % 4 == 0: return ''.join(reversed(str1)) return str1 print(reverse_string('Python')) print(reverse_string('abcd'))
# -*- coding: utf-8 -*- """ Package of employer interfaces and implementations. """
""" Package of employer interfaces and implementations. """
# https://www.codingame.com/training/easy/lumen def get_neighbors(col, row, room_size): if room_size == 1: return if row > 0: yield col, row - 1 if col > 0: yield col - 1, row - 1 if col < room_size - 1: yield col + 1, row - 1 if row < room_size - 1: yield col, row + 1 if col > 0: yield col - 1, row + 1 if col < room_size - 1: yield col + 1, row + 1 if col > 0: yield col - 1, row if col < room_size - 1: yield col + 1, row def fill_light(col, row, light_level, room, room_size): if light_level == 0: return if room[col][row] in ('X', 'C'): room[col][row] = light_level elif room[col][row] >= light_level: return room[col][row] = light_level for nc, nr in get_neighbors(col, row, room_size): fill_light(nc, nr, light_level - 1, room, room_size) def count_dark_spots(room, room_size): ret = 0 for col in range(room_size): for row in range(room_size): if room[col][row] in ('X', 0): ret += 1 return ret def solution(): room_size = int(input()) base_light = int(input()) candles = [] room = [] for col in range(room_size): room.append(input().split()) for row, c in enumerate(room[-1]): if c == 'C': candles.append((col, row)) for col, row in candles: fill_light(col, row, base_light, room, room_size) dark_spots = count_dark_spots(room, room_size) print(dark_spots) solution()
def get_neighbors(col, row, room_size): if room_size == 1: return if row > 0: yield (col, row - 1) if col > 0: yield (col - 1, row - 1) if col < room_size - 1: yield (col + 1, row - 1) if row < room_size - 1: yield (col, row + 1) if col > 0: yield (col - 1, row + 1) if col < room_size - 1: yield (col + 1, row + 1) if col > 0: yield (col - 1, row) if col < room_size - 1: yield (col + 1, row) def fill_light(col, row, light_level, room, room_size): if light_level == 0: return if room[col][row] in ('X', 'C'): room[col][row] = light_level elif room[col][row] >= light_level: return room[col][row] = light_level for (nc, nr) in get_neighbors(col, row, room_size): fill_light(nc, nr, light_level - 1, room, room_size) def count_dark_spots(room, room_size): ret = 0 for col in range(room_size): for row in range(room_size): if room[col][row] in ('X', 0): ret += 1 return ret def solution(): room_size = int(input()) base_light = int(input()) candles = [] room = [] for col in range(room_size): room.append(input().split()) for (row, c) in enumerate(room[-1]): if c == 'C': candles.append((col, row)) for (col, row) in candles: fill_light(col, row, base_light, room, room_size) dark_spots = count_dark_spots(room, room_size) print(dark_spots) solution()
neighborhoods = [ "Andersonville", "Archer Heights", "Ashburn", "Ashburn Estates", "Austin", "Avaondale", "Belmont Central", "Beverly", "Beverly Woods", "Brainerd", "Bridgeport", "Brighton Park", "Bronceville", "Bucktown", "Burnside", "Calumet Heights", "Canaryville", "Clearing", "Chatham", "Chinatown", "Cottage Grove Heights", "Cragin", "Dunning", "East Chicago", "Edison Park", "Edgebrook", "Edgewater", "Englewood", "Ford City", "Gage Park", "Galewood", "Garfield Park", "Garfield Ridge", "Gold Coast", "Grand Crossing", "Gresham", "Hamilton Park", "Humboldt Park", "Hyde Park", "Jefferson Park", "Kelvyn Park", "Kenwood", "Kilbourn Park", "Lake Meadows", "Lakeview", "Lawndale", "Lincoln Park", "Lincoln Square", "Little Village", "Logan Square", "Longwood Manor", "Loop", "Marquette Park", "McKinley Park", "Midway", "Morgan Park", "Montclare", "Mount Greenwood", "North Center", "Norwood Park", "Old Irving Park", "Old Town", "Park Manor", "Pilsen", "Princeton Park", "Portage Park", "Pullman", "Ravenswood", "River North", "River West", "Rodgers Park", "Roscoe VIllage", "Roseland", "Sauganash", "Schorsch Village", "Scottsdale", "South Chicago", "South Deering", "South Loop", "South Shore", "Streeterville", "Tri-Taylor", "Ukrainian Village", "United Center", "Uptown", "Vittum Park", "Washington Heights", "West Elsdon", "West Loop", "West Pullman", "Westlawn", "Wicker Park", "Woodlawn", "Wrigleyville", "Wrigtwood", ]
neighborhoods = ['Andersonville', 'Archer Heights', 'Ashburn', 'Ashburn Estates', 'Austin', 'Avaondale', 'Belmont Central', 'Beverly', 'Beverly Woods', 'Brainerd', 'Bridgeport', 'Brighton Park', 'Bronceville', 'Bucktown', 'Burnside', 'Calumet Heights', 'Canaryville', 'Clearing', 'Chatham', 'Chinatown', 'Cottage Grove Heights', 'Cragin', 'Dunning', 'East Chicago', 'Edison Park', 'Edgebrook', 'Edgewater', 'Englewood', 'Ford City', 'Gage Park', 'Galewood', 'Garfield Park', 'Garfield Ridge', 'Gold Coast', 'Grand Crossing', 'Gresham', 'Hamilton Park', 'Humboldt Park', 'Hyde Park', 'Jefferson Park', 'Kelvyn Park', 'Kenwood', 'Kilbourn Park', 'Lake Meadows', 'Lakeview', 'Lawndale', 'Lincoln Park', 'Lincoln Square', 'Little Village', 'Logan Square', 'Longwood Manor', 'Loop', 'Marquette Park', 'McKinley Park', 'Midway', 'Morgan Park', 'Montclare', 'Mount Greenwood', 'North Center', 'Norwood Park', 'Old Irving Park', 'Old Town', 'Park Manor', 'Pilsen', 'Princeton Park', 'Portage Park', 'Pullman', 'Ravenswood', 'River North', 'River West', 'Rodgers Park', 'Roscoe VIllage', 'Roseland', 'Sauganash', 'Schorsch Village', 'Scottsdale', 'South Chicago', 'South Deering', 'South Loop', 'South Shore', 'Streeterville', 'Tri-Taylor', 'Ukrainian Village', 'United Center', 'Uptown', 'Vittum Park', 'Washington Heights', 'West Elsdon', 'West Loop', 'West Pullman', 'Westlawn', 'Wicker Park', 'Woodlawn', 'Wrigleyville', 'Wrigtwood']
largura = int(input('digite a largura: ')) altura = int(input('digite a altura: ')) resetalargura = largura contador = largura print((largura) * '#', end='') while altura > 0: while contador < largura and contador > 0: print('#', end='') contador -= 1 print('#') altura -= 1 print((largura) * '#', end='') #while altura > 1: #if contador < largura and contador > 0: #print('#', (largura - 3) * ' ', end='') #elif contador == largura: #print((largura - 1) * '#', end='') #print('#') #altura -= 1 #contador -= 1 # #print((largura) * '#', end='')
largura = int(input('digite a largura: ')) altura = int(input('digite a altura: ')) resetalargura = largura contador = largura print(largura * '#', end='') while altura > 0: while contador < largura and contador > 0: print('#', end='') contador -= 1 print('#') altura -= 1 print(largura * '#', end='')
""" Use recursion to write a Python function for determining if a string S has more vowels than consonants. """ def remove_whitespace(string: str) -> str: """ This function replace whitespaces for void string -> '' Input: string with (or without) whitespace Output: string without whitespace """ try: if len(string) == 0 or (len(string) == 1 and string != ' '): return string.lower() else: new_string = string.replace(' ', '').replace('(', '').replace(')', '').replace('.', '').replace(',', '') return new_string.lower() except TypeError: exit('Invalid entry...') def vowels_consonants(S: list, stop: int, v_dict: dict, c_dict: dict) -> dict: """ This function count the vowels and consonants in the list S (note S is a list of letters in any string given), using a dictionary (built-in data structure, -dict-) and later return a tuple with two dictionary's, one for vowels and other for consonants. Note: this function call itself n-1 times for a list (S) of length n (n-1 = stop). Input: list 'S', top of the list 'stop' and two dictionary's one for vowels and other for consonants (which are used for counting the number of vowels and consonants on S). Output: a tuple of two dictionary's. """ if len(S) == 0: return None else: if S[stop - 1] in v_dict.keys(): v_dict[S[stop - 1]] += 1 else: c_dict[S[stop - 1]] += 1 if stop > 0: vowels_consonants(S, stop - 1, v_dict, c_dict) return v_dict, c_dict def more_vowel_than_consonants(vowel_dict: dict, consonant_dict: dict) -> bool: """ Function that returns a boolean value, indicating if an string have more vowels than consonants. Input: two dictionary's -> vowel_dict, consonant_dict. Output: True if number of vowels are greater than number of consonants. Neither return False. (Boolean type). """ more_vowels = sum(vowel_dict.values()) > sum(consonant_dict.values()) if more_vowels: return True elif not more_vowels: return False if __name__=='__main__': vowels = {x: 0 for x in {'a', 'e', 'i', 'o', 'u'}} consonants = {x: 0 for x in set(chr(y) for y in range(97, 123, 1)).difference({'a', 'e', 'i', 'o', 'u'})} word = sorted(list(remove_whitespace('Each element of the list will result in a bit memory address being stored in the primary array, ' 'and an int instance being stored elsewhere in memory. Python allows you to query ' 'the actual number of bytes being used for the primary storage of any object. This ' 'is done using the get size of function of the sys module. On our system, the size of ' 'a typical int object requires bytes of memory (well beyond the bytes needed ' 'for representing the actual bit number). In all, the list will be using bytes per ' 'entry, rather than the bytes that a compact list of integers would require.'))) top_word_list = len(word) - 1 vowels_consonants_dicts = vowels_consonants(word, top_word_list, vowels, consonants) print(more_vowel_than_consonants(vowels_consonants_dicts[0], vowels_consonants_dicts[1]))
""" Use recursion to write a Python function for determining if a string S has more vowels than consonants. """ def remove_whitespace(string: str) -> str: """ This function replace whitespaces for void string -> '' Input: string with (or without) whitespace Output: string without whitespace """ try: if len(string) == 0 or (len(string) == 1 and string != ' '): return string.lower() else: new_string = string.replace(' ', '').replace('(', '').replace(')', '').replace('.', '').replace(',', '') return new_string.lower() except TypeError: exit('Invalid entry...') def vowels_consonants(S: list, stop: int, v_dict: dict, c_dict: dict) -> dict: """ This function count the vowels and consonants in the list S (note S is a list of letters in any string given), using a dictionary (built-in data structure, -dict-) and later return a tuple with two dictionary's, one for vowels and other for consonants. Note: this function call itself n-1 times for a list (S) of length n (n-1 = stop). Input: list 'S', top of the list 'stop' and two dictionary's one for vowels and other for consonants (which are used for counting the number of vowels and consonants on S). Output: a tuple of two dictionary's. """ if len(S) == 0: return None else: if S[stop - 1] in v_dict.keys(): v_dict[S[stop - 1]] += 1 else: c_dict[S[stop - 1]] += 1 if stop > 0: vowels_consonants(S, stop - 1, v_dict, c_dict) return (v_dict, c_dict) def more_vowel_than_consonants(vowel_dict: dict, consonant_dict: dict) -> bool: """ Function that returns a boolean value, indicating if an string have more vowels than consonants. Input: two dictionary's -> vowel_dict, consonant_dict. Output: True if number of vowels are greater than number of consonants. Neither return False. (Boolean type). """ more_vowels = sum(vowel_dict.values()) > sum(consonant_dict.values()) if more_vowels: return True elif not more_vowels: return False if __name__ == '__main__': vowels = {x: 0 for x in {'a', 'e', 'i', 'o', 'u'}} consonants = {x: 0 for x in set((chr(y) for y in range(97, 123, 1))).difference({'a', 'e', 'i', 'o', 'u'})} word = sorted(list(remove_whitespace('Each element of the list will result in a bit memory address being stored in the primary array, and an int instance being stored elsewhere in memory. Python allows you to query the actual number of bytes being used for the primary storage of any object. This is done using the get size of function of the sys module. On our system, the size of a typical int object requires bytes of memory (well beyond the bytes needed for representing the actual bit number). In all, the list will be using bytes per entry, rather than the bytes that a compact list of integers would require.'))) top_word_list = len(word) - 1 vowels_consonants_dicts = vowels_consonants(word, top_word_list, vowels, consonants) print(more_vowel_than_consonants(vowels_consonants_dicts[0], vowels_consonants_dicts[1]))
def task_dis(size,task_list): task_num=len(task_list) task_dis_list=[] for i in range(size): task_dis_list.append([]) #print(str(task_dis_list)) for i in range(len(task_list)): for j in range(size): if i%size==j: task_dis_list[j].append(task_list[i]) #for i in range(size): # print("************"+str(i)+"************") # print(str(task_dis_list[i])) return task_dis_list #testing code if 1==0: size=12 task_list=[{0,2},{1,2},{2,2},{3,2},{4,2},{5,2},{6,2},{7,2},{8,2},{9,2},\ {10,2},{11,2},{12,2},{13,2},{14,2},{15,2},{16,2},{17,2},{18,2},{19,2}, {20,2},{21,2},{22,2},{23,2},{24,2},{25,2},{26,2},{27,2},{28,2},{29,2}, {30,2},{31,2},{32,2},{33,2},{34,2},{35,2},{36,2},{37,2},{38,2},{39,2}] task_dis_list=task_dis(size,task_list) print(str(task_dis_list)) for i in range(size): print("************"+str(i)+"************") print(str(task_dis_list[i]))
def task_dis(size, task_list): task_num = len(task_list) task_dis_list = [] for i in range(size): task_dis_list.append([]) for i in range(len(task_list)): for j in range(size): if i % size == j: task_dis_list[j].append(task_list[i]) return task_dis_list if 1 == 0: size = 12 task_list = [{0, 2}, {1, 2}, {2, 2}, {3, 2}, {4, 2}, {5, 2}, {6, 2}, {7, 2}, {8, 2}, {9, 2}, {10, 2}, {11, 2}, {12, 2}, {13, 2}, {14, 2}, {15, 2}, {16, 2}, {17, 2}, {18, 2}, {19, 2}, {20, 2}, {21, 2}, {22, 2}, {23, 2}, {24, 2}, {25, 2}, {26, 2}, {27, 2}, {28, 2}, {29, 2}, {30, 2}, {31, 2}, {32, 2}, {33, 2}, {34, 2}, {35, 2}, {36, 2}, {37, 2}, {38, 2}, {39, 2}] task_dis_list = task_dis(size, task_list) print(str(task_dis_list)) for i in range(size): print('************' + str(i) + '************') print(str(task_dis_list[i]))
''' By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? ''' p_no = 0 def is_prime(x): if x >= 2: for y in range(2,x): if not( x % y ): #reverse the modulo operation return False else: return False return True arr=[] for i in range(int(100000)): if is_prime(i)==True: p_no += 1 arr.append(i) print(arr) print ("We found " + str(p_no) + " prime numbers.")
""" By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? """ p_no = 0 def is_prime(x): if x >= 2: for y in range(2, x): if not x % y: return False else: return False return True arr = [] for i in range(int(100000)): if is_prime(i) == True: p_no += 1 arr.append(i) print(arr) print('We found ' + str(p_no) + ' prime numbers.')
class Pendulum(): """ Pendulum class implements the parameters and differential equation for a pendulum using the notation from Taylor. The class will now have the solve_ode method removed...everything else will remain the same. Parameters ---------- omega_0 : float natural frequency of the pendulum (sqrt{g/l} where l is the pendulum length) beta : float coefficient of friction gamma_ext : float amplitude of external force is gamma * omega_0**2 omega_ext : float frequency of external force phi_ext : float phase angle for external force Methods ------- dy_dt(y, t) Returns the right side of the differential equation in vector y, given time t and the corresponding value of y. driving_force(t) Returns the value of the external driving force at time t. """ def __init__(self, omega_0=1., beta=0.2, gamma_ext=0.2, omega_ext=0.689, phi_ext=0. ): self.omega_0 = omega_0 self.beta = beta self.gamma_ext = gamma_ext self.omega_ext = omega_ext self.phi_ext = phi_ext def dy_dt(self, y, t): """ This function returns the right-hand side of the diffeq: [dphi/dt d^2phi/dt^2] Parameters ---------- y : float A 2-component vector with y[0] = phi(t) and y[1] = dphi/dt t : float time """ F_ext = self.driving_force(t) return [y[1], -self.omega_0**2 * np.sin(y[0]) - 2.*self.beta * y[1] \ + F_ext] def driving_force(self, t): """ This function returns the value of the driving force at time t. """ return self.gamma_ext * self.omega_0**2 \ * np.cos(self.omega_ext*t + self.phi_ext) v_0 = np.array([10.0]) abserr = 1.e-8 relerr = 1.e-8 t_start = 0. t_end = 10. t_pts = np.linspace(t_start, t_end, 20) solution = solve_ivp(dy_dt, (t_start, t_end), v_0, t_eval=t_pts, rtol=relerr, atol=abserr)
class Pendulum: """ Pendulum class implements the parameters and differential equation for a pendulum using the notation from Taylor. The class will now have the solve_ode method removed...everything else will remain the same. Parameters ---------- omega_0 : float natural frequency of the pendulum (sqrt{g/l} where l is the pendulum length) beta : float coefficient of friction gamma_ext : float amplitude of external force is gamma * omega_0**2 omega_ext : float frequency of external force phi_ext : float phase angle for external force Methods ------- dy_dt(y, t) Returns the right side of the differential equation in vector y, given time t and the corresponding value of y. driving_force(t) Returns the value of the external driving force at time t. """ def __init__(self, omega_0=1.0, beta=0.2, gamma_ext=0.2, omega_ext=0.689, phi_ext=0.0): self.omega_0 = omega_0 self.beta = beta self.gamma_ext = gamma_ext self.omega_ext = omega_ext self.phi_ext = phi_ext def dy_dt(self, y, t): """ This function returns the right-hand side of the diffeq: [dphi/dt d^2phi/dt^2] Parameters ---------- y : float A 2-component vector with y[0] = phi(t) and y[1] = dphi/dt t : float time """ f_ext = self.driving_force(t) return [y[1], -self.omega_0 ** 2 * np.sin(y[0]) - 2.0 * self.beta * y[1] + F_ext] def driving_force(self, t): """ This function returns the value of the driving force at time t. """ return self.gamma_ext * self.omega_0 ** 2 * np.cos(self.omega_ext * t + self.phi_ext) v_0 = np.array([10.0]) abserr = 1e-08 relerr = 1e-08 t_start = 0.0 t_end = 10.0 t_pts = np.linspace(t_start, t_end, 20) solution = solve_ivp(dy_dt, (t_start, t_end), v_0, t_eval=t_pts, rtol=relerr, atol=abserr)
load("//third_party:repos/boost.bzl", "boost_repository") load("//third_party:repos/grpc.bzl", "grpc_rules_repository") load("//third_party:repos/gtest.bzl", "gtest_repository") def dependencies(excludes = []): ignores = native.existing_rules().keys() + excludes if "com_github_nelhage_rules_boost" not in ignores: boost_repository() if "rules_proto_grpc" not in ignores: grpc_rules_repository() if "gtest" not in ignores: gtest_repository(name = "gtest")
load('//third_party:repos/boost.bzl', 'boost_repository') load('//third_party:repos/grpc.bzl', 'grpc_rules_repository') load('//third_party:repos/gtest.bzl', 'gtest_repository') def dependencies(excludes=[]): ignores = native.existing_rules().keys() + excludes if 'com_github_nelhage_rules_boost' not in ignores: boost_repository() if 'rules_proto_grpc' not in ignores: grpc_rules_repository() if 'gtest' not in ignores: gtest_repository(name='gtest')
class EncodingEnum: BINARY_ENCODING = 0 BINARY_WITH_VARIABLE_LENGTH_STRINGS = 1 JSON_ENCODING = 2 JSON_COMPACT_ENCODING = 3 PROTOCOL_BUFFERS = 4
class Encodingenum: binary_encoding = 0 binary_with_variable_length_strings = 1 json_encoding = 2 json_compact_encoding = 3 protocol_buffers = 4
JS(""" __NULL_OBJECT__ = {} __concat_tables_array = function(t1, t2) for i=1,#t2 do t1[ #t1+1 ] = t2[i] end return t1 end __concat_tables = function(t1, t2) for k,v in pairs(t2) do t1[k] = v end return t1 end function table.shallow_copy(t) local t2 = {} for k,v in pairs(t) do t2[k] = v end return t2 end __test_if_true__ = function( x ) if x == true then return true elseif x == false then return false elseif x == 0 then return false elseif x == nil then return false elseif x == '' then return false elseif x.__class__ and x.__class__.__name__ == 'list' then if x.length > 0 then return true else return false end elseif x.__class__ and x.__class__.__name__ == 'dict' then if x.keys().length > 0 then return true else return false end else return true end end __set__ = function(ob, name, value) ob[ name ] = value end __get__ = function(ob, name) if name == '__call__' then if type(ob)=='function' then return ob else return ob.__call__ end elseif type(ob)=='string' then return __get__helper_string(ob,name) elseif ob.__getters__ and ob.__getters__[name] then return ob.__getters__[name]( ob ) --unbound method-- elseif ob[name]==nil and ob.__getattr__ then return ob.__getattr__( {name} ) else return ob[ name ] end end __sprintf = function(s, args) if type(args)=='table' then return string.format(s, unpack(args)) else return string.format(s, args) end end function string:to_array() local i = 1 local t = {} for c in self:gmatch('.') do t[ i ] = c i = i + 1 end return t end function string:split(sSeparator, nMax, bRegexp) assert(sSeparator ~= '') assert(nMax == nil or nMax >= 1) if sSeparator == nil then sSeparator = ' ' end local aRecord = {} if self:len() > 0 then local bPlain = not bRegexp nMax = nMax or -1 local nField=1 nStart=1 local nFirst,nLast = self:find(sSeparator, nStart, bPlain) while nFirst and nMax ~= 0 do aRecord[nField] = self:sub(nStart, nFirst-1) nField = nField+1 nStart = nLast+1 nFirst,nLast = self:find(sSeparator, nStart, bPlain) nMax = nMax-1 end aRecord[nField] = self:sub(nStart) end return aRecord end __bind_methods__ = function(object, class) for k,v in pairs( class.__attributes__ ) do if object[k] == nil then if type(v)=='function' then object[ k ] = function(_args, _kwargs) local o = {object} if _args then return v(__concat_tables_array(o, _args), _kwargs or {}) else return v(o, _kwargs or {}) end end else -- TODO class attribute should have dynamic look up. object[ k ] = v end end end for k,v in pairs( class.__bases__ ) do __bind_methods__( object, v ) end end __bind_properties__ = function(object, class) for k,v in pairs( class.__properties__ ) do assert( type(v.get)=='function' ) if object.__getters__[k] == nil then object.__getters__[k] = v.get --unbound method-- end end for k,v in pairs( class.__bases__ ) do __bind_properties__( object, v ) end end __create_class__ = function(class_name, parents, attrs, props) local class = { __bases__ = parents, __name__ = class_name, __properties__ = props, __attributes__ = attrs } function class.__call__( args, kwargs ) local object = { __class__ = class, __dict__ = 'TODO', __getters__ = {} } __bind_methods__( object, class ) __bind_properties__( object, class ) for k,v in pairs( class.__attributes__ ) do class[ k ] = v end if object.__init__ then object.__init__( args, kwargs ) end return object end return class end __add_op = function(a,b) if type(a) == 'string' then return a .. b elseif type(a) == 'table' and a.__class__ then return a.__add__({b}, {}) else return a + b end end __add__ = function(a,b) if type(a) == 'string' then return a .. b else return a + b end end """) def str(ob): with lowlevel: return tostring(ob) def int(ob): with lowlevel: return tonumber(ob) def float(ob): with lowlevel: return tonumber(ob) def len(ob): with lowlevel: if type(ob) == 'string': return string.len(ob) else: return ob.length def chr(a): with lowlevel: return string.char(a) def ord(a): with lowlevel: return string.byte(a) def getattr(ob, name): with lowlevel: return ob[name] ## could be None (nil), no good way to raise AttributeError def isinstance( ob, klass ): if ob == None: return False elif ob.__class__: if ob.__class__.__name__ == klass.__name__: return True else: return False else: return False def sum( arr ): a = 0 for b in arr: a += b return a class __iterator_string: def __init__(self, obj, index): with lowlevel: self.obj = obj self.index = index self.length = string.len(obj) def next(self): with lowlevel: index = self.index self.index += 1 return string.sub( self.obj, index+1, index+1 ) class __iterator_list: def __init__(self, obj, index): self.obj = obj self.index = index self.length = len(obj) def next(self): with lowlevel: index = self.index self.index += 1 return self.obj[...][index+1] class list: ''' Array length in Lua must be manually tracked, because a normal for loop will not properly loop over a sparse Array with nil holes. ''' def __init__(self, items, pointer=None, length=0): with lowlevel: self.length = length if type(items)=='string': self[...] = string.to_array( items ) self.length = string.len(items) elif type(items)=='table' and items.__class__ and items.__class__.__name__=='list': print('HIT TABLE!!!') elif pointer: self[...] = pointer else: self[...] = {} def __contains__(self, value): with lowlevel: for v in self[...]: if v == value: return True return False def __getitem__(self, index): with lowlevel: if index < 0: index = self.length + index return self[...][index+1] def __setitem__(self, index, value): with lowlevel: if index < 0: index = self.length + index self[...][index+1] = value def __getslice__(self, start, stop, step): if stop == None and step == None: with lowlevel: copy = table.shallow_copy( self[...] ) return list( pointer=copy, length=self.length ) elif stop < 0: ## TODO pass def __iter__(self): return __iterator_list(self, 0) def __add__(self, other): with lowlevel: ptr = table.shallow_copy( self[...] ) copy = list( pointer=ptr, length=self.length ) for item in other: copy.append( item ) return copy def append(self, item): with lowlevel: self.length += 1 self[...][ self.length ] = item def index(self, obj): with lowlevel: i = 0 while i < self.length: if self[...][i+1] == obj: return i i += 1 tuple = list ## this must come after list because list.__call__ is used directly, ## and the lua compiler can not use forward references. JS(''' __create_list = function(size) return __get__(list, "__call__")({}, {pointer={},length=size}) end __get__helper_string = function(s, name) local wrapper if name == '__getitem__' then wrapper = function(args, kwargs) return string.sub(s, args[1]+1, args[1]+1) end elseif name == '__contains__' then wrapper = function(args, kwargs) if s:find( args[1] ) then return true else return false end end elseif name == '__getslice__' then wrapper = function(args, kwargs) if args[1]==nil and args[2]==nil and args[3]==-1 then return s:reverse() end end elseif name == '__iter__' then wrapper = function(args, kwargs) return __iterator_string.__call__( {s, 0} ) end elseif name == 'upper' then wrapper = function(args, kwargs) return string.upper(s) end elseif name == 'lower' then wrapper = function(args, kwargs) return string.lower(s) end elseif name == 'split' then wrapper = function(args, kwargs) local a if args then a = s:split( args[1] ) else a = s:split() end return list.__call__( {}, {pointer=a, length=#a} ) end else print('ERROR: NotImplemented') end return wrapper end ''') def range(num, stop): """Emulates Python's range function""" if stop is not None: i = num num = stop else: i = 0 arr = [] while i < num: arr.append(i) i += 1 return arr class dict: def __init__(self, object, pointer=None): with lowlevel: self[...] = {} if pointer: self[...] = pointer elif object: for d in object: ## array self[...][ d.key ] = d.value def __getitem__(self, key): with lowlevel: return self[...][ key ] def __setitem__(self, key, value): with lowlevel: self[...][ key ] = value def keys(self): with lowlevel: ptr = [] i = 1 for k,v in pairs(self[...]): ptr[ i ] = k i = i + 1 return list( pointer=ptr, length=i-1 ) def __iter__(self): return self.keys().__iter__() def items(self): with lowlevel: ptr = [] i = 1 for k,v in pairs(self[...]): p = [k,v] item = list.__call__([], {pointer:p, length:2}) ptr[ i ] = item i = i + 1 return list( pointer=ptr, length=i-1 )
js("\n__NULL_OBJECT__ = {}\n\n__concat_tables_array = function(t1, t2)\n\tfor i=1,#t2 do\n\t\tt1[ #t1+1 ] = t2[i]\n\tend\n\treturn t1\nend\n\n__concat_tables = function(t1, t2)\n\tfor k,v in pairs(t2) do\n\t\tt1[k] = v\n\tend\n\treturn t1\nend\n\nfunction table.shallow_copy(t)\n\tlocal t2 = {}\n\tfor k,v in pairs(t) do\n\t\tt2[k] = v\n\tend\n\treturn t2\nend\n\n__test_if_true__ = function( x )\n\tif x == true then return true\n\telseif x == false then return false\n\telseif x == 0 then return false\n\telseif x == nil then return false\n\telseif x == '' then return false\n\telseif x.__class__ and x.__class__.__name__ == 'list' then\n\t\tif x.length > 0 then return true\n\t\telse return false end\n\telseif x.__class__ and x.__class__.__name__ == 'dict' then\n\t\tif x.keys().length > 0 then return true\n\t\telse return false end\n\telse\n\t\treturn true\n\tend\nend\n\n__set__ = function(ob, name, value)\n\tob[ name ] = value\nend\n\n__get__ = function(ob, name)\n\tif name == '__call__' then\n\t\tif type(ob)=='function' then\n\t\t\treturn ob\n\t\telse\n\t\t\treturn ob.__call__\n\t\tend\n\telseif type(ob)=='string' then\n\t\treturn __get__helper_string(ob,name)\n\telseif ob.__getters__ and ob.__getters__[name] then\n\t\treturn ob.__getters__[name]( ob ) --unbound method--\n\telseif ob[name]==nil and ob.__getattr__ then\n\t\treturn ob.__getattr__( {name} )\n\telse\n\t\treturn ob[ name ]\n\tend\nend\n\n__sprintf = function(s, args)\n\tif type(args)=='table' then\n\t\treturn string.format(s, unpack(args))\n\telse\n\t\treturn string.format(s, args)\n\tend\nend\n\nfunction string:to_array()\n\tlocal i = 1\n\tlocal t = {}\n\tfor c in self:gmatch('.') do\n\t\tt[ i ] = c\n\t\ti = i + 1\n\tend\n\treturn t\nend\n\nfunction string:split(sSeparator, nMax, bRegexp)\n\tassert(sSeparator ~= '')\n\tassert(nMax == nil or nMax >= 1)\n\tif sSeparator == nil then\n\t\tsSeparator = ' '\n\tend\n\n\tlocal aRecord = {}\n\n\tif self:len() > 0 then\n\t\tlocal bPlain = not bRegexp\n\t\tnMax = nMax or -1\n\n\t\tlocal nField=1 nStart=1\n\t\tlocal nFirst,nLast = self:find(sSeparator, nStart, bPlain)\n\t\twhile nFirst and nMax ~= 0 do\n\t\t\taRecord[nField] = self:sub(nStart, nFirst-1)\n\t\t\tnField = nField+1\n\t\t\tnStart = nLast+1\n\t\t\tnFirst,nLast = self:find(sSeparator, nStart, bPlain)\n\t\t\tnMax = nMax-1\n\t\tend\n\t\taRecord[nField] = self:sub(nStart)\n\tend\n\treturn aRecord\nend\n\n__bind_methods__ = function(object, class)\n\tfor k,v in pairs( class.__attributes__ ) do\n\t\tif object[k] == nil then\n\t\t\tif type(v)=='function' then\n\t\t\t\tobject[ k ] = function(_args, _kwargs)\n\t\t\t\t\tlocal o = {object}\n\t\t\t\t\tif _args then\n\t\t\t\t\t\treturn v(__concat_tables_array(o, _args), _kwargs or {})\n\t\t\t\t\telse\n\t\t\t\t\t\treturn v(o, _kwargs or {})\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\telse\n\t\t\t\t-- TODO class attribute should have dynamic look up.\n\t\t\t\tobject[ k ] = v\n\t\t\tend\n\t\tend\n\tend\n\tfor k,v in pairs( class.__bases__ ) do\n\t\t__bind_methods__( object, v )\n\tend\nend\n\n__bind_properties__ = function(object, class)\n\tfor k,v in pairs( class.__properties__ ) do\n\t\tassert( type(v.get)=='function' )\n\t\tif object.__getters__[k] == nil then\n\t\t\tobject.__getters__[k] = v.get --unbound method--\n\t\tend\n\tend\n\tfor k,v in pairs( class.__bases__ ) do\n\t\t__bind_properties__( object, v )\n\tend\nend\n\n\n__create_class__ = function(class_name, parents, attrs, props)\n\tlocal class = {\n\t\t__bases__ = parents,\n\t\t__name__ = class_name,\n\t\t__properties__ = props,\n\t\t__attributes__ = attrs\n\t}\n\tfunction class.__call__( args, kwargs )\n\t\tlocal object = {\n\t\t\t__class__ = class,\n\t\t\t__dict__ = 'TODO',\n\t\t\t__getters__ = {}\n\t\t}\n\t\t__bind_methods__( object, class )\n\t\t__bind_properties__( object, class )\n\n\t\tfor k,v in pairs( class.__attributes__ ) do\n\t\t\tclass[ k ] = v\n\t\tend\n\n\t\tif object.__init__ then\n\t\t\tobject.__init__( args, kwargs )\n\t\tend\n\t\treturn object\n\tend\n\treturn class\nend\n\n\n__add_op = function(a,b)\n\tif type(a) == 'string' then\n\t\treturn a .. b\n\telseif type(a) == 'table' and a.__class__ then\n\t\treturn a.__add__({b}, {})\n\telse\n\t\treturn a + b\n\tend\nend\n\n__add__ = function(a,b)\n\tif type(a) == 'string' then\n\t\treturn a .. b\n\telse\n\t\treturn a + b\n\tend\nend\n\n") def str(ob): with lowlevel: return tostring(ob) def int(ob): with lowlevel: return tonumber(ob) def float(ob): with lowlevel: return tonumber(ob) def len(ob): with lowlevel: if type(ob) == 'string': return string.len(ob) else: return ob.length def chr(a): with lowlevel: return string.char(a) def ord(a): with lowlevel: return string.byte(a) def getattr(ob, name): with lowlevel: return ob[name] def isinstance(ob, klass): if ob == None: return False elif ob.__class__: if ob.__class__.__name__ == klass.__name__: return True else: return False else: return False def sum(arr): a = 0 for b in arr: a += b return a class __Iterator_String: def __init__(self, obj, index): with lowlevel: self.obj = obj self.index = index self.length = string.len(obj) def next(self): with lowlevel: index = self.index self.index += 1 return string.sub(self.obj, index + 1, index + 1) class __Iterator_List: def __init__(self, obj, index): self.obj = obj self.index = index self.length = len(obj) def next(self): with lowlevel: index = self.index self.index += 1 return self.obj[...][index + 1] class List: """ Array length in Lua must be manually tracked, because a normal for loop will not properly loop over a sparse Array with nil holes. """ def __init__(self, items, pointer=None, length=0): with lowlevel: self.length = length if type(items) == 'string': self[...] = string.to_array(items) self.length = string.len(items) elif type(items) == 'table' and items.__class__ and (items.__class__.__name__ == 'list'): print('HIT TABLE!!!') elif pointer: self[...] = pointer else: self[...] = {} def __contains__(self, value): with lowlevel: for v in self[...]: if v == value: return True return False def __getitem__(self, index): with lowlevel: if index < 0: index = self.length + index return self[...][index + 1] def __setitem__(self, index, value): with lowlevel: if index < 0: index = self.length + index self[...][index + 1] = value def __getslice__(self, start, stop, step): if stop == None and step == None: with lowlevel: copy = table.shallow_copy(self[...]) return list(pointer=copy, length=self.length) elif stop < 0: pass def __iter__(self): return __iterator_list(self, 0) def __add__(self, other): with lowlevel: ptr = table.shallow_copy(self[...]) copy = list(pointer=ptr, length=self.length) for item in other: copy.append(item) return copy def append(self, item): with lowlevel: self.length += 1 self[...][self.length] = item def index(self, obj): with lowlevel: i = 0 while i < self.length: if self[...][i + 1] == obj: return i i += 1 tuple = list js('\n\n__create_list = function(size)\n\treturn __get__(list, "__call__")({}, {pointer={},length=size})\nend\n\n__get__helper_string = function(s, name)\n\tlocal wrapper\n\tif name == \'__getitem__\' then\n\t\twrapper = function(args, kwargs)\n\t\t\treturn string.sub(s, args[1]+1, args[1]+1)\n\t\tend\n\n\telseif name == \'__contains__\' then\n\t\twrapper = function(args, kwargs)\n\t\t\tif s:find( args[1] ) then return true\n\t\t\telse return false end\n\t\tend\n\n\telseif name == \'__getslice__\' then\n\t\twrapper = function(args, kwargs)\n\t\t\tif args[1]==nil and args[2]==nil and args[3]==-1 then\n\t\t\t\treturn s:reverse()\n\t\t\tend\n\t\tend\n\n\telseif name == \'__iter__\' then\n\t\twrapper = function(args, kwargs)\n\t\t\treturn __iterator_string.__call__( {s, 0} )\n\t\tend\n\n\telseif name == \'upper\' then\n\t\twrapper = function(args, kwargs)\n\t\t\treturn string.upper(s)\n\t\tend\n\telseif name == \'lower\' then\n\t\twrapper = function(args, kwargs)\n\t\t\treturn string.lower(s)\n\t\tend\n\telseif name == \'split\' then\n\t\twrapper = function(args, kwargs)\n\t\t\tlocal a\n\t\t\tif args then\n\t\t\t\ta = s:split( args[1] )\n\t\t\telse\n\t\t\t\ta = s:split()\n\t\t\tend\n\t\t\treturn list.__call__( {}, {pointer=a, length=#a} )\n\t\tend\n\telse\n\t\tprint(\'ERROR: NotImplemented\')\n\tend\n\n\treturn wrapper\nend\n') def range(num, stop): """Emulates Python's range function""" if stop is not None: i = num num = stop else: i = 0 arr = [] while i < num: arr.append(i) i += 1 return arr class Dict: def __init__(self, object, pointer=None): with lowlevel: self[...] = {} if pointer: self[...] = pointer elif object: for d in object: self[...][d.key] = d.value def __getitem__(self, key): with lowlevel: return self[...][key] def __setitem__(self, key, value): with lowlevel: self[...][key] = value def keys(self): with lowlevel: ptr = [] i = 1 for (k, v) in pairs(self[...]): ptr[i] = k i = i + 1 return list(pointer=ptr, length=i - 1) def __iter__(self): return self.keys().__iter__() def items(self): with lowlevel: ptr = [] i = 1 for (k, v) in pairs(self[...]): p = [k, v] item = list.__call__([], {pointer: p, length: 2}) ptr[i] = item i = i + 1 return list(pointer=ptr, length=i - 1)
num = int(input('Digite um numero [999 para parar]: ')) soma = 0 tot = 0 while num != 999: soma += num tot += 1 num = int(input('Digite um numero [999 para parar] : ')) print(f'{soma} e {tot}')
num = int(input('Digite um numero [999 para parar]: ')) soma = 0 tot = 0 while num != 999: soma += num tot += 1 num = int(input('Digite um numero [999 para parar] : ')) print(f'{soma} e {tot}')
_base_ = [ '../../_base_/models/faster_rcnn_r50_fpn.py', '../../_base_/datasets/waymo_detection_1280x1920.py', '../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py' ] # model model = dict( rpn_head=dict( anchor_generator=dict( type='AnchorGenerator', scales=[3], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64]),), roi_head=dict( bbox_roi_extractor=dict( type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32], finest_scale=19), bbox_head=dict(num_classes=3)) ) # data data = dict(samples_per_gpu=4) # lr is set for a batch size of 8 optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) # learning policy lr_config = dict( policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=12) # load_from = 'https://open-mmlab.s3.ap-northeast-2.amazonaws.com/mmdetection/v2.0/faster_rcnn/faster_rcnn_r50_fpn_2x_coco/faster_rcnn_r50_fpn_2x_coco_bbox_mAP-0.384_20200504_210434-a5d8aa15.pth' # noqa resume_from = 'saved_models/study/faster_rcnn_r50_fpn_fp16_4x2_1x_1280x1920_improved/epoch_10.pth' # fp16 settings fp16 = dict(loss_scale=512.)
_base_ = ['../../_base_/models/faster_rcnn_r50_fpn.py', '../../_base_/datasets/waymo_detection_1280x1920.py', '../../_base_/schedules/schedule_1x.py', '../../_base_/default_runtime.py'] model = dict(rpn_head=dict(anchor_generator=dict(type='AnchorGenerator', scales=[3], ratios=[0.5, 1.0, 2.0], strides=[4, 8, 16, 32, 64])), roi_head=dict(bbox_roi_extractor=dict(type='SingleRoIExtractor', roi_layer=dict(type='RoIAlign', output_size=7, sampling_ratio=0), out_channels=256, featmap_strides=[4, 8, 16, 32], finest_scale=19), bbox_head=dict(num_classes=3))) data = dict(samples_per_gpu=4) optimizer = dict(type='SGD', lr=0.01, momentum=0.9, weight_decay=0.0001) optimizer_config = dict(grad_clip=None) lr_config = dict(policy='step', warmup='linear', warmup_iters=500, warmup_ratio=0.001, step=[8, 11]) runner = dict(type='EpochBasedRunner', max_epochs=12) resume_from = 'saved_models/study/faster_rcnn_r50_fpn_fp16_4x2_1x_1280x1920_improved/epoch_10.pth' fp16 = dict(loss_scale=512.0)
a = 5 b = 6 c = 7.5 result = multiply(a, b, c) print(result)
a = 5 b = 6 c = 7.5 result = multiply(a, b, c) print(result)
ch=input("Enter ch = ") for i in range (0,len(ch)-1,2): if(ch[i].isalpha()): print((ch[i])*int(ch[i+1]),end="") elif(ch[i+1].isalpha()): print((ch[i+1])*int(ch[i]),end="")
ch = input('Enter ch = ') for i in range(0, len(ch) - 1, 2): if ch[i].isalpha(): print(ch[i] * int(ch[i + 1]), end='') elif ch[i + 1].isalpha(): print(ch[i + 1] * int(ch[i]), end='')
class KalmanFilter: def __init__(self, errorMeasurement, errorEstimate, q): self.errorMeasurement = errorMeasurement self.errorEstimate = errorEstimate self.q = q #covariance error self.lastEstimate = 25.0 self.currentEstimate = 25.0 def updateEstimate(self,measurement): kGain = self.errorEstimate/(self.errorEstimate+self.errorMeasurement) self.currentEstimate = self.lastEstimate + kGain*(measurement-self.lastEstimate) self.errorEstimate = (1.0-kGain)*self.errorEstimate + abs(self.lastEstimate-self.currentEstimate)*self.q self.lastEstimate=self.currentEstimate return self.currentEstimate def setLastEstimate(self,val): self.lastEstimate = val self.currentEstimate = val
class Kalmanfilter: def __init__(self, errorMeasurement, errorEstimate, q): self.errorMeasurement = errorMeasurement self.errorEstimate = errorEstimate self.q = q self.lastEstimate = 25.0 self.currentEstimate = 25.0 def update_estimate(self, measurement): k_gain = self.errorEstimate / (self.errorEstimate + self.errorMeasurement) self.currentEstimate = self.lastEstimate + kGain * (measurement - self.lastEstimate) self.errorEstimate = (1.0 - kGain) * self.errorEstimate + abs(self.lastEstimate - self.currentEstimate) * self.q self.lastEstimate = self.currentEstimate return self.currentEstimate def set_last_estimate(self, val): self.lastEstimate = val self.currentEstimate = val
''' Settings for generating synthetic images using code for Cut, Paste, and Learn Paper ''' # Paths BACKGROUND_DIR = '/scratch/jnan1/background/TRAIN' BACKGROUND_GLOB_STRING = '*.png' INVERTED_MASK = False # Set to true if white pixels represent background # Parameters for generator NUMBER_OF_WORKERS = 4 BLENDING_LIST = ['gaussian', 'none', 'box', 'motion'] # Parameters for images MIN_NO_OF_OBJECTS = 1 MAX_NO_OF_OBJECTS = 3 MIN_NO_OF_DISTRACTOR_OBJECTS = 1 MAX_NO_OF_DISTRACTOR_OBJECTS = 3 WIDTH = 960 HEIGHT = 720 OBJECT_SIZE = 256 MAX_ATTEMPTS_TO_SYNTHESIZE = 20 # Parameters for objects in images MIN_SCALE = 0.25 # min scale for scale augmentation MAX_SCALE = 0.6 # max scale for scale augmentation MAX_DEGREES = 30 # max rotation allowed during rotation augmentation MAX_TRUNCATION_FRACTION = 0 # max fraction to be truncated = MAX_TRUNCACTION_FRACTION*(WIDTH/HEIGHT) MAX_ALLOWED_IOU = 0.75 # IOU > MAX_ALLOWED_IOU is considered an occlusion MIN_WIDTH = 6 # Minimum width of object to use for data generation MIN_HEIGHT = 6 # Minimum height of object to use for data generation
""" Settings for generating synthetic images using code for Cut, Paste, and Learn Paper """ background_dir = '/scratch/jnan1/background/TRAIN' background_glob_string = '*.png' inverted_mask = False number_of_workers = 4 blending_list = ['gaussian', 'none', 'box', 'motion'] min_no_of_objects = 1 max_no_of_objects = 3 min_no_of_distractor_objects = 1 max_no_of_distractor_objects = 3 width = 960 height = 720 object_size = 256 max_attempts_to_synthesize = 20 min_scale = 0.25 max_scale = 0.6 max_degrees = 30 max_truncation_fraction = 0 max_allowed_iou = 0.75 min_width = 6 min_height = 6
# https://adventofcode.com/2019/day/4 def is_valid_password(i: int, version: int = 1) -> bool: i_digits = [int(digit) for digit in str(i)] is_increasing, repeats = True, False for k in range(len(i_digits) - 1): if i_digits[k] > i_digits[k+1]: is_increasing = False elif version == 1 and i_digits[k] == i_digits[k+1]: repeats = True elif version == 2 and i_digits[k] == i_digits[k+1]: if 0 < k < len(i_digits) - 2: valid_repeat = ((i_digits[k-1] != i_digits[k]) and (i_digits[k+1] != i_digits[k+2])) elif k == 0: valid_repeat = i_digits[k+1] != i_digits[k+2] elif k == len(i_digits) - 2: valid_repeat = i_digits[k-1] != i_digits[k] else: raise ValueError('k takes on an unexpected value') if valid_repeat: repeats = True return is_increasing and repeats def main(code_range: iter): password_count = [0, 0] for i in code_range: password_count[0] += int(is_valid_password(i, version=1)) password_count[1] += int(is_valid_password(i, version=2)) print(password_count[0]) print(password_count[1]) if __name__ == '__main__': possible_range = range(156218, 652527 + 1) main(possible_range)
def is_valid_password(i: int, version: int=1) -> bool: i_digits = [int(digit) for digit in str(i)] (is_increasing, repeats) = (True, False) for k in range(len(i_digits) - 1): if i_digits[k] > i_digits[k + 1]: is_increasing = False elif version == 1 and i_digits[k] == i_digits[k + 1]: repeats = True elif version == 2 and i_digits[k] == i_digits[k + 1]: if 0 < k < len(i_digits) - 2: valid_repeat = i_digits[k - 1] != i_digits[k] and i_digits[k + 1] != i_digits[k + 2] elif k == 0: valid_repeat = i_digits[k + 1] != i_digits[k + 2] elif k == len(i_digits) - 2: valid_repeat = i_digits[k - 1] != i_digits[k] else: raise value_error('k takes on an unexpected value') if valid_repeat: repeats = True return is_increasing and repeats def main(code_range: iter): password_count = [0, 0] for i in code_range: password_count[0] += int(is_valid_password(i, version=1)) password_count[1] += int(is_valid_password(i, version=2)) print(password_count[0]) print(password_count[1]) if __name__ == '__main__': possible_range = range(156218, 652527 + 1) main(possible_range)
""" Module: 'pybricks.uev3dev.sound' on LEGO EV3 v1.0.0 """ # MCU: sysname=ev3, nodename=ev3, release=('v1.0.0',), version=('0.0.0',), machine=ev3 # Stubber: 1.3.2 INT32 = 671088640 class Mixer: '' _attach = None _close = None _find_selem = None _load = None _open = None _selem_get_playback_volume_range = None _selem_id_set_index = None _selem_id_set_name = None _selem_id_sizeof = None _selem_register = None _selem_set_playback_volume_all = None def close(): pass def set_beep_volume(): pass def set_pcm_volume(): pass class PCM: '' _ACCESS_RW_INTERLEAVED = 3 _FORMAT_S16_LE = 2 _STREAM_PLAYBACK = 0 _close = None _drain = None _drop = None _hw_params = None _hw_params_any = None _hw_params_get_period_size = None _hw_params_set_access = None _hw_params_set_channels = None _hw_params_set_format = None _hw_params_set_rate = None _hw_params_sizeof = None _open = None _prepare = None _writei = None def close(): pass def play(): pass class PlayType: '' ONCE = 1 REPEAT = 2 WAIT = 0 class Sound: '' def _beep(): pass def _play_tone(): pass def _stop(): pass def play_file(): pass def play_note(): pass def play_tone(): pass def stop(): pass class SoundFile: '' def _cancel_token(): pass _read = None def close(): pass class SoundFileError: '' class Timeout: '' _ONE = None def _run(): pass def cancel(): pass def close(): pass def start(): pass def wait(): pass UINT16 = 268435456 UINT32 = 536870912 UINT64 = 805306368 _BEEP_DEV = '/dev/input/by-path/platform-sound-event' class _CancelToken: '' def cancel(): pass _EV_SND = 18 _NOTES = None _SEEK_SET = 0 _SF_INFO = None _SMF_READ = 16 _SND_TONE = 2 _input_event = None _libsndfile = None _sf_close = None _sf_count_t = 805306368 _sf_open = None _sf_readf_short = None _sf_seek = None _sf_strerror = None _thread = None def addressof(): pass def calcsize(): pass def debug_print(): pass ffilib = None os = None def pack(): pass def sizeof(): pass def sleep(): pass def sleep_ms(): pass class struct: '' def unpack(): pass
""" Module: 'pybricks.uev3dev.sound' on LEGO EV3 v1.0.0 """ int32 = 671088640 class Mixer: """""" _attach = None _close = None _find_selem = None _load = None _open = None _selem_get_playback_volume_range = None _selem_id_set_index = None _selem_id_set_name = None _selem_id_sizeof = None _selem_register = None _selem_set_playback_volume_all = None def close(): pass def set_beep_volume(): pass def set_pcm_volume(): pass class Pcm: """""" _access_rw_interleaved = 3 _format_s16_le = 2 _stream_playback = 0 _close = None _drain = None _drop = None _hw_params = None _hw_params_any = None _hw_params_get_period_size = None _hw_params_set_access = None _hw_params_set_channels = None _hw_params_set_format = None _hw_params_set_rate = None _hw_params_sizeof = None _open = None _prepare = None _writei = None def close(): pass def play(): pass class Playtype: """""" once = 1 repeat = 2 wait = 0 class Sound: """""" def _beep(): pass def _play_tone(): pass def _stop(): pass def play_file(): pass def play_note(): pass def play_tone(): pass def stop(): pass class Soundfile: """""" def _cancel_token(): pass _read = None def close(): pass class Soundfileerror: """""" class Timeout: """""" _one = None def _run(): pass def cancel(): pass def close(): pass def start(): pass def wait(): pass uint16 = 268435456 uint32 = 536870912 uint64 = 805306368 _beep_dev = '/dev/input/by-path/platform-sound-event' class _Canceltoken: """""" def cancel(): pass _ev_snd = 18 _notes = None _seek_set = 0 _sf_info = None _smf_read = 16 _snd_tone = 2 _input_event = None _libsndfile = None _sf_close = None _sf_count_t = 805306368 _sf_open = None _sf_readf_short = None _sf_seek = None _sf_strerror = None _thread = None def addressof(): pass def calcsize(): pass def debug_print(): pass ffilib = None os = None def pack(): pass def sizeof(): pass def sleep(): pass def sleep_ms(): pass class Struct: """""" def unpack(): pass
""" Fill out the file src/visualization/visualize.py with this (as minimum, feel free to add more vizualizations) loads a pre-trained network, extracts some intermediate representation of the data (your training set) from your cnn. This could be the features just before the final classification layer Visualize features in a 2D space using t-SNE to do the dimensionality reduction save the visualization to a file in the reports/figures/ folder """
""" Fill out the file src/visualization/visualize.py with this (as minimum, feel free to add more vizualizations) loads a pre-trained network, extracts some intermediate representation of the data (your training set) from your cnn. This could be the features just before the final classification layer Visualize features in a 2D space using t-SNE to do the dimensionality reduction save the visualization to a file in the reports/figures/ folder """
def astore_url(package, uid, instance = "https://astore.corp.enfabrica.net"): """Returns a URL for a particular package version from astore.""" if not package.startswith("/"): package = "/" + package return "{}/d{}?u={}".format( instance, package, uid, ) def _astore_upload(ctx): push = ctx.actions.declare_file("{}.sh".format(ctx.attr.name)) if ctx.attr.dir and ctx.attr.file: fail("in '%s' rule for an astore_upload in %s - you can only set dir or file, not both" % (ctx.attr.name, ctx.build_file_path), "dir") inputs = [ctx.executable._astore_client] targets = [] for target in ctx.attr.targets: targets.extend([t.short_path for t in target.files.to_list()]) inputs.extend([f for f in target.files.to_list()]) template = ctx.file._astore_upload_file if ctx.attr.dir: template = ctx.file._astore_upload_dir ctx.actions.expand_template( template = template, output = push, substitutions = { "{astore}": ctx.executable._astore_client.short_path, "{targets}": " ".join(targets), "{file}": ctx.attr.file, "{dir}": ctx.attr.dir, }, is_executable = True, ) return [DefaultInfo(executable = push, runfiles = ctx.runfiles(inputs))] astore_upload = rule( implementation = _astore_upload, attrs = { "targets": attr.label_list(allow_files = True, providers = [DefaultInfo], mandatory = True), "dir": attr.string( doc = "All the targets outputs will be uploaded as different files in an astore directory.", ), "file": attr.string( doc = "All the targets outputs will be uploaded as the same file in an astore directory. " + "This is useful when you have multiple targets to build the same binary for different " + "architectures or operating systems.", ), "_astore_upload_file": attr.label( default = Label("//bazel/astore:astore_upload_file.sh"), allow_single_file = True, ), "_astore_upload_dir": attr.label( default = Label("//bazel/astore:astore_upload_dir.sh"), allow_single_file = True, ), "_astore_client": attr.label( default = Label("//astore/client:astore"), allow_single_file = True, executable = True, cfg = "host", ), }, executable = True, doc = """Uploads artifacts to an artifact store - astore. With this rule, you can easily upload the output of a build rule to an artifact store.""", ) def _astore_download(ctx): output = ctx.actions.declare_file(ctx.attr.download_src.split("/")[-1]) command = ("%s download --no-progress -o %s %s" % (ctx.executable._astore_client.path, output.path, ctx.attr.download_src)) if ctx.attr.arch: command += " -a " + ctx.attr.arch ctx.actions.run_shell( command = command, tools = [ctx.executable._astore_client], outputs = [output], execution_requirements = { # We can't run these remotely since remote workers won't have # credentials to fetch from astore. # We should also avoid remotely caching since: # * this means we need to give individuals permissions to remotely # cache local actions, which we currently don't do # * we might spend lots of disk/network caching astore artifacts # remotely "no-remote": "Don't run remotely or cache remotely", "requires-network": "Downloads from astore", "no-cache": "Not hermetic, since it doesn't refer to packages by hash", }, ) return [DefaultInfo(files = depset([output]))] astore_download = rule( implementation = _astore_download, attrs = { "download_src": attr.string( doc = "Provided the full path, download a file from astore.", mandatory = True, ), "arch": attr.string( doc = "Architecture to download the file for.", ), "_astore_client": attr.label( default = Label("//astore/client:astore"), allow_single_file = True, executable = True, cfg = "host", ), }, doc = """Downloads artifacts from artifact store - astore. With this rule, you can easily download files from an artifact store.""", ) def astore_download_and_extract(ctx, digest, stripPrefix): """Fetch and extract a package from astore. This method downloads a package stored as an archive in astore, verifies the sha256 digest provided by calling rules, and strips out any archive path components provided by the caller. This function is only meant to be used by Bazel repository rules and they do not maintain a dependency graph and the ctx object is different than the ones used with regular rules. """ f = ctx.path(ctx.attr.path.split("/")[-1]) # Download archive enkit_args = [ "enkit", "astore", "download", "--force-uid", ctx.attr.uid, "--output", f, "--overwrite", ] res = ctx.execute(enkit_args, timeout = 60) if res.return_code: fail("Astore download failed\nArgs: {}\nStdout:\n{}\nStderr:\n{}\n".format( enkit_args, res.stdout, res.stderr, )) # Check digest of archive checksum_args = ["sha256sum", f] res = ctx.execute(checksum_args, timeout = 10) if res.return_code: fail("Failed to calculate checksum\nArgs: {}\nStdout:\n{}\nStderr:\n{}\n".format( checksum_args, res.stdout, res.stderr, )) got_digest = res.stdout.strip().split(" ")[0] if got_digest != digest: fail("WORKSPACE repository {}: Got digest {}; expected digest {}".format( ctx.attr.name, got_digest, digest, )) ctx.extract( archive = f, output = ".", stripPrefix = stripPrefix, ) ctx.delete(f) if hasattr(ctx.attr, "build") and ctx.attr.build: ctx.template("BUILD.bazel", ctx.attr.build) # This wrapper is in place to allow a rolling upgrade across Enkit and the # external repositories which consume the kernel_tree_version rule defined in # //enkit/linux/defs.bzl, which uses "sha256" as the attribute name instead of # "digest". def _astore_download_and_extract_impl(ctx): astore_download_and_extract(ctx, ctx.attr.digest, ctx.attr.strip_prefix) astore_package = repository_rule( implementation = _astore_download_and_extract_impl, attrs = { "build": attr.label( doc = "An optional BUILD file to copy in the unpacked tree.", allow_single_file = True, ), "path": attr.string( doc = "Path to the object in astore.", mandatory = True, ), "uid": attr.string( doc = "Astore UID of the desired version of the object.", mandatory = True, ), "digest": attr.string( doc = "SHA256 digest of the object.", mandatory = True, ), "strip_prefix": attr.string( doc = "Optional path prefix to strip out of the archive.", ), }, )
def astore_url(package, uid, instance='https://astore.corp.enfabrica.net'): """Returns a URL for a particular package version from astore.""" if not package.startswith('/'): package = '/' + package return '{}/d{}?u={}'.format(instance, package, uid) def _astore_upload(ctx): push = ctx.actions.declare_file('{}.sh'.format(ctx.attr.name)) if ctx.attr.dir and ctx.attr.file: fail("in '%s' rule for an astore_upload in %s - you can only set dir or file, not both" % (ctx.attr.name, ctx.build_file_path), 'dir') inputs = [ctx.executable._astore_client] targets = [] for target in ctx.attr.targets: targets.extend([t.short_path for t in target.files.to_list()]) inputs.extend([f for f in target.files.to_list()]) template = ctx.file._astore_upload_file if ctx.attr.dir: template = ctx.file._astore_upload_dir ctx.actions.expand_template(template=template, output=push, substitutions={'{astore}': ctx.executable._astore_client.short_path, '{targets}': ' '.join(targets), '{file}': ctx.attr.file, '{dir}': ctx.attr.dir}, is_executable=True) return [default_info(executable=push, runfiles=ctx.runfiles(inputs))] astore_upload = rule(implementation=_astore_upload, attrs={'targets': attr.label_list(allow_files=True, providers=[DefaultInfo], mandatory=True), 'dir': attr.string(doc='All the targets outputs will be uploaded as different files in an astore directory.'), 'file': attr.string(doc='All the targets outputs will be uploaded as the same file in an astore directory. ' + 'This is useful when you have multiple targets to build the same binary for different ' + 'architectures or operating systems.'), '_astore_upload_file': attr.label(default=label('//bazel/astore:astore_upload_file.sh'), allow_single_file=True), '_astore_upload_dir': attr.label(default=label('//bazel/astore:astore_upload_dir.sh'), allow_single_file=True), '_astore_client': attr.label(default=label('//astore/client:astore'), allow_single_file=True, executable=True, cfg='host')}, executable=True, doc='Uploads artifacts to an artifact store - astore.\n\nWith this rule, you can easily upload the output of a build rule\nto an artifact store.') def _astore_download(ctx): output = ctx.actions.declare_file(ctx.attr.download_src.split('/')[-1]) command = '%s download --no-progress -o %s %s' % (ctx.executable._astore_client.path, output.path, ctx.attr.download_src) if ctx.attr.arch: command += ' -a ' + ctx.attr.arch ctx.actions.run_shell(command=command, tools=[ctx.executable._astore_client], outputs=[output], execution_requirements={'no-remote': "Don't run remotely or cache remotely", 'requires-network': 'Downloads from astore', 'no-cache': "Not hermetic, since it doesn't refer to packages by hash"}) return [default_info(files=depset([output]))] astore_download = rule(implementation=_astore_download, attrs={'download_src': attr.string(doc='Provided the full path, download a file from astore.', mandatory=True), 'arch': attr.string(doc='Architecture to download the file for.'), '_astore_client': attr.label(default=label('//astore/client:astore'), allow_single_file=True, executable=True, cfg='host')}, doc='Downloads artifacts from artifact store - astore.\n\nWith this rule, you can easily download\nfiles from an artifact store.') def astore_download_and_extract(ctx, digest, stripPrefix): """Fetch and extract a package from astore. This method downloads a package stored as an archive in astore, verifies the sha256 digest provided by calling rules, and strips out any archive path components provided by the caller. This function is only meant to be used by Bazel repository rules and they do not maintain a dependency graph and the ctx object is different than the ones used with regular rules. """ f = ctx.path(ctx.attr.path.split('/')[-1]) enkit_args = ['enkit', 'astore', 'download', '--force-uid', ctx.attr.uid, '--output', f, '--overwrite'] res = ctx.execute(enkit_args, timeout=60) if res.return_code: fail('Astore download failed\nArgs: {}\nStdout:\n{}\nStderr:\n{}\n'.format(enkit_args, res.stdout, res.stderr)) checksum_args = ['sha256sum', f] res = ctx.execute(checksum_args, timeout=10) if res.return_code: fail('Failed to calculate checksum\nArgs: {}\nStdout:\n{}\nStderr:\n{}\n'.format(checksum_args, res.stdout, res.stderr)) got_digest = res.stdout.strip().split(' ')[0] if got_digest != digest: fail('WORKSPACE repository {}: Got digest {}; expected digest {}'.format(ctx.attr.name, got_digest, digest)) ctx.extract(archive=f, output='.', stripPrefix=stripPrefix) ctx.delete(f) if hasattr(ctx.attr, 'build') and ctx.attr.build: ctx.template('BUILD.bazel', ctx.attr.build) def _astore_download_and_extract_impl(ctx): astore_download_and_extract(ctx, ctx.attr.digest, ctx.attr.strip_prefix) astore_package = repository_rule(implementation=_astore_download_and_extract_impl, attrs={'build': attr.label(doc='An optional BUILD file to copy in the unpacked tree.', allow_single_file=True), 'path': attr.string(doc='Path to the object in astore.', mandatory=True), 'uid': attr.string(doc='Astore UID of the desired version of the object.', mandatory=True), 'digest': attr.string(doc='SHA256 digest of the object.', mandatory=True), 'strip_prefix': attr.string(doc='Optional path prefix to strip out of the archive.')})
# -*- coding: utf-8 -*- """ Datary Api python sdk Operations Limits files. """ class DataryOperationLimits(): """ Datary OperationLimits module class """ _DEFAULT_LIMITED_DATARY_SIZE = 9500000
""" Datary Api python sdk Operations Limits files. """ class Dataryoperationlimits: """ Datary OperationLimits module class """ _default_limited_datary_size = 9500000
#Function which finds 45 minutes before current time def alarm_clock(h, m): #Finding total minutes passed total_minutes = h * 60 + m ans = [] #Subtracting 45 minutes if total_minutes >= 45: answer_minutes = total_minutes - 45 else: answer_minutes = total_minutes - 45 + 1440 #Finding answer hours, and minutes ans += [answer_minutes // 60, answer_minutes % 60] #Returning value return ans #Input part H, M = map(int, input().split()) answer_list = [] #Applying algorithm answer_list = alarm_clock(H, M) #Output part for i in range(len(answer_list)): print(answer_list[i], end = " ") print()
def alarm_clock(h, m): total_minutes = h * 60 + m ans = [] if total_minutes >= 45: answer_minutes = total_minutes - 45 else: answer_minutes = total_minutes - 45 + 1440 ans += [answer_minutes // 60, answer_minutes % 60] return ans (h, m) = map(int, input().split()) answer_list = [] answer_list = alarm_clock(H, M) for i in range(len(answer_list)): print(answer_list[i], end=' ') print()
# -*- coding: utf-8 -*- """ Created on Thu Oct 25 22:37:47 2018 @author: JinJheng """ def compute(): x=int(input()) if x<=1: print('Not Prime') else: for i in range(2,x+1): if x%i==0: print('Not Prime') else: print('Prime') break compute()
""" Created on Thu Oct 25 22:37:47 2018 @author: JinJheng """ def compute(): x = int(input()) if x <= 1: print('Not Prime') else: for i in range(2, x + 1): if x % i == 0: print('Not Prime') else: print('Prime') break compute()
# -*- coding: utf-8 -*- """ Created on Wed Dec 13 17:02:29 2017 @author: taichi """ file = open("sample_data\poem.txt", "a" ); file.write("How can a clam cram in a clean cream can?") file.close()
""" Created on Wed Dec 13 17:02:29 2017 @author: taichi """ file = open('sample_data\\poem.txt', 'a') file.write('How can a clam cram in a clean cream can?') file.close()
class TypeValidator(object): def __init__(self, *types, **options): self.types = types self.exclude = options.get('exclude') def __call__(self, value): if self.exclude is not None and isinstance(value, self.exclude): return False if not isinstance(value, self.types): return False return True class AttributeValidator(object): def __init__(self, attribute): self.attribute = attribute def __call__(self, value): if not hasattr(value, self.attribute): return False return True
class Typevalidator(object): def __init__(self, *types, **options): self.types = types self.exclude = options.get('exclude') def __call__(self, value): if self.exclude is not None and isinstance(value, self.exclude): return False if not isinstance(value, self.types): return False return True class Attributevalidator(object): def __init__(self, attribute): self.attribute = attribute def __call__(self, value): if not hasattr(value, self.attribute): return False return True
class ImageArea: def __init__(self, width, height): self.width = width self.height = height def get_area(self): area = self.width * self.height return area def __gt__(self, other): return self.get_area() > other.get_area() def __ge__(self, other): return self.get_area() >= other.get_area() def __lt__(self, other): return self.get_area() < other.get_area() def __le__(self, other): return self.get_area() <= other.get_area() def __eq__(self, other): return self.get_area() == other.get_area() def __ne__(self, other): return self.get_area() != other.get_area() image_one = ImageArea(10, 10) image_two = ImageArea(10, 10) print(image_one < image_two) print(image_one <= image_two) print(image_one > image_two) print(image_one >= image_two) print(image_one == image_two) print(image_one != image_two)
class Imagearea: def __init__(self, width, height): self.width = width self.height = height def get_area(self): area = self.width * self.height return area def __gt__(self, other): return self.get_area() > other.get_area() def __ge__(self, other): return self.get_area() >= other.get_area() def __lt__(self, other): return self.get_area() < other.get_area() def __le__(self, other): return self.get_area() <= other.get_area() def __eq__(self, other): return self.get_area() == other.get_area() def __ne__(self, other): return self.get_area() != other.get_area() image_one = image_area(10, 10) image_two = image_area(10, 10) print(image_one < image_two) print(image_one <= image_two) print(image_one > image_two) print(image_one >= image_two) print(image_one == image_two) print(image_one != image_two)
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: found = {} max_length = 0 start_pos = -1 for pos, char in enumerate(s): if char in found and start_pos <= found[char]: start_pos = found[char] else: max_length = max(max_length, pos - start_pos) found[char] = pos return max_length
class Solution: def length_of_longest_substring(self, s: str) -> int: found = {} max_length = 0 start_pos = -1 for (pos, char) in enumerate(s): if char in found and start_pos <= found[char]: start_pos = found[char] else: max_length = max(max_length, pos - start_pos) found[char] = pos return max_length
try: raise ArithmeticError except Exception: print("Caught ArithmeticError via Exception") try: raise ArithmeticError except ArithmeticError: print("Caught ArithmeticError") try: raise AssertionError except Exception: print("Caught AssertionError via Exception") try: raise AssertionError except AssertionError: print("Caught AssertionError") try: raise AttributeError except Exception: print("Caught AttributeError via Exception") try: raise AttributeError except AttributeError: print("Caught AttributeError") #try: # raise BufferError #except Exception: # print("Caught BufferError via Exception") #try: # raise BufferError #except BufferError: # print("Caught BufferError") #try: # raise BytesWarning #except Warning: # print("Caught BytesWarning via Warning") #try: # raise BytesWarning #except BytesWarning: # print("Caught BytesWarning") #try: # raise DeprecationWarning #except Warning: # print("Caught DeprecationWarning via Warning") #try: # raise DeprecationWarning #except DeprecationWarning: # print("Caught DeprecationWarning") try: raise EOFError except Exception: print("Caught EOFError via Exception") try: raise EOFError except EOFError: print("Caught EOFError") #try: # raise EnvironmentError #except Exception: # print("Caught EnvironmentError via Exception") #try: # raise EnvironmentError #except EnvironmentError: # print("Caught EnvironmentError") try: raise Exception except BaseException: print("Caught Exception via BaseException") try: raise Exception except Exception: print("Caught Exception") #try: # raise FloatingPointError #except ArithmeticError: # print("Caught FloatingPointError via ArithmeticError") #try: # raise FloatingPointError #except FloatingPointError: # print("Caught FloatingPointError") #try: # raise FutureWarning #except Warning: # print("Caught FutureWarning via Warning") #try: # raise FutureWarning #except FutureWarning: # print("Caught FutureWarning") #try: # raise IOError #except Exception: # print("Caught IOError via Exception") #try: # raise IOError #except IOError: # print("Caught IOError") try: raise ImportError except Exception: print("Caught ImportError via Exception") try: raise ImportError except ImportError: print("Caught ImportError") #try: # raise ImportWarning #except Warning: # print("Caught ImportWarning via Warning") #try: # raise ImportWarning #except ImportWarning: # print("Caught ImportWarning") try: raise IndentationError except SyntaxError: print("Caught IndentationError via SyntaxError") try: raise IndentationError except IndentationError: print("Caught IndentationError") try: raise IndexError except LookupError: print("Caught IndexError via LookupError") try: raise IndexError except IndexError: print("Caught IndexError") try: raise KeyError except LookupError: print("Caught KeyError via LookupError") try: raise KeyError except KeyError: print("Caught KeyError") try: raise LookupError except Exception: print("Caught LookupError via Exception") try: raise LookupError except LookupError: print("Caught LookupError") try: raise MemoryError except Exception: print("Caught MemoryError via Exception") try: raise MemoryError except MemoryError: print("Caught MemoryError") try: raise NameError except Exception: print("Caught NameError via Exception") try: raise NameError except NameError: print("Caught NameError") try: raise NotImplementedError except RuntimeError: print("Caught NotImplementedError via RuntimeError") try: raise NotImplementedError except NotImplementedError: print("Caught NotImplementedError") try: raise OSError except Exception: print("Caught OSError via Exception") try: raise OSError except OSError: print("Caught OSError") try: raise OverflowError except ArithmeticError: print("Caught OverflowError via ArithmeticError") try: raise OverflowError except OverflowError: print("Caught OverflowError") #try: # raise PendingDeprecationWarning #except Warning: # print("Caught PendingDeprecationWarning via Warning") #try: # raise PendingDeprecationWarning #except PendingDeprecationWarning: # print("Caught PendingDeprecationWarning") #try: # raise ReferenceError #except Exception: # print("Caught ReferenceError via Exception") #try: # raise ReferenceError #except ReferenceError: # print("Caught ReferenceError") #try: # raise ResourceWarning #except Warning: # print("Caught ResourceWarning via Warning") #try: # raise ResourceWarning #except ResourceWarning: # print("Caught ResourceWarning") try: raise RuntimeError except Exception: print("Caught RuntimeError via Exception") try: raise RuntimeError except RuntimeError: print("Caught RuntimeError") #try: # raise RuntimeWarning #except Warning: # print("Caught RuntimeWarning via Warning") #try: # raise RuntimeWarning #except RuntimeWarning: # print("Caught RuntimeWarning") try: raise SyntaxError except Exception: print("Caught SyntaxError via Exception") try: raise SyntaxError except SyntaxError: print("Caught SyntaxError") #try: # raise SyntaxWarning #except Warning: # print("Caught SyntaxWarning via Warning") #try: # raise SyntaxWarning #except SyntaxWarning: # print("Caught SyntaxWarning") try: raise SystemError except Exception: print("Caught SystemError via Exception") try: raise SystemError except SystemError: print("Caught SystemError") #try: # raise TabError #except IndentationError: # print("Caught TabError via IndentationError") #try: # raise TabError #except TabError: # print("Caught TabError") try: raise TypeError except Exception: print("Caught TypeError via Exception") try: raise TypeError except TypeError: print("Caught TypeError") #try: # raise UnboundLocalError #except NameError: # print("Caught UnboundLocalError via NameError") #try: # raise UnboundLocalError #except UnboundLocalError: # print("Caught UnboundLocalError") #try: # raise UserWarning #except Warning: # print("Caught UserWarning via Warning") #try: # raise UserWarning #except UserWarning: # print("Caught UserWarning") try: raise ValueError except Exception: print("Caught ValueError via Exception") try: raise ValueError except ValueError: print("Caught ValueError") #try: # raise Warning #except Exception: # print("Caught Warning via Exception") #try: # raise Warning #except Warning: # print("Caught Warning") try: raise ZeroDivisionError except ArithmeticError: print("Caught ZeroDivisionError via ArithmeticError") try: raise ZeroDivisionError except ZeroDivisionError: print("Caught ZeroDivisionError")
try: raise ArithmeticError except Exception: print('Caught ArithmeticError via Exception') try: raise ArithmeticError except ArithmeticError: print('Caught ArithmeticError') try: raise AssertionError except Exception: print('Caught AssertionError via Exception') try: raise AssertionError except AssertionError: print('Caught AssertionError') try: raise AttributeError except Exception: print('Caught AttributeError via Exception') try: raise AttributeError except AttributeError: print('Caught AttributeError') try: raise EOFError except Exception: print('Caught EOFError via Exception') try: raise EOFError except EOFError: print('Caught EOFError') try: raise Exception except BaseException: print('Caught Exception via BaseException') try: raise Exception except Exception: print('Caught Exception') try: raise ImportError except Exception: print('Caught ImportError via Exception') try: raise ImportError except ImportError: print('Caught ImportError') try: raise IndentationError except SyntaxError: print('Caught IndentationError via SyntaxError') try: raise IndentationError except IndentationError: print('Caught IndentationError') try: raise IndexError except LookupError: print('Caught IndexError via LookupError') try: raise IndexError except IndexError: print('Caught IndexError') try: raise KeyError except LookupError: print('Caught KeyError via LookupError') try: raise KeyError except KeyError: print('Caught KeyError') try: raise LookupError except Exception: print('Caught LookupError via Exception') try: raise LookupError except LookupError: print('Caught LookupError') try: raise MemoryError except Exception: print('Caught MemoryError via Exception') try: raise MemoryError except MemoryError: print('Caught MemoryError') try: raise NameError except Exception: print('Caught NameError via Exception') try: raise NameError except NameError: print('Caught NameError') try: raise NotImplementedError except RuntimeError: print('Caught NotImplementedError via RuntimeError') try: raise NotImplementedError except NotImplementedError: print('Caught NotImplementedError') try: raise OSError except Exception: print('Caught OSError via Exception') try: raise OSError except OSError: print('Caught OSError') try: raise OverflowError except ArithmeticError: print('Caught OverflowError via ArithmeticError') try: raise OverflowError except OverflowError: print('Caught OverflowError') try: raise RuntimeError except Exception: print('Caught RuntimeError via Exception') try: raise RuntimeError except RuntimeError: print('Caught RuntimeError') try: raise SyntaxError except Exception: print('Caught SyntaxError via Exception') try: raise SyntaxError except SyntaxError: print('Caught SyntaxError') try: raise SystemError except Exception: print('Caught SystemError via Exception') try: raise SystemError except SystemError: print('Caught SystemError') try: raise TypeError except Exception: print('Caught TypeError via Exception') try: raise TypeError except TypeError: print('Caught TypeError') try: raise ValueError except Exception: print('Caught ValueError via Exception') try: raise ValueError except ValueError: print('Caught ValueError') try: raise ZeroDivisionError except ArithmeticError: print('Caught ZeroDivisionError via ArithmeticError') try: raise ZeroDivisionError except ZeroDivisionError: print('Caught ZeroDivisionError')
# The directory where jobs are stored job_directory = "/fred/oz988/gwcloud/jobs/" # Format submission script for specified scheduler. scheduler = "slurm" # Environment scheduler sources during runtime scheduler_env = "/fred/oz988/gwcloud/gwcloud_job_client/bundles/unpacked/fbc9f7c0815f1a83b0de36f957351c93797b2049/venv/bin/activate"
job_directory = '/fred/oz988/gwcloud/jobs/' scheduler = 'slurm' scheduler_env = '/fred/oz988/gwcloud/gwcloud_job_client/bundles/unpacked/fbc9f7c0815f1a83b0de36f957351c93797b2049/venv/bin/activate'
# Node: Gate G102 (1096088604) # http://www.openstreetmap.org/node/1096088604 assert_has_feature( 16, 10487, 25366, 'pois', { 'id': 1096088604, 'kind': 'aeroway_gate' }) # Node: Gate 1 (2618197593) # http://www.openstreetmap.org/node/2618197593 assert_has_feature( 16, 10309, 22665, 'pois', { 'id': 2618197593, 'kind': 'gate', 'aeroway': type(None) }) # Node: Lone Star Sports # http://www.openstreetmap.org/node/2122898936 assert_has_feature( 16, 13462, 24933, 'pois', { 'id': 2122898936, 'kind': 'ski_rental' }) # http://www.openstreetmap.org/way/52497271 assert_has_feature( 16, 10566, 25429, 'landuse', { 'id': 52497271, 'kind': 'wood' }) # http://www.openstreetmap.org/way/207859675 assert_has_feature( 16, 11306, 26199, 'landuse', { 'id': 207859675, 'kind': 'wood' }) # http://www.openstreetmap.org/way/417405367 assert_has_feature( 16, 10480, 25323, 'landuse', { 'id': 417405367, 'kind': 'natural_wood' }) # http://www.openstreetmap.org/way/422270533 assert_has_feature( 16, 10476, 25324, 'landuse', { 'id': 422270533, 'kind': 'forest' }) # http://www.openstreetmap.org/way/95360670 assert_has_feature( 16, 17780, 27428, 'landuse', { 'id': 95360670, 'kind': 'natural_forest' }) # Way: Stables & Equestrian Area (393312618) # http://www.openstreetmap.org/way/393312618 assert_has_feature( 16, 10294, 25113, 'landuse', { 'id': 393312618, 'kind': 'park' }) # http://www.openstreetmap.org/way/29191880 assert_has_feature( 16, 12393, 26315, 'landuse', { 'id': 29191880, 'kind': 'natural_park' })
assert_has_feature(16, 10487, 25366, 'pois', {'id': 1096088604, 'kind': 'aeroway_gate'}) assert_has_feature(16, 10309, 22665, 'pois', {'id': 2618197593, 'kind': 'gate', 'aeroway': type(None)}) assert_has_feature(16, 13462, 24933, 'pois', {'id': 2122898936, 'kind': 'ski_rental'}) assert_has_feature(16, 10566, 25429, 'landuse', {'id': 52497271, 'kind': 'wood'}) assert_has_feature(16, 11306, 26199, 'landuse', {'id': 207859675, 'kind': 'wood'}) assert_has_feature(16, 10480, 25323, 'landuse', {'id': 417405367, 'kind': 'natural_wood'}) assert_has_feature(16, 10476, 25324, 'landuse', {'id': 422270533, 'kind': 'forest'}) assert_has_feature(16, 17780, 27428, 'landuse', {'id': 95360670, 'kind': 'natural_forest'}) assert_has_feature(16, 10294, 25113, 'landuse', {'id': 393312618, 'kind': 'park'}) assert_has_feature(16, 12393, 26315, 'landuse', {'id': 29191880, 'kind': 'natural_park'})
"""def splitText(text, lineLength, tabCount): lastSpace = 0 cnt = 0 if(len(text) <= lineLength): return text for(i in range(len(text))) if(cnt > lineLength) if(text[i] == ' '): last""" def writeBinaryData(file, data, length): itr = 0 for i in range(length): if itr % 16 == 0: file.writeNoNewline(" ") val = (data[i] & 0xFF) strVal = "0x%02X" % val file.writeNoNewline(strVal) if itr < 15 and i < length - 1: file.writeNoNewline(",") itr += 1 else: file.write(",") itr = 0 def writeFileDescription(file, name, summary, desc): text = headerDesc.replace("${FILENAME}", name) text = headerDesc.replace("${FILESUMMARY}", summary) text = headerDesc.replace("${FILEDESC}", desc) file.write(text) def generateContextAction(text, variables, owner, event, action): val = getActionArgumentValue(action, "Language") if val == None or len(val) == 0: text.append(" // leSetStringLanguage(); // no valid language selected!") else: text.append(" leSetStringLanguage(language_%s);" % val)
"""def splitText(text, lineLength, tabCount): lastSpace = 0 cnt = 0 if(len(text) <= lineLength): return text for(i in range(len(text))) if(cnt > lineLength) if(text[i] == ' '): last""" def write_binary_data(file, data, length): itr = 0 for i in range(length): if itr % 16 == 0: file.writeNoNewline(' ') val = data[i] & 255 str_val = '0x%02X' % val file.writeNoNewline(strVal) if itr < 15 and i < length - 1: file.writeNoNewline(',') itr += 1 else: file.write(',') itr = 0 def write_file_description(file, name, summary, desc): text = headerDesc.replace('${FILENAME}', name) text = headerDesc.replace('${FILESUMMARY}', summary) text = headerDesc.replace('${FILEDESC}', desc) file.write(text) def generate_context_action(text, variables, owner, event, action): val = get_action_argument_value(action, 'Language') if val == None or len(val) == 0: text.append(' // leSetStringLanguage(); // no valid language selected!') else: text.append(' leSetStringLanguage(language_%s);' % val)
# Leo colorizer control file for io mode. # This file is in the public domain. # Properties for io mode. properties = { "commentStart": "*/", "indentCloseBrackets": ")", "indentOpenBrackets": "(", "lineComment": "//", "lineUpClosingBracket": "true", } # Attributes dict for io_main ruleset. io_main_attributes_dict = { "default": "null", "digit_re": "", "escape": "\\", "highlight_digits": "true", "ignore_case": "false", "no_word_sep": "", } # Dictionary of attributes dictionaries for io mode. attributesDictDict = { "io_main": io_main_attributes_dict, } # Keywords dict for io_main ruleset. io_main_keywords_dict = { "Block": "keyword1", "Buffer": "keyword1", "CFunction": "keyword1", "Date": "keyword1", "Duration": "keyword1", "File": "keyword1", "Future": "keyword1", "LinkedList": "keyword1", "List": "keyword1", "Map": "keyword1", "Message": "keyword1", "Nil": "keyword1", "Nop": "keyword1", "Number": "keyword1", "Object": "keyword1", "String": "keyword1", "WeakLink": "keyword1", "block": "keyword1", "clone": "keyword3", "do": "keyword2", "else": "keyword2", "foreach": "keyword2", "forward": "keyword3", "hasSlot": "keyword3", "if": "keyword2", "method": "keyword1", "print": "keyword3", "proto": "keyword3", "self": "keyword3", "setSlot": "keyword3", "super": "keyword3", "type": "keyword3", "while": "keyword2", "write": "keyword3", } # Dictionary of keywords dictionaries for io mode. keywordsDictDict = { "io_main": io_main_keywords_dict, } # Rules for io_main ruleset. def io_rule0(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment1", seq="#", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def io_rule1(colorer, s, i): return colorer.match_eol_span(s, i, kind="comment1", seq="//", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="", exclude_match=False) def io_rule2(colorer, s, i): return colorer.match_span(s, i, kind="comment1", begin="/*", end="*/", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def io_rule3(colorer, s, i): return colorer.match_span(s, i, kind="literal2", begin="\"", end="\"", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def io_rule4(colorer, s, i): return colorer.match_span(s, i, kind="literal2", begin="\"\"\"", end="\"\"\"", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="",exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def io_rule5(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="`", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule6(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="~", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule7(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="@", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule8(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="@@", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule9(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="$", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule10(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="%", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule11(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="^", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule12(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="&", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule13(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="*", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule14(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="-", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule15(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="+", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule16(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="/", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule17(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule18(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="{", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule19(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="}", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule20(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="[", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule21(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="]", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule22(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="|", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule23(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="\\", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule24(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq=">=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule25(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="<=", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule26(colorer, s, i): return colorer.match_seq(s, i, kind="operator", seq="?", at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate="") def io_rule27(colorer, s, i): return colorer.match_keywords(s, i) # Rules dict for io_main ruleset. rulesDict1 = { "\"": [io_rule3,io_rule4,], "#": [io_rule0,], "$": [io_rule9,], "%": [io_rule10,], "&": [io_rule12,], "*": [io_rule13,], "+": [io_rule15,], "-": [io_rule14,], "/": [io_rule1,io_rule2,io_rule16,], "0": [io_rule27,], "1": [io_rule27,], "2": [io_rule27,], "3": [io_rule27,], "4": [io_rule27,], "5": [io_rule27,], "6": [io_rule27,], "7": [io_rule27,], "8": [io_rule27,], "9": [io_rule27,], "<": [io_rule25,], "=": [io_rule17,], ">": [io_rule24,], "?": [io_rule26,], "@": [io_rule7,io_rule8,io_rule27,], "A": [io_rule27,], "B": [io_rule27,], "C": [io_rule27,], "D": [io_rule27,], "E": [io_rule27,], "F": [io_rule27,], "G": [io_rule27,], "H": [io_rule27,], "I": [io_rule27,], "J": [io_rule27,], "K": [io_rule27,], "L": [io_rule27,], "M": [io_rule27,], "N": [io_rule27,], "O": [io_rule27,], "P": [io_rule27,], "Q": [io_rule27,], "R": [io_rule27,], "S": [io_rule27,], "T": [io_rule27,], "U": [io_rule27,], "V": [io_rule27,], "W": [io_rule27,], "X": [io_rule27,], "Y": [io_rule27,], "Z": [io_rule27,], "[": [io_rule20,], "\\": [io_rule23,], "]": [io_rule21,], "^": [io_rule11,], "`": [io_rule5,], "a": [io_rule27,], "b": [io_rule27,], "c": [io_rule27,], "d": [io_rule27,], "e": [io_rule27,], "f": [io_rule27,], "g": [io_rule27,], "h": [io_rule27,], "i": [io_rule27,], "j": [io_rule27,], "k": [io_rule27,], "l": [io_rule27,], "m": [io_rule27,], "n": [io_rule27,], "o": [io_rule27,], "p": [io_rule27,], "q": [io_rule27,], "r": [io_rule27,], "s": [io_rule27,], "t": [io_rule27,], "u": [io_rule27,], "v": [io_rule27,], "w": [io_rule27,], "x": [io_rule27,], "y": [io_rule27,], "z": [io_rule27,], "{": [io_rule18,], "|": [io_rule22,], "}": [io_rule19,], "~": [io_rule6,], } # x.rulesDictDict for io mode. rulesDictDict = { "io_main": rulesDict1, } # Import dict for io mode. importDict = {}
properties = {'commentStart': '*/', 'indentCloseBrackets': ')', 'indentOpenBrackets': '(', 'lineComment': '//', 'lineUpClosingBracket': 'true'} io_main_attributes_dict = {'default': 'null', 'digit_re': '', 'escape': '\\', 'highlight_digits': 'true', 'ignore_case': 'false', 'no_word_sep': ''} attributes_dict_dict = {'io_main': io_main_attributes_dict} io_main_keywords_dict = {'Block': 'keyword1', 'Buffer': 'keyword1', 'CFunction': 'keyword1', 'Date': 'keyword1', 'Duration': 'keyword1', 'File': 'keyword1', 'Future': 'keyword1', 'LinkedList': 'keyword1', 'List': 'keyword1', 'Map': 'keyword1', 'Message': 'keyword1', 'Nil': 'keyword1', 'Nop': 'keyword1', 'Number': 'keyword1', 'Object': 'keyword1', 'String': 'keyword1', 'WeakLink': 'keyword1', 'block': 'keyword1', 'clone': 'keyword3', 'do': 'keyword2', 'else': 'keyword2', 'foreach': 'keyword2', 'forward': 'keyword3', 'hasSlot': 'keyword3', 'if': 'keyword2', 'method': 'keyword1', 'print': 'keyword3', 'proto': 'keyword3', 'self': 'keyword3', 'setSlot': 'keyword3', 'super': 'keyword3', 'type': 'keyword3', 'while': 'keyword2', 'write': 'keyword3'} keywords_dict_dict = {'io_main': io_main_keywords_dict} def io_rule0(colorer, s, i): return colorer.match_eol_span(s, i, kind='comment1', seq='#', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False) def io_rule1(colorer, s, i): return colorer.match_eol_span(s, i, kind='comment1', seq='//', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False) def io_rule2(colorer, s, i): return colorer.match_span(s, i, kind='comment1', begin='/*', end='*/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def io_rule3(colorer, s, i): return colorer.match_span(s, i, kind='literal2', begin='"', end='"', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def io_rule4(colorer, s, i): return colorer.match_span(s, i, kind='literal2', begin='"""', end='"""', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='', exclude_match=False, no_escape=False, no_line_break=False, no_word_break=False) def io_rule5(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='`', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule6(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='~', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule7(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='@', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule8(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='@@', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule9(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='$', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule10(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='%', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule11(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='^', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule12(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='&', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule13(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='*', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule14(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='-', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule15(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='+', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule16(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='/', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule17(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule18(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='{', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule19(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='}', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule20(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='[', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule21(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq=']', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule22(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='|', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule23(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='\\', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule24(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='>=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule25(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='<=', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule26(colorer, s, i): return colorer.match_seq(s, i, kind='operator', seq='?', at_line_start=False, at_whitespace_end=False, at_word_start=False, delegate='') def io_rule27(colorer, s, i): return colorer.match_keywords(s, i) rules_dict1 = {'"': [io_rule3, io_rule4], '#': [io_rule0], '$': [io_rule9], '%': [io_rule10], '&': [io_rule12], '*': [io_rule13], '+': [io_rule15], '-': [io_rule14], '/': [io_rule1, io_rule2, io_rule16], '0': [io_rule27], '1': [io_rule27], '2': [io_rule27], '3': [io_rule27], '4': [io_rule27], '5': [io_rule27], '6': [io_rule27], '7': [io_rule27], '8': [io_rule27], '9': [io_rule27], '<': [io_rule25], '=': [io_rule17], '>': [io_rule24], '?': [io_rule26], '@': [io_rule7, io_rule8, io_rule27], 'A': [io_rule27], 'B': [io_rule27], 'C': [io_rule27], 'D': [io_rule27], 'E': [io_rule27], 'F': [io_rule27], 'G': [io_rule27], 'H': [io_rule27], 'I': [io_rule27], 'J': [io_rule27], 'K': [io_rule27], 'L': [io_rule27], 'M': [io_rule27], 'N': [io_rule27], 'O': [io_rule27], 'P': [io_rule27], 'Q': [io_rule27], 'R': [io_rule27], 'S': [io_rule27], 'T': [io_rule27], 'U': [io_rule27], 'V': [io_rule27], 'W': [io_rule27], 'X': [io_rule27], 'Y': [io_rule27], 'Z': [io_rule27], '[': [io_rule20], '\\': [io_rule23], ']': [io_rule21], '^': [io_rule11], '`': [io_rule5], 'a': [io_rule27], 'b': [io_rule27], 'c': [io_rule27], 'd': [io_rule27], 'e': [io_rule27], 'f': [io_rule27], 'g': [io_rule27], 'h': [io_rule27], 'i': [io_rule27], 'j': [io_rule27], 'k': [io_rule27], 'l': [io_rule27], 'm': [io_rule27], 'n': [io_rule27], 'o': [io_rule27], 'p': [io_rule27], 'q': [io_rule27], 'r': [io_rule27], 's': [io_rule27], 't': [io_rule27], 'u': [io_rule27], 'v': [io_rule27], 'w': [io_rule27], 'x': [io_rule27], 'y': [io_rule27], 'z': [io_rule27], '{': [io_rule18], '|': [io_rule22], '}': [io_rule19], '~': [io_rule6]} rules_dict_dict = {'io_main': rulesDict1} import_dict = {}
# Copyright 2019 Open Source Robotics Foundation # Licensed under the Apache License, version 2.0 """Colcon event handler extensions for analyzing sanitizer outputs."""
"""Colcon event handler extensions for analyzing sanitizer outputs."""
x = int(input()) ar = list(map(int,input().split())) ar = sorted(ar) if(ar[0]<=0): print(False) else: chk = False for i in ar: s = str(i) if (s==s[::-1]): chk = True break print(chk)
x = int(input()) ar = list(map(int, input().split())) ar = sorted(ar) if ar[0] <= 0: print(False) else: chk = False for i in ar: s = str(i) if s == s[::-1]: chk = True break print(chk)
#!/bin/zsh ''' Extending the Multiclipboard Extend the multiclipboard program in this chapter so that it has a delete <keyword> command line argument that will delete a keyword from the shelf. Then add a delete command line argument that will delete all keywords. '''
""" Extending the Multiclipboard Extend the multiclipboard program in this chapter so that it has a delete <keyword> command line argument that will delete a keyword from the shelf. Then add a delete command line argument that will delete all keywords. """
""" 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below. """ largest = None smallest = None while True: input_value = input("Enter a number: ") if input_value == "done" : break try: num = int(input_value) if smallest is None: smallest = num if largest is None: largest = num if num > largest: largest = num if num < smallest: smallest = num except: print("Invalid input") continue print("Maximum is", largest) print("Minimum is", smallest)
""" 5.2 Write a program that repeatedly prompts a user for integer numbers until the user enters 'done'. Once 'done' is entered, print out the largest and smallest of the numbers. If the user enters anything other than a valid number catch it with a try/except and put out an appropriate message and ignore the number. Enter 7, 2, bob, 10, and 4 and match the output below. """ largest = None smallest = None while True: input_value = input('Enter a number: ') if input_value == 'done': break try: num = int(input_value) if smallest is None: smallest = num if largest is None: largest = num if num > largest: largest = num if num < smallest: smallest = num except: print('Invalid input') continue print('Maximum is', largest) print('Minimum is', smallest)
# Copyright 2021 Google LLC # # 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. """Provides classes to ease writing snippets of javascript code in python. The JsSelector class allows generating selector code easily. """ class JsSelector(object): """Create javascript code for selecting DOM elements. This class generates javascript code that can chain calls on a root element ('document' by default) while catering to common use cases such as querySelector, and shadowRoot. Uses a javascript array type as an optional type so that you can create a document element selector arbitrarily deep, across shadowroots, and with null guards. Typical usage: RECIPE = ( JsSelector() .QuerySelector('[data-window-id="ui.RECIPE_OVERVIEW"]').NullGuard() .ShadowRoot().NullGuard() .QuerySelector('[id="some-container"]').NullGuard()) RECIPE_ELEMENT = RECIPE.Property('someElement') def test(): <device>.devtools.connect().evaluate_javascript( RECIPE_ELEMENT.GetOrDefault('0')) <device>.devtools.connect().evaluate_javascript( '(%s) != null' %s RECIPE.GetOrDefault()) """ def __init__(self, javascript='[document]'): self._javascript = '%s' % javascript def __str__(self): """Returns the javascript representation as a description.""" return self._javascript def QuerySelector(self, selector): """Returns this selector followed by a call to querySelector.""" return JsSelector('%s.map(e=>e.querySelector(\'%s\'))' % (self._javascript, selector)) def NullGuard(self): """Returns this selector followed by a null check. Generates code that ensures that subsequent javascript methods will not be called if the value is null. Returns: JsSelector: A selector that represents this selector followed by a null check. """ return JsSelector('%s.flatMap(e=>e==null?[]:[e])' % (self._javascript)) def ShadowRoot(self): """Returns this selector followed by getting the shadowRoot property.""" return self.Property('shadowRoot') def Property(self, property_name): """Returns this selector followed by a call to the given property.""" return JsSelector('%s.map(e=>e.%s)' % (self._javascript, property_name)) def Map(self, function): """Returns this selector followed by a call to the given function.""" return JsSelector('%s.map(%s)' % (self._javascript, function)) def GetOrDefault(self, default='null'): """Returns code for this selector's value or the given default. The expression will yield either null or the value. Args: default (str): A javascript expression of the default value. Must not be None, but the javascript expression may evaluate to 'null'. Returns: str: a string with the javascript expression. """ return '[%s].flatMap(a=>a.length==0?[(%s)]:a)[0]' % (self._javascript, default) def ToJavascript(self): """Returns the javascript code for this selector. The statement will have a type of array, and the array will be empty or contain a single value. Returns: str: a string with the javascript expression. """ return self._javascript
"""Provides classes to ease writing snippets of javascript code in python. The JsSelector class allows generating selector code easily. """ class Jsselector(object): """Create javascript code for selecting DOM elements. This class generates javascript code that can chain calls on a root element ('document' by default) while catering to common use cases such as querySelector, and shadowRoot. Uses a javascript array type as an optional type so that you can create a document element selector arbitrarily deep, across shadowroots, and with null guards. Typical usage: RECIPE = ( JsSelector() .QuerySelector('[data-window-id="ui.RECIPE_OVERVIEW"]').NullGuard() .ShadowRoot().NullGuard() .QuerySelector('[id="some-container"]').NullGuard()) RECIPE_ELEMENT = RECIPE.Property('someElement') def test(): <device>.devtools.connect().evaluate_javascript( RECIPE_ELEMENT.GetOrDefault('0')) <device>.devtools.connect().evaluate_javascript( '(%s) != null' %s RECIPE.GetOrDefault()) """ def __init__(self, javascript='[document]'): self._javascript = '%s' % javascript def __str__(self): """Returns the javascript representation as a description.""" return self._javascript def query_selector(self, selector): """Returns this selector followed by a call to querySelector.""" return js_selector("%s.map(e=>e.querySelector('%s'))" % (self._javascript, selector)) def null_guard(self): """Returns this selector followed by a null check. Generates code that ensures that subsequent javascript methods will not be called if the value is null. Returns: JsSelector: A selector that represents this selector followed by a null check. """ return js_selector('%s.flatMap(e=>e==null?[]:[e])' % self._javascript) def shadow_root(self): """Returns this selector followed by getting the shadowRoot property.""" return self.Property('shadowRoot') def property(self, property_name): """Returns this selector followed by a call to the given property.""" return js_selector('%s.map(e=>e.%s)' % (self._javascript, property_name)) def map(self, function): """Returns this selector followed by a call to the given function.""" return js_selector('%s.map(%s)' % (self._javascript, function)) def get_or_default(self, default='null'): """Returns code for this selector's value or the given default. The expression will yield either null or the value. Args: default (str): A javascript expression of the default value. Must not be None, but the javascript expression may evaluate to 'null'. Returns: str: a string with the javascript expression. """ return '[%s].flatMap(a=>a.length==0?[(%s)]:a)[0]' % (self._javascript, default) def to_javascript(self): """Returns the javascript code for this selector. The statement will have a type of array, and the array will be empty or contain a single value. Returns: str: a string with the javascript expression. """ return self._javascript
class CityNotFoundError(Exception): pass class ServerError(Exception): pass class OWMApiKeyIsNotCorrectError(ServerError): pass
class Citynotfounderror(Exception): pass class Servererror(Exception): pass class Owmapikeyisnotcorrecterror(ServerError): pass
class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: l = 0 r = len(numbers) - 1 while l < r: sum = numbers[l] + numbers[r] if sum == target: return [l + 1, r + 1] if sum < target: l += 1 else: r -= 1
class Solution: def two_sum(self, numbers: List[int], target: int) -> List[int]: l = 0 r = len(numbers) - 1 while l < r: sum = numbers[l] + numbers[r] if sum == target: return [l + 1, r + 1] if sum < target: l += 1 else: r -= 1
HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' REDEFINED = "\033[0;0m" PROCESS = "\033[1;37;42m" def message_information(text): print(OKBLUE + str(text) + REDEFINED) def message_sucess(text): print(OKGREEN + str(text) + REDEFINED) def message_failed(text): print(FAIL + str(text) + REDEFINED) def message_warning(text): print(WARNING + str(text) + REDEFINED) def process(text): print(PROCESS + f" {text} " + REDEFINED)
header = '\x1b[95m' okblue = '\x1b[94m' okgreen = '\x1b[92m' warning = '\x1b[93m' fail = '\x1b[91m' endc = '\x1b[0m' bold = '\x1b[1m' underline = '\x1b[4m' redefined = '\x1b[0;0m' process = '\x1b[1;37;42m' def message_information(text): print(OKBLUE + str(text) + REDEFINED) def message_sucess(text): print(OKGREEN + str(text) + REDEFINED) def message_failed(text): print(FAIL + str(text) + REDEFINED) def message_warning(text): print(WARNING + str(text) + REDEFINED) def process(text): print(PROCESS + f' {text} ' + REDEFINED)
class SensorStatusJob: on = 'ON' off = 'OFF' broken = 'BROKEN' charge_low = 'CHARGE_LOW' discharged = 'DISCHARGED' class SensorStatusSituation: null = 'NULL' stable = 'STABLE' fire = 'FIRE' warning = 'WARNING' class ObjectStatusJob: on = 'ON' off = 'OFF' defect = 'DEFECT' class ObjectStatusSituation: null = 'NULL' stable = 'STABLE' fire = 'FIRE' warning = 'WARNING'
class Sensorstatusjob: on = 'ON' off = 'OFF' broken = 'BROKEN' charge_low = 'CHARGE_LOW' discharged = 'DISCHARGED' class Sensorstatussituation: null = 'NULL' stable = 'STABLE' fire = 'FIRE' warning = 'WARNING' class Objectstatusjob: on = 'ON' off = 'OFF' defect = 'DEFECT' class Objectstatussituation: null = 'NULL' stable = 'STABLE' fire = 'FIRE' warning = 'WARNING'
""" # @Time : 2020/6/24 # @Author : Jimou Chen """ class Stack: def __init__(self): self.elem = [] def pop(self): self.elem.pop() def push(self, obj): self.elem.append(obj) def get_pop(self): return self.elem[-1] def is_empty(self): if len(self.elem) == 0: return True else: return False def length(self): return len(self.elem) def show(self): print(self.elem) if __name__ == '__main__': stack = Stack() stack.elem = [1, 2, 3, 4, 5, 6, 7] stack.show() stack.pop() stack.show() stack.push(999) stack.show() if stack.is_empty(): print("empty") else: print("no empty")
""" # @Time : 2020/6/24 # @Author : Jimou Chen """ class Stack: def __init__(self): self.elem = [] def pop(self): self.elem.pop() def push(self, obj): self.elem.append(obj) def get_pop(self): return self.elem[-1] def is_empty(self): if len(self.elem) == 0: return True else: return False def length(self): return len(self.elem) def show(self): print(self.elem) if __name__ == '__main__': stack = stack() stack.elem = [1, 2, 3, 4, 5, 6, 7] stack.show() stack.pop() stack.show() stack.push(999) stack.show() if stack.is_empty(): print('empty') else: print('no empty')
"""Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order. Examples Valid arrays a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write b's elements in terms of squares: a = [121, 144, 19, 161, 19, 144, 19, 11] b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] Invalid arrays If, for example, we change the first number to something else, comp may not return true anymore: a = [121, 144, 19, 161, 19, 144, 19, 11] b = [132, 14641, 20736, 361, 25921, 361, 20736, 361] comp(a,b) returns false because in b 132 is not the square of any number of a. a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361] comp(a,b) returns false because in b 36100 is not the square of any number of a.""" def comp(array1, array2): for i in array2: if int(i ** 0.5) in array1: continue else: print(i) return False return True a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] print(comp(a, b))
"""Given two arrays a and b write a function comp(a, b) (orcompSame(a, b)) that checks whether the two arrays have the "same" elements, with the same multiplicities. "Same" means, here, that the elements in b are the elements in a squared, regardless of the order. Examples Valid arrays a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] comp(a, b) returns true because in b 121 is the square of 11, 14641 is the square of 121, 20736 the square of 144, 361 the square of 19, 25921 the square of 161, and so on. It gets obvious if we write b's elements in terms of squares: a = [121, 144, 19, 161, 19, 144, 19, 11] b = [11*11, 121*121, 144*144, 19*19, 161*161, 19*19, 144*144, 19*19] Invalid arrays If, for example, we change the first number to something else, comp may not return true anymore: a = [121, 144, 19, 161, 19, 144, 19, 11] b = [132, 14641, 20736, 361, 25921, 361, 20736, 361] comp(a,b) returns false because in b 132 is not the square of any number of a. a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 36100, 25921, 361, 20736, 361] comp(a,b) returns false because in b 36100 is not the square of any number of a.""" def comp(array1, array2): for i in array2: if int(i ** 0.5) in array1: continue else: print(i) return False return True a = [121, 144, 19, 161, 19, 144, 19, 11] b = [121, 14641, 20736, 361, 25921, 361, 20736, 361] print(comp(a, b))
# Misc general coloring tips # Color organization: highlighted, neutral, and low-lighted/background # Red and green in center of screen # Blue, black, white, and yellow in periphery of screen # http://www.awwwards.com/flat-design-an-in-depth-look.html # main actions such as "Submit," "Send," "See More," should have vivid color with strong contrast to background, same as logo # secondary button color, usually a light gray, ok vs cancel titlefont1 = {"type": ("Segoe UI", 12, "bold"), "color": "black"} titlefont1_contrast = {"type": ("Segoe UI", 12, "bold"), "color": "white"} font1 = {"type": ("Segoe UI", 10), "color": "black"} font2 = {"type": ("Segoe UI", 10), "color": "Grey42"} color1 = "Grey69" color2 = "Grey79" color3 = "Grey89" color4 = "Grey99" color5 = "white" strongcolor1 = "gold" strongcolor2 = "dark orange" alterncolor1 = "DodgerBlue" alterncolor2 = "Blue3" # Dark version ##titlefont1 = {"type": ("Segoe UI", 12, "bold"), ## "color": "white"} ##titlefont1_contrast = {"type": ("Segoe UI", 12, "bold"), ## "color": "white"} ## ##font1 = {"type": ("Segoe UI", 10), ## "color": "white"} ##font2 = {"type": ("Segoe UI", 10), ## "color": "Grey82"} ## ##color1 = "Grey9" ##color2 = "Grey19" ##color3 = "Grey29" ##color4 = "Grey39" ##color5 = "Grey49" ## ##strongcolor1 = "gold" ##strongcolor2 = "dark orange" ## ##alterncolor1 = "DodgerBlue" ##alterncolor2 = "Blue3" ##
titlefont1 = {'type': ('Segoe UI', 12, 'bold'), 'color': 'black'} titlefont1_contrast = {'type': ('Segoe UI', 12, 'bold'), 'color': 'white'} font1 = {'type': ('Segoe UI', 10), 'color': 'black'} font2 = {'type': ('Segoe UI', 10), 'color': 'Grey42'} color1 = 'Grey69' color2 = 'Grey79' color3 = 'Grey89' color4 = 'Grey99' color5 = 'white' strongcolor1 = 'gold' strongcolor2 = 'dark orange' alterncolor1 = 'DodgerBlue' alterncolor2 = 'Blue3'
subprocess.Popen('/bin/ls *', shell=True) #nosec (on the line) subprocess.Popen('/bin/ls *', #nosec (at the start of function call) shell=True) subprocess.Popen('/bin/ls *', shell=True) #nosec (on the specific kwarg line)
subprocess.Popen('/bin/ls *', shell=True) subprocess.Popen('/bin/ls *', shell=True) subprocess.Popen('/bin/ls *', shell=True)
''' Single point of truth for version information ''' VERSION_NO = '1.1.7' VERSION_DESC = 'VAWS' + VERSION_NO
""" Single point of truth for version information """ version_no = '1.1.7' version_desc = 'VAWS' + VERSION_NO
# Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def detectCycle(self, head: ListNode) -> ListNode: if head is None: return None slow = fast = head meet = None while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: meet = slow break if meet is None: return None p1 = head p2 = meet while p1 != p2: p1 = p1.next p2 = p2.next return p1 A = Solution() a = ListNode(3) b = ListNode(2) c = ListNode(0) d = ListNode(-4) a.next = b b.next = c c.next = d d.next = b e = ListNode(1) f = ListNode(2) e.next = f f.next = e print(A.detectCycle(e))
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def detect_cycle(self, head: ListNode) -> ListNode: if head is None: return None slow = fast = head meet = None while fast and fast.next: slow = slow.next fast = fast.next.next if slow == fast: meet = slow break if meet is None: return None p1 = head p2 = meet while p1 != p2: p1 = p1.next p2 = p2.next return p1 a = solution() a = list_node(3) b = list_node(2) c = list_node(0) d = list_node(-4) a.next = b b.next = c c.next = d d.next = b e = list_node(1) f = list_node(2) e.next = f f.next = e print(A.detectCycle(e))
# Create a string variable with your full name name = "Boris Johnson" # Split the string into a list names = name.split(" ") # Print out your surname surname = names[-1] print("Surname:", surname) # Check if your surname contains the letter 'e' pos = surname.find("e") print("Position of 'e':", pos) # or contains the letter 'o' pos = surname.find("o") print("Position of 'o':", pos)
name = 'Boris Johnson' names = name.split(' ') surname = names[-1] print('Surname:', surname) pos = surname.find('e') print("Position of 'e':", pos) pos = surname.find('o') print("Position of 'o':", pos)
""" Max() Function Write a program that can take two numbers from user and then pass these numbers as arguments to function called max(a, b) where a is the first number and b is the second number. This finction should print the maximum number. """ def Max(a, b): # He used 'M' capital in Max() because there is a built-in function called max() so Max(). So Max() and max() are differient! if a> b: print(a, "is the maximum number") else: print(b, "is the maximum number") # main program starts here num1 = int(input("Enter number 1: ")) num2 = int(input("Enter number 2: ")) print("maximum value is", Max(num1, num2)) # Enter number 1: 12 # Enter number 2: 8 # 12 is the maximum number # maximum value is None
""" Max() Function Write a program that can take two numbers from user and then pass these numbers as arguments to function called max(a, b) where a is the first number and b is the second number. This finction should print the maximum number. """ def max(a, b): if a > b: print(a, 'is the maximum number') else: print(b, 'is the maximum number') num1 = int(input('Enter number 1: ')) num2 = int(input('Enter number 2: ')) print('maximum value is', max(num1, num2))
# Bit Manipulation # Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight). # # Example 1: # # Input: 11 # Output: 3 # Explanation: Integer 11 has binary representation 00000000000000000000000000001011 # Example 2: # # Input: 128 # Output: 1 # Explanation: Integer 128 has binary representation 00000000000000000000000010000000 class Solution(object): def hammingWeight(self, n): """ :type n: int :rtype: int """ return bin(n)[2:].count('1')
class Solution(object): def hamming_weight(self, n): """ :type n: int :rtype: int """ return bin(n)[2:].count('1')
value = 'some' #modify this line if value == 'Y' or value == 'y': print('yes') elif value == 'N' or value == 'n': print('no') else: print('error')
value = 'some' if value == 'Y' or value == 'y': print('yes') elif value == 'N' or value == 'n': print('no') else: print('error')
class BasicBlock(object): def __init__(self): self.start_addr = 0 self.end_addr = 0 self.instructions = [] self.successors = [] def __str__(self): return "0x%x - 0x%x (%d) -> [%s]" % (self.start_addr, self.end_addr, len(self.instructions), ", ".join(["0x%x" % ref for ref in self.successors]))
class Basicblock(object): def __init__(self): self.start_addr = 0 self.end_addr = 0 self.instructions = [] self.successors = [] def __str__(self): return '0x%x - 0x%x (%d) -> [%s]' % (self.start_addr, self.end_addr, len(self.instructions), ', '.join(['0x%x' % ref for ref in self.successors]))
events = input().split("|") energy = 100 coins = 100 is_bankrupt = False for event in events: args = event.split("-") name = args[0] value = int(args[1]) if name == "rest": gained_energy = 0 if energy + value < 100: gained_energy = value energy += value else: gained_energy = 100 - energy energy = 100 print(f"You gained {gained_energy} energy.") print(f"Current energy: {energy}.") elif name == "order": if energy < 30: energy += 50 print("You had to rest!") continue coins += value energy -= 30 print(f"You earned {value} coins.") else: if coins <= value: print(f"Closed! Cannot afford {name}.") is_bankrupt = True break coins -= value print(f"You bought {name}.") if not is_bankrupt: print("Day completed!") print(f"Coins: {coins}") print(f"Energy: {energy}")
events = input().split('|') energy = 100 coins = 100 is_bankrupt = False for event in events: args = event.split('-') name = args[0] value = int(args[1]) if name == 'rest': gained_energy = 0 if energy + value < 100: gained_energy = value energy += value else: gained_energy = 100 - energy energy = 100 print(f'You gained {gained_energy} energy.') print(f'Current energy: {energy}.') elif name == 'order': if energy < 30: energy += 50 print('You had to rest!') continue coins += value energy -= 30 print(f'You earned {value} coins.') else: if coins <= value: print(f'Closed! Cannot afford {name}.') is_bankrupt = True break coins -= value print(f'You bought {name}.') if not is_bankrupt: print('Day completed!') print(f'Coins: {coins}') print(f'Energy: {energy}')
to_name = { "TA": "TA", "D": "dependent", "TC": "tile coding", "RB": "random binary", "R": "random real-valued", "P": "polynomial", "F": "fourier", "RC": "state aggregation", }
to_name = {'TA': 'TA', 'D': 'dependent', 'TC': 'tile coding', 'RB': 'random binary', 'R': 'random real-valued', 'P': 'polynomial', 'F': 'fourier', 'RC': 'state aggregation'}
# https://leetcode.com/problems/partition-array-into-three-parts-with-equal-sum/ # split a array into 3 equal subarray def canThreePartsEqualSum(self, A): """ :type A: List[int] :rtype: bool """ s= sum(A) if s%3!=0: return False each_sum = s/3 result = [2*each_sum,each_sum] temp =0 for val in A: if not result: return True else: temp += val if temp == result[-1]: result.pop() return False
def can_three_parts_equal_sum(self, A): """ :type A: List[int] :rtype: bool """ s = sum(A) if s % 3 != 0: return False each_sum = s / 3 result = [2 * each_sum, each_sum] temp = 0 for val in A: if not result: return True else: temp += val if temp == result[-1]: result.pop() return False
# -*- coding:utf-8 -*- class Solution: def IsPopOrder(self, pushV, popV): # write code here imi = [pushV.pop(0)] while imi: cur = popV.pop(0) while imi[-1] != cur: if not pushV: return False imi.append(pushV.pop(0)) imi.pop() return True s = Solution() s.IsPopOrder([1,2,3,4,5],[3,2,5,4,1])
class Solution: def is_pop_order(self, pushV, popV): imi = [pushV.pop(0)] while imi: cur = popV.pop(0) while imi[-1] != cur: if not pushV: return False imi.append(pushV.pop(0)) imi.pop() return True s = solution() s.IsPopOrder([1, 2, 3, 4, 5], [3, 2, 5, 4, 1])
colors_file = None try: colors_file = open("colors2.txt", "r") for color in colors_file: print(color.rstrip()) except IOError as exc: print(exc) finally: if colors_file: colors_file.close() # print(dir(colors_file))
colors_file = None try: colors_file = open('colors2.txt', 'r') for color in colors_file: print(color.rstrip()) except IOError as exc: print(exc) finally: if colors_file: colors_file.close()
''' import html2text html = input('') text = html2text.html2text(html) print(text) input() ''' teste = input("Digite:") if teste == "1": print("1") elif teste == "2": print("2") else: print("3")
""" import html2text html = input('') text = html2text.html2text(html) print(text) input() """ teste = input('Digite:') if teste == '1': print('1') elif teste == '2': print('2') else: print('3')
d = {'name':'mari','age':19,'gender':'feminine'} del d['age'] print(d.values()) # .keys() # .items() for k,v in d.items(): print(f'[{k}]:[{v}]') print(d) e = {} br = [] for c in range(0,2): e['uf'] = str(input('estado: ')) e['cidade'] = str(input('cidade: ')) br.append(e.copy()) print(br)
d = {'name': 'mari', 'age': 19, 'gender': 'feminine'} del d['age'] print(d.values()) for (k, v) in d.items(): print(f'[{k}]:[{v}]') print(d) e = {} br = [] for c in range(0, 2): e['uf'] = str(input('estado: ')) e['cidade'] = str(input('cidade: ')) br.append(e.copy()) print(br)
class MultiplesOf3And5: def execute(self, top): result = 0 for multiple in [3, 5]: result += sum(self.get_multiples(multiple, top)) return result def get_multiples(self, multiple, top): value = 0 while value < top: yield value value += multiple
class Multiplesof3And5: def execute(self, top): result = 0 for multiple in [3, 5]: result += sum(self.get_multiples(multiple, top)) return result def get_multiples(self, multiple, top): value = 0 while value < top: yield value value += multiple
# # PROBLEM INTERPRETATION | MY INTERPRETATION # | # West | West # _______ | _______ # *South-West* / \ North-West | *South* / \ North-West # / \ | / \ # \ / | \ / # South-Est \_______/ *North-Est* | South-Est \_______/ *North* # Est | Est # | # | # | # --------------------> Est | # | --------------------> Est # / \ | | . # / / \ / \ / \ / \ \ | | _____________________________ . # / | A | B | C | D | \ | | | A | B | C | D | | . # / / \ / \ / \ / \ / \ \ | | |_____|_____|_____|_____|_____| . # / | E | F | G | H | I | \ | | | E | F | G | H | I | . # / \ / \ / \ / \ / \ / \ | | |_____|_____|_____|_____|_____| . # / | J | K | L | M | \ | | | | J | K | L | M | . # |/ \ / \ / \ / \ / \| | \|/ |_____|_____|_____|_____|_____| . # ' ' | ' _| # *South-West* South-Est | *South* South-Est # def resize(list_, radius, default): # resize generic list, expanding symmetrically for _ in range((size(radius) - len(list_)) // 2): list_.append(safe_copy(default)) list_.insert(0, safe_copy(default)) def safe_copy(element): try: return element.copy() except AttributeError: return element def size(radius): # given the radius (max index abs value) the size is 2 radius + 1 for the center + 2 for margins return 2 * radius + 3 def resize_floor(f, s_radius, e_radius): resize(f, s_radius, ['.'] * size(e_radius)) for r in floor: resize(r, e_radius, '.') def is_margin(num, radius): return num == 0 or num == size(radius) - 1 # part 1 blacks = set() for tile in open("input.txt", "r").read().split('\n'): tile = tile.replace('sw', 's').replace('ne', 'n') s = tile.count('s') - tile.count('n') e = tile.count('e') - tile.count('w') coords = (s, e) if coords in blacks: blacks.remove(coords) else: blacks.add(coords) print(len(blacks)) # part 2 sRadius = 0 # radius is max coord in abs value eRadius = 0 floor = [['.']] for tile in blacks: # set starting black tiles (from part 1 set) to '#' sRadius = max(sRadius, abs(tile[0])) eRadius = max(eRadius, abs(tile[1])) resize_floor(floor, sRadius, eRadius) floor[tile[0] + sRadius + 1][tile[1] + eRadius + 1] = '#' # +1 for margin for _ in range(100): expandS = 0 expandE = 0 for i in range(len(floor)): for j in range(len(floor[i])): neighbours = 0 for delta in [(1, 0), (1, 1), (0, 1), (-1, 0), (-1, -1), (0, -1)]: # count neighbours y = i + delta[0] x = j + delta[1] if 0 <= y < len(floor) and 0 <= x < len(floor[i]): if floor[y][x] == '#' or floor[y][x] == '0': neighbours += 1 if floor[i][j] == '#': # decide changes but don't apply yet if neighbours == 0 or neighbours > 2: floor[i][j] = '0' # '0' is '#' going to '.' if floor[i][j] == '.': if neighbours == 2: floor[i][j] = '1' # '1' is '.' going to '#' for i in range(len(floor)): # apply changes for j in range(len(floor[i])): if floor[i][j] == '0' or floor[i][j] == '1': if floor[i][j] == '0': floor[i][j] = '.' else: floor[i][j] = '#' if is_margin(i, sRadius): # expand radius if I'm writing on margin expandS = 1 if is_margin(j, eRadius): expandE = 1 sRadius += expandS eRadius += expandE resize_floor(floor, sRadius, eRadius) total = 0 # count final number of '#' for row in floor: total += row.count('#') print(total)
def resize(list_, radius, default): for _ in range((size(radius) - len(list_)) // 2): list_.append(safe_copy(default)) list_.insert(0, safe_copy(default)) def safe_copy(element): try: return element.copy() except AttributeError: return element def size(radius): return 2 * radius + 3 def resize_floor(f, s_radius, e_radius): resize(f, s_radius, ['.'] * size(e_radius)) for r in floor: resize(r, e_radius, '.') def is_margin(num, radius): return num == 0 or num == size(radius) - 1 blacks = set() for tile in open('input.txt', 'r').read().split('\n'): tile = tile.replace('sw', 's').replace('ne', 'n') s = tile.count('s') - tile.count('n') e = tile.count('e') - tile.count('w') coords = (s, e) if coords in blacks: blacks.remove(coords) else: blacks.add(coords) print(len(blacks)) s_radius = 0 e_radius = 0 floor = [['.']] for tile in blacks: s_radius = max(sRadius, abs(tile[0])) e_radius = max(eRadius, abs(tile[1])) resize_floor(floor, sRadius, eRadius) floor[tile[0] + sRadius + 1][tile[1] + eRadius + 1] = '#' for _ in range(100): expand_s = 0 expand_e = 0 for i in range(len(floor)): for j in range(len(floor[i])): neighbours = 0 for delta in [(1, 0), (1, 1), (0, 1), (-1, 0), (-1, -1), (0, -1)]: y = i + delta[0] x = j + delta[1] if 0 <= y < len(floor) and 0 <= x < len(floor[i]): if floor[y][x] == '#' or floor[y][x] == '0': neighbours += 1 if floor[i][j] == '#': if neighbours == 0 or neighbours > 2: floor[i][j] = '0' if floor[i][j] == '.': if neighbours == 2: floor[i][j] = '1' for i in range(len(floor)): for j in range(len(floor[i])): if floor[i][j] == '0' or floor[i][j] == '1': if floor[i][j] == '0': floor[i][j] = '.' else: floor[i][j] = '#' if is_margin(i, sRadius): expand_s = 1 if is_margin(j, eRadius): expand_e = 1 s_radius += expandS e_radius += expandE resize_floor(floor, sRadius, eRadius) total = 0 for row in floor: total += row.count('#') print(total)
# Why does this file exist, and why not put this in `__main__`? # # You might be tempted to import things from __main__ later, # but that will cause problems: the code will get executed twice: # # - When you run `python -m poetry_issue_2369` python will execute # `__main__.py` as a script. That means there won't be any # `poetry_issue_2369.__main__` in `sys.modules`. # - When you import `__main__` it will get executed again (as a module) because # there's no `poetry_issue_2369.__main__` in `sys.modules`. def main(args=None): return 1
def main(args=None): return 1
class YRangeConfigurator: """ """ def __init__(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :type config: dict """ self.__config = config self.__y_range = None def set_config(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :type config: dict """ self.__config = config def get_config(self): """ :return: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :rtype: dict """ return self.__config def set_y_range_config(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :type config: dict """ if not isinstance(config, dict): raise TypeError("The configuration that has been provided is not of a dictionary type") if not isinstance(config['network_config'], dict): raise TypeError("The configurators configuration should be provided in a dict") if 'y_range' not in config['network_config'].keys(): raise KeyError("The y-range configuration has not been set.") if not isinstance(config['network_config']['y_range'], list): raise TypeError("The y-range configuration is not of a list type") y_range = config['network_config']['y_range'] self.__y_range = y_range def get_y_range_config(self): """ :return: :rtype: list """ return self.__y_range def build(self): """ """ config = self.get_config() self.set_y_range_config(config=config)
class Yrangeconfigurator: """ """ def __init__(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :type config: dict """ self.__config = config self.__y_range = None def set_config(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :type config: dict """ self.__config = config def get_config(self): """ :return: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :rtype: dict """ return self.__config def set_y_range_config(self, config): """ :param config: The config parameter is a dictionary containing all of the Dataspot basic configurations. An example of the basic structure can be found in examples/dataspot_config_example.json :type config: dict """ if not isinstance(config, dict): raise type_error('The configuration that has been provided is not of a dictionary type') if not isinstance(config['network_config'], dict): raise type_error('The configurators configuration should be provided in a dict') if 'y_range' not in config['network_config'].keys(): raise key_error('The y-range configuration has not been set.') if not isinstance(config['network_config']['y_range'], list): raise type_error('The y-range configuration is not of a list type') y_range = config['network_config']['y_range'] self.__y_range = y_range def get_y_range_config(self): """ :return: :rtype: list """ return self.__y_range def build(self): """ """ config = self.get_config() self.set_y_range_config(config=config)
{ "task": "tabular", "core": { "data": { "bs": 64, #Default "val_bs": null, #Default "device": null, #Default "no_check": false, #Default "num_workers": 16, "validation": { "method": "none", # [split_none, split_by_rand_pct, split_subsets, split_by_files, split_by_fname_file, split_by_folder, split_by_idx, split_by_idxs, split_by_list, split_by_valid_func, split_from_df] "rand_pct": { "valid_pct": 0.2, #Default "seed": null #Default }, "idx": { "csv_name": null, "valid_idx": 20 }, "subsets": { "train_size": 0.08, "valid_size": 0.2, "seed": null }, "files": { "valid_names": null }, "fname_file": { "fname": null, "path": null }, "folder": { "train": "train", "valid": "train" }, "idxs": { "train_idx": null, "valid_idx": null }, "list": { "train": null, "valid": null }, "valid_func": { "fname": null, "func": null }, "from_df": { "col": null #Default is 2 } }, "label": { "method": "from_df", # [label_empty, label_from_df, label_const, label_from_folder, label_from_func, label_from_re] "from_df": { "default":true, "cols": 1, #Default "label_cls": null, #Default options: null, FloatList, CategoryList, MultiCategoryList, EmptyLabelList "items": null, "label_delim": null, "one_hot": false, "classes": null }, "const": { "const": 0, #Default "label_cls": null #Default }, "from_func": { "fname": null, "func": null }, "from_re": { "pat": null, "full_path": false }, "from_folder": { "label_cls": null } } }, "metric": { # Available options: [accuracy, accuracy_thresh, top_k_accuracy, dice, error_rate, mean_squared_error, mean_absolute_error, # mean_squared_logarithmic_error, exp_rmspe, root_mean_squared_error, fbeta, explained_variance, r2_score, Precision, Recall, # FBeta, ExplainedVariance, MatthewsCorreff, KappaScore, MultiLabelFbeta, auc_roc_score, roc_curve, AUROC] "methods": [ "accuracy", "error_rate", "Precision" ], "accuracy_thresh": { "thresh": 0.5, #Default "sigmoid": true #Default }, "top_k_accuracy": { "k": 5 #Default }, "dice": { "iou": false, #Default "eps": 1e-8 #Default }, "fbeta": { "thresh": 0.2, #Default "beta": 2, #Default "eps": 1e-9, #Default "sigmoid": true #Default }, "Precision": { "average": "binary", #Default "pos_label": 1, #Default "eps": 1e-9 #Default }, "Recall": { "average": "binary", #Default "pos_label": 1, #Default "eps": 1e-9 #Default }, "FBeta": { "average": "binary", #Default "pos_label": 1, #Default "eps": 1e-9, #Default "beta": 2 #Default }, "KappaScore": { "weights": null }, "MultiLabelFbeta": { "beta": 2, #Default "eps": 1e-15, #Default "thresh": 0.3, #Default "sigmoid": true, #Default "average": "micro" #Default } }, "loss": { "type": "pre-defined", "pre-defined": { "func": "MSELossFlat" # BCEFlat, BCEWithLogitsFlat, CrossEntropyFlat, MSELossFlat, NoopLoss, WassersteinLoss }, "custom": { "fname": null, "func": null } }, "optimizer": { # "available_opts": [ # "SGD", # "RMSProp", # "Adam", # "AdamW", # "Adadelta", # "Adagrad", # "SparseAdam", # "Adamax", # "ASGD" # ], "chosen_opt": "ASGD", "arguments": { "SGD": { "lr": 0, "momentum": 0, "weight_decay": 0, "dampening": 0, "nesterov": false }, "RMSProp": { "lr": 0.01, "momentum": 0, "alpha": 0.99, "eps": 1e-8, "centered": false, "weight_decay": 0 }, "Adam": { "lr": 0.001, "momentum": 0.9, "alpha": 0.999, "eps": 1e-8, "weight_decay": 0, "amsgrad": false }, "AdamW": { "lr": 0.001, "momentum": 0.9, "alpha": 0.999, "eps": 1e-8, "weight_decay": 0.01, "amsgrad": false }, "Adadelta": { "lr": 1, "rho": 0.9, "eps": 0.000001, "weight_decay": 0 }, "Adagrad": { "lr": 0.01, "lr_decay": 0, "eps": 1e-10, "weight_decay": 0 }, "SparseAdam": { "lr": 0.001, "momentum": 0.9, "alpha": 0.999, "eps": 1e-8 }, "Adamax": { "lr": 0.002, "momentum": 0.9, "alpha": 0.999, "eps": 1e-8, "weight_decay": 0.01 }, "ASGD": { "lr": 0.01, "lambd": 0.0001, "alpha": 0.75, "t0": 1000000, "weight_decay": 0 } } } }, "tabular": { "input": { "csv_name": "./data/hello.csv", "dep_var": "columnt", "cat_names": [ "column1" ], "cont_names": [ "column2" ], "test_df": { "has_test": false, "csv_name": null } }, "transform": { "FillMissing": { "fill_strategy": "MEDIAN", # MEDIAN, COMMON, CONSTANT "add_col": true, "fill_val": 0 #Filled with this if CONSTANT }, "Categorify": true, "Normalize": true, "Datetime": { "cols": [], "cyclic": false #Bool } }, "model": { "type": "default", #Default, Custom "default": { "out_sz": null, "layers": null, "emb_drop": 0, "ps": null, "y_range": null, "use_bn": true, "bn_final": false }, "custom": { "layers": [], "extra_args": { "bn_begin": false } } } }, "test_df": null, "vision": { "subtask": "object-detection", "input": { "method": "from_folder", "from_folder": { "path": "data/coco_tiny", "extensions": null, "recurse": true, "exclude": null, "include": null, "processor": null, "presort": false }, "from_csv": { "csv_name": null, "path":null, "cols": 0, "delimiter": null, "header": "infer", "processor": null } }, "classification-single-label": {}, "classification-multi-label": {}, "regression": {}, "segmentation": {}, "gan": { "noise_sz": 100 }, "object-detection": {}, "points": {}, "transform": { "size":24, "data_aug":["basic_transforms","zoom_crop","manual"], "chosen_data_aug":"manual", "basic_transforms": { "do_flip":true, "flip_vert":false, "max_rotate":10.0, "max_zoom":1, "max_lighting":0.8, "max_warp":0.2, "p_affine":0.75, "p_lighting":0.75 }, "zoom_crop": { "scale":[0.75,2], "do_rand":true, "p":1.0 }, "manual": { "brightness": { "change":0.5 }, "contrast": { "scale":1.0 }, "crop": { "size":300, "row_pct":0.5, "col_pct":0.5 }, "crop_pad": { "size":300, "padding_mode":"reflection", "row_pct":0.5, "col_pct":0.5 }, "dihedral": { "k":0 }, "dihedral_affine": { "k":0 }, "flip_lr": {}, "flip_affine": {}, "jitter": { "magnitude":0.0 }, "pad": { "padding":50, "available_modes":["zeros", "border", "reflection"], "mode":"reflection" }, "rotate": { "degrees":0.0 }, "rgb_randomize": { "channels":["Red", "Green", "Blue"], "chosen_channels":"Red", "thresh":[0.2,0.595,0.99], "chosen_thresh":0.2 }, "skew": { "direction":0, "magnitude":0, "invert":false }, "squish": { "scale":1.0, "row_pct":0.5, "col_pct":0.5 }, "symmetric_wrap": { "magnitude":[-0.2,0.2] }, "tilt": { "direction":0, "magnitude":0 }, "zoom": { "scale":1.0, "row_pct":0.5, "col_pct":0.5 }, "cutout": { "n_holes":1, "length":40 } } } } }
{'task': 'tabular', 'core': {'data': {'bs': 64, 'val_bs': null, 'device': null, 'no_check': false, 'num_workers': 16, 'validation': {'method': 'none', 'rand_pct': {'valid_pct': 0.2, 'seed': null}, 'idx': {'csv_name': null, 'valid_idx': 20}, 'subsets': {'train_size': 0.08, 'valid_size': 0.2, 'seed': null}, 'files': {'valid_names': null}, 'fname_file': {'fname': null, 'path': null}, 'folder': {'train': 'train', 'valid': 'train'}, 'idxs': {'train_idx': null, 'valid_idx': null}, 'list': {'train': null, 'valid': null}, 'valid_func': {'fname': null, 'func': null}, 'from_df': {'col': null}}, 'label': {'method': 'from_df', 'from_df': {'default': true, 'cols': 1, 'label_cls': null, 'items': null, 'label_delim': null, 'one_hot': false, 'classes': null}, 'const': {'const': 0, 'label_cls': null}, 'from_func': {'fname': null, 'func': null}, 'from_re': {'pat': null, 'full_path': false}, 'from_folder': {'label_cls': null}}}, 'metric': {'methods': ['accuracy', 'error_rate', 'Precision'], 'accuracy_thresh': {'thresh': 0.5, 'sigmoid': true}, 'top_k_accuracy': {'k': 5}, 'dice': {'iou': false, 'eps': 1e-08}, 'fbeta': {'thresh': 0.2, 'beta': 2, 'eps': 1e-09, 'sigmoid': true}, 'Precision': {'average': 'binary', 'pos_label': 1, 'eps': 1e-09}, 'Recall': {'average': 'binary', 'pos_label': 1, 'eps': 1e-09}, 'FBeta': {'average': 'binary', 'pos_label': 1, 'eps': 1e-09, 'beta': 2}, 'KappaScore': {'weights': null}, 'MultiLabelFbeta': {'beta': 2, 'eps': 1e-15, 'thresh': 0.3, 'sigmoid': true, 'average': 'micro'}}, 'loss': {'type': 'pre-defined', 'pre-defined': {'func': 'MSELossFlat'}, 'custom': {'fname': null, 'func': null}}, 'optimizer': {'chosen_opt': 'ASGD', 'arguments': {'SGD': {'lr': 0, 'momentum': 0, 'weight_decay': 0, 'dampening': 0, 'nesterov': false}, 'RMSProp': {'lr': 0.01, 'momentum': 0, 'alpha': 0.99, 'eps': 1e-08, 'centered': false, 'weight_decay': 0}, 'Adam': {'lr': 0.001, 'momentum': 0.9, 'alpha': 0.999, 'eps': 1e-08, 'weight_decay': 0, 'amsgrad': false}, 'AdamW': {'lr': 0.001, 'momentum': 0.9, 'alpha': 0.999, 'eps': 1e-08, 'weight_decay': 0.01, 'amsgrad': false}, 'Adadelta': {'lr': 1, 'rho': 0.9, 'eps': 1e-06, 'weight_decay': 0}, 'Adagrad': {'lr': 0.01, 'lr_decay': 0, 'eps': 1e-10, 'weight_decay': 0}, 'SparseAdam': {'lr': 0.001, 'momentum': 0.9, 'alpha': 0.999, 'eps': 1e-08}, 'Adamax': {'lr': 0.002, 'momentum': 0.9, 'alpha': 0.999, 'eps': 1e-08, 'weight_decay': 0.01}, 'ASGD': {'lr': 0.01, 'lambd': 0.0001, 'alpha': 0.75, 't0': 1000000, 'weight_decay': 0}}}}, 'tabular': {'input': {'csv_name': './data/hello.csv', 'dep_var': 'columnt', 'cat_names': ['column1'], 'cont_names': ['column2'], 'test_df': {'has_test': false, 'csv_name': null}}, 'transform': {'FillMissing': {'fill_strategy': 'MEDIAN', 'add_col': true, 'fill_val': 0}, 'Categorify': true, 'Normalize': true, 'Datetime': {'cols': [], 'cyclic': false}}, 'model': {'type': 'default', 'default': {'out_sz': null, 'layers': null, 'emb_drop': 0, 'ps': null, 'y_range': null, 'use_bn': true, 'bn_final': false}, 'custom': {'layers': [], 'extra_args': {'bn_begin': false}}}}, 'test_df': null, 'vision': {'subtask': 'object-detection', 'input': {'method': 'from_folder', 'from_folder': {'path': 'data/coco_tiny', 'extensions': null, 'recurse': true, 'exclude': null, 'include': null, 'processor': null, 'presort': false}, 'from_csv': {'csv_name': null, 'path': null, 'cols': 0, 'delimiter': null, 'header': 'infer', 'processor': null}}, 'classification-single-label': {}, 'classification-multi-label': {}, 'regression': {}, 'segmentation': {}, 'gan': {'noise_sz': 100}, 'object-detection': {}, 'points': {}, 'transform': {'size': 24, 'data_aug': ['basic_transforms', 'zoom_crop', 'manual'], 'chosen_data_aug': 'manual', 'basic_transforms': {'do_flip': true, 'flip_vert': false, 'max_rotate': 10.0, 'max_zoom': 1, 'max_lighting': 0.8, 'max_warp': 0.2, 'p_affine': 0.75, 'p_lighting': 0.75}, 'zoom_crop': {'scale': [0.75, 2], 'do_rand': true, 'p': 1.0}, 'manual': {'brightness': {'change': 0.5}, 'contrast': {'scale': 1.0}, 'crop': {'size': 300, 'row_pct': 0.5, 'col_pct': 0.5}, 'crop_pad': {'size': 300, 'padding_mode': 'reflection', 'row_pct': 0.5, 'col_pct': 0.5}, 'dihedral': {'k': 0}, 'dihedral_affine': {'k': 0}, 'flip_lr': {}, 'flip_affine': {}, 'jitter': {'magnitude': 0.0}, 'pad': {'padding': 50, 'available_modes': ['zeros', 'border', 'reflection'], 'mode': 'reflection'}, 'rotate': {'degrees': 0.0}, 'rgb_randomize': {'channels': ['Red', 'Green', 'Blue'], 'chosen_channels': 'Red', 'thresh': [0.2, 0.595, 0.99], 'chosen_thresh': 0.2}, 'skew': {'direction': 0, 'magnitude': 0, 'invert': false}, 'squish': {'scale': 1.0, 'row_pct': 0.5, 'col_pct': 0.5}, 'symmetric_wrap': {'magnitude': [-0.2, 0.2]}, 'tilt': {'direction': 0, 'magnitude': 0}, 'zoom': {'scale': 1.0, 'row_pct': 0.5, 'col_pct': 0.5}, 'cutout': {'n_holes': 1, 'length': 40}}}}}
__author__ = 'saeedamen' # Saeed Amen / saeed@thalesians.com # # Copyright 2015 Thalesians Ltd. - http//www.thalesians.com / @thalesians # # 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. # """ TechParams Holds parameters for calculation of technical indicators """ class TechParams: pass # TODO add specific fields so can error check fields
__author__ = 'saeedamen' '\nTechParams\n\nHolds parameters for calculation of technical indicators\n\n' class Techparams: pass
def find_best_step(v): """ Returns best solution for given value :param v: value :return: best solution or None when no any solutions available """ s = bin(v)[2:] r = s.find("0") l = len(s) - r if (r == -1) or ((l - 1) < 0): return None return 1 << (l - 1) def play_game_bool(task): """ Solves one task for game :param task: :return: """ win_games_count = 0 while True: # looking for best solution for current task bst = find_best_step(task) if bst is None: break task -= bst win_games_count += 1 return win_games_count % 2 == 1 def game_result_to_string(result): return "PAT" if result else "MAT"
def find_best_step(v): """ Returns best solution for given value :param v: value :return: best solution or None when no any solutions available """ s = bin(v)[2:] r = s.find('0') l = len(s) - r if r == -1 or l - 1 < 0: return None return 1 << l - 1 def play_game_bool(task): """ Solves one task for game :param task: :return: """ win_games_count = 0 while True: bst = find_best_step(task) if bst is None: break task -= bst win_games_count += 1 return win_games_count % 2 == 1 def game_result_to_string(result): return 'PAT' if result else 'MAT'
class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = {} for i in nums: if i in seen: return True seen[i] = 1 return False
class Solution: def contains_duplicate(self, nums: List[int]) -> bool: seen = {} for i in nums: if i in seen: return True seen[i] = 1 return False
class Node(object): def __init__(self, val=None): self.val = val self.next = None class SinglyLinkedList(object): def __init__(self): self.head = None def traverse_list(self): """.""" root = self.head while root is not None: print(root.val) root = root.next def insert(self, new_data): """.""" new_node = Node(new_data) # Update the new nodes next pointer to existing head new_node.next = self.head self.head = new_node def insert_at_end(self, new_data): """.""" new_node = Node(new_data) # Check if there ll is empty if self.head is None: self.head = new_node return # Find the last node in ll last = self.head while last.next: last = last.next # Attach the last elements next pointer to the new node last.next = new_node def insert_in_between(self, middle_node, new_data): """.""" # Raise exception if the middle node is not None if middle_node is None: raise Exception('Given node can not be None.') new_node = Node(new_data) new_node.next = middle_node.next middle_node.next = new_node def remove(self, remove_val): """.""" cur = self.head # Check if the value we are removing is the head if cur is not None: if cur.val == remove_val: self.head = cur.next cur = None return # Traverse the ll while cur is not None: # If we found the correct value break loop if cur.val == remove_val: break prev = cur cur = cur.next # Check if we have traversed the entire ll and not found the value if cur == None: return # Set prev pointer to cur.next prev.next = cur.next # Set cur to None (not needed since python has garbage collection) cur = None
class Node(object): def __init__(self, val=None): self.val = val self.next = None class Singlylinkedlist(object): def __init__(self): self.head = None def traverse_list(self): """.""" root = self.head while root is not None: print(root.val) root = root.next def insert(self, new_data): """.""" new_node = node(new_data) new_node.next = self.head self.head = new_node def insert_at_end(self, new_data): """.""" new_node = node(new_data) if self.head is None: self.head = new_node return last = self.head while last.next: last = last.next last.next = new_node def insert_in_between(self, middle_node, new_data): """.""" if middle_node is None: raise exception('Given node can not be None.') new_node = node(new_data) new_node.next = middle_node.next middle_node.next = new_node def remove(self, remove_val): """.""" cur = self.head if cur is not None: if cur.val == remove_val: self.head = cur.next cur = None return while cur is not None: if cur.val == remove_val: break prev = cur cur = cur.next if cur == None: return prev.next = cur.next cur = None
d = {"a": 1, "b": 2, "c": 3} sum=0 for i in d: sum+=d.get(i) print(sum)
d = {'a': 1, 'b': 2, 'c': 3} sum = 0 for i in d: sum += d.get(i) print(sum)
def triple_sum(nums): result = [] for i in nums: for j in nums: for k in nums: j_is_unique = j != i and j != k k_is_unique = k != i sum_is_zero = (i + j + k) == 0 if j_is_unique and k_is_unique and sum_is_zero: if set([i,j,k]) not in result: result.append(set([i,j,k])) return result if __name__ == '__main__': nums = set([0, -1, 2, -3, 1]) print(triple_sum(nums))
def triple_sum(nums): result = [] for i in nums: for j in nums: for k in nums: j_is_unique = j != i and j != k k_is_unique = k != i sum_is_zero = i + j + k == 0 if j_is_unique and k_is_unique and sum_is_zero: if set([i, j, k]) not in result: result.append(set([i, j, k])) return result if __name__ == '__main__': nums = set([0, -1, 2, -3, 1]) print(triple_sum(nums))
class Solution: def tribonacci(self, n: int) -> int: # fib = [0]*41 # fib[0] = 0 # fib[1] = 1 # fib [2] = 1 # for i in range(n+1): # fib[i+3] = fib[i] + fib[i+1] + fib[i+2] # return fib[n] dp = [0, 1, 1] for i in range(3, n + 1): dp[i % 3] = sum(dp) return dp[n % 3] """ def tribonacci(self, n): a, b, c = 0, 1, 1 for _ in range(n): a, b, c = b, c, a + b + c return c int tribonacci(int n) { int dp[3] = {0, 1, 1}; for (int i = 3; i <= n; ++i) dp[i%3] += dp[(i+1)%3] + dp[(i+2)%3]; return dp[n%3]; } """
class Solution: def tribonacci(self, n: int) -> int: dp = [0, 1, 1] for i in range(3, n + 1): dp[i % 3] = sum(dp) return dp[n % 3] '\n def tribonacci(self, n):\n a, b, c = 0, 1, 1\n for _ in range(n): a, b, c = b, c, a + b + c\n return c\n \nint tribonacci(int n) {\n int dp[3] = {0, 1, 1};\n for (int i = 3; i <= n; ++i)\n dp[i%3] += dp[(i+1)%3] + dp[(i+2)%3];\n return dp[n%3];\n}\n'
s=str(input()) n1,n2=[int(e) for e in input().split()] j=0 for i in range(len(s)): if j<n1-1: print(s[j],end="") j+=1 elif j>=n1-1: j=n2 if j>=n1: print(s[j],end="") j-=1 elif j<=k: print(s[j],end="") j+=1 k=n2-1
s = str(input()) (n1, n2) = [int(e) for e in input().split()] j = 0 for i in range(len(s)): if j < n1 - 1: print(s[j], end='') j += 1 elif j >= n1 - 1: j = n2 if j >= n1: print(s[j], end='') j -= 1 elif j <= k: print(s[j], end='') j += 1 k = n2 - 1
def mapDict(d, mapF): result = {} for key in d: mapped = mapF(key, d[key]) if mapped != None: result[key] = mapped return result withPath = mapDict(houseClosestObj, lambda house, obj: { "target": obj, "path": houseObjPaths[house][obj]}) with open("houseClosestObj.json", "w") as fp: json.dump(withPath, fp)
def map_dict(d, mapF): result = {} for key in d: mapped = map_f(key, d[key]) if mapped != None: result[key] = mapped return result with_path = map_dict(houseClosestObj, lambda house, obj: {'target': obj, 'path': houseObjPaths[house][obj]}) with open('houseClosestObj.json', 'w') as fp: json.dump(withPath, fp)
# rounds a number to the nearest even number # Author: Isabella Doyle num = float(input("Enter a number: ")) round = round(num) print('{} rounded is {}'.format(num, round))
num = float(input('Enter a number: ')) round = round(num) print('{} rounded is {}'.format(num, round))
def main(): print('This is printed from testfile.py') if __name__=='__main__': main()
def main(): print('This is printed from testfile.py') if __name__ == '__main__': main()
"""Lexicon exceptions module""" class ProviderNotAvailableError(Exception): """ Custom exception to raise when a provider is not available, typically because some optional dependencies are missing """
"""Lexicon exceptions module""" class Providernotavailableerror(Exception): """ Custom exception to raise when a provider is not available, typically because some optional dependencies are missing """
def _get_main(ctx): if ctx.file.main: return ctx.file.main.path main = ctx.label.name + ".py" for src in ctx.files.srcs: if src.basename == main: return src.path fail( "corresponding default '{}' does not appear in srcs. ".format(main) + "Add it or override default file name with a 'main' attribute", ) def _conda_impl(ctx): env = ctx.attr.env launcher = ctx.actions.declare_file(ctx.label.name) args = ctx.actions.args() args.add(ctx.file.launcher) args.add(launcher) ctx.actions.run_shell( inputs = [ctx.file.launcher], outputs = [launcher], arguments = [args], command = "cp $1 $2", ) launcher_main = ctx.actions.declare_file(ctx.label.name + ".main") ctx.actions.write( output = launcher_main, content = _get_main(ctx), ) runfiles = ctx.runfiles( collect_data = True, collect_default = True, files = ctx.files.srcs, symlinks = { ".main": launcher_main, }, root_symlinks = { ".cenv": env.files.to_list()[0], ".main": launcher_main, }, ) return [DefaultInfo(executable = launcher, runfiles = runfiles)] _conda_attrs = { "srcs": attr.label_list(allow_files = [".py"]), "data": attr.label_list(allow_files = True), "deps": attr.label_list(), "env": attr.label( mandatory = True, allow_files = True, ), "main": attr.label(allow_single_file = [".py"]), "launcher": attr.label( default = Label("//tools/conda_run"), allow_single_file = True, ), } _conda_binary = rule( attrs = _conda_attrs, executable = True, implementation = _conda_impl, ) _conda_test = rule( attrs = _conda_attrs, test = True, implementation = _conda_impl, ) def conda_binary(tags = [], **kwargs): _conda_binary(tags = tags + ["conda"], **kwargs) def conda_test(tags = [], **kwargs): _conda_test(tags = tags + ["conda"], **kwargs)
def _get_main(ctx): if ctx.file.main: return ctx.file.main.path main = ctx.label.name + '.py' for src in ctx.files.srcs: if src.basename == main: return src.path fail("corresponding default '{}' does not appear in srcs. ".format(main) + "Add it or override default file name with a 'main' attribute") def _conda_impl(ctx): env = ctx.attr.env launcher = ctx.actions.declare_file(ctx.label.name) args = ctx.actions.args() args.add(ctx.file.launcher) args.add(launcher) ctx.actions.run_shell(inputs=[ctx.file.launcher], outputs=[launcher], arguments=[args], command='cp $1 $2') launcher_main = ctx.actions.declare_file(ctx.label.name + '.main') ctx.actions.write(output=launcher_main, content=_get_main(ctx)) runfiles = ctx.runfiles(collect_data=True, collect_default=True, files=ctx.files.srcs, symlinks={'.main': launcher_main}, root_symlinks={'.cenv': env.files.to_list()[0], '.main': launcher_main}) return [default_info(executable=launcher, runfiles=runfiles)] _conda_attrs = {'srcs': attr.label_list(allow_files=['.py']), 'data': attr.label_list(allow_files=True), 'deps': attr.label_list(), 'env': attr.label(mandatory=True, allow_files=True), 'main': attr.label(allow_single_file=['.py']), 'launcher': attr.label(default=label('//tools/conda_run'), allow_single_file=True)} _conda_binary = rule(attrs=_conda_attrs, executable=True, implementation=_conda_impl) _conda_test = rule(attrs=_conda_attrs, test=True, implementation=_conda_impl) def conda_binary(tags=[], **kwargs): _conda_binary(tags=tags + ['conda'], **kwargs) def conda_test(tags=[], **kwargs): _conda_test(tags=tags + ['conda'], **kwargs)
#---------------------------------------------------------------------------------------------------------- # # AUTOMATICALLY GENERATED FILE TO BE USED BY W_HOTBOX # # NAME: Copy Hue/Sat # #---------------------------------------------------------------------------------------------------------- ns = nuke.selectedNodes() for n in ns: n.knob('hue').setValue(1) n.knob('sat').setValue(1) n.knob('lumaMix').setValue(0)
ns = nuke.selectedNodes() for n in ns: n.knob('hue').setValue(1) n.knob('sat').setValue(1) n.knob('lumaMix').setValue(0)
loader=""" d = dict(locals(), **globals()) exec(self.payload, d, d) """
loader = '\nd = dict(locals(), **globals())\nexec(self.payload, d, d)\n'
#!/usr/bin/env python temp = 24 Farenheint = temp * 1.8 + 32 print(Farenheint)
temp = 24 farenheint = temp * 1.8 + 32 print(Farenheint)
# Copyright 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. class ProjectConfig(object): """Contains information about the benchmark runtime environment. Attributes: top_level_dir: A dir that contains benchmark, page test, and/or story set dirs and associated artifacts. benchmark_dirs: A list of dirs containing benchmarks. benchmark_aliases: A dict of name:alias string pairs to be matched against exactly during benchmark selection. client_configs: A list of paths to a ProjectDependencies json files. default_chrome_root: A path to chromium source directory. Many telemetry features depend on chromium source tree's presence and those won't work in case this is not specified. """ def __init__(self, top_level_dir, benchmark_dirs=None, benchmark_aliases=None, client_configs=None, default_chrome_root=None): self._top_level_dir = top_level_dir self._benchmark_dirs = benchmark_dirs or [] self._benchmark_aliases = benchmark_aliases or dict() self._client_configs = client_configs or [] self._default_chrome_root = default_chrome_root @property def top_level_dir(self): return self._top_level_dir @property def start_dirs(self): return self._benchmark_dirs @property def benchmark_dirs(self): return self._benchmark_dirs @property def benchmark_aliases(self): return self._benchmark_aliases @property def client_configs(self): return self._client_configs @property def default_chrome_root(self): return self._default_chrome_root
class Projectconfig(object): """Contains information about the benchmark runtime environment. Attributes: top_level_dir: A dir that contains benchmark, page test, and/or story set dirs and associated artifacts. benchmark_dirs: A list of dirs containing benchmarks. benchmark_aliases: A dict of name:alias string pairs to be matched against exactly during benchmark selection. client_configs: A list of paths to a ProjectDependencies json files. default_chrome_root: A path to chromium source directory. Many telemetry features depend on chromium source tree's presence and those won't work in case this is not specified. """ def __init__(self, top_level_dir, benchmark_dirs=None, benchmark_aliases=None, client_configs=None, default_chrome_root=None): self._top_level_dir = top_level_dir self._benchmark_dirs = benchmark_dirs or [] self._benchmark_aliases = benchmark_aliases or dict() self._client_configs = client_configs or [] self._default_chrome_root = default_chrome_root @property def top_level_dir(self): return self._top_level_dir @property def start_dirs(self): return self._benchmark_dirs @property def benchmark_dirs(self): return self._benchmark_dirs @property def benchmark_aliases(self): return self._benchmark_aliases @property def client_configs(self): return self._client_configs @property def default_chrome_root(self): return self._default_chrome_root
expected_output = { 'id':{ 101: { 'connection': 0, 'name': 'grpc-tcp', 'state': 'Resolving', 'explanation': 'Resolution request in progress' } } }
expected_output = {'id': {101: {'connection': 0, 'name': 'grpc-tcp', 'state': 'Resolving', 'explanation': 'Resolution request in progress'}}}
dolares = input('Cuantos dolares tienes?: ') dolares = float(dolares) valor_dolar = 0.045 peso = dolares / valor_dolar peso = round(peso,2) peso = str(peso) print('Tienes $' + peso + ' Pesos')
dolares = input('Cuantos dolares tienes?: ') dolares = float(dolares) valor_dolar = 0.045 peso = dolares / valor_dolar peso = round(peso, 2) peso = str(peso) print('Tienes $' + peso + ' Pesos')
class dforest(object): """union-find with union-by-rank and path compression""" def __init__(self,cap=100): """creates a disjoint forest with the given capacity""" self.__parent = [ i for i in range(cap) ] self.__rank = [ 0 for i in range(cap) ] self.__count = [ 1 for i in range(cap) ] self.__ccount = cap def __str__(self): """return the string representation of the disjoint forest""" return str(self.__parent) def __len__(self): """return the length of the disjoint forest""" return len(self.__parent) def find(self,x): """return the representative of x in the disjoint forest""" ans = self.__parent[x] if ans!=x: self.__parent[x] = ans = self.find(ans) return ans def findCount(self, x): return self.__count[self.find(x)] def getAllCounts(self): return self.__count def union(self,x,y): """union of the trees of x and y""" rx,ry = self.find(x),self.find(y) if rx!=ry: kx,ky = self.__rank[rx],self.__rank[ry] if kx>=ky: self.__parent[ry] = rx self.__count[rx] += self.__count[ry] if kx==ky: self.__rank[rx] += 1 else: self.__parent[rx] = ry self.__count[ry] += self.__count[rx] self.__ccount -= 1 def ccount(self): """return the number of trees in the dijoint forest""" return self.__ccount def toMatrix(self, rows): matrix = [] cols = len(self.__parent) // rows for r in range(rows): #print("r", r, "(rows-1)*r", (rows-1)*r, "cols", cols, "(rows-1)*r+cols", (rows-1)*r+cols) matrix.append([x for x in self.__parent[(cols)*r:(cols)*r+cols]]) return matrix def maxCountParent(self): return self.find(self.__count.index(max(self.__count))) def maxCount(self): return max(self.__count) def setCount(self, x, count): """ Manually sets count """ self.__count[x] = count if __name__ == "__main__": forest = dforest(20) for i in range(19): #print(forest.getAllCounts()) #print(forest) #forest.union(i, i+1) pass print(forest.getAllCounts()) print(forest) print(forest.toMatrix(5))
class Dforest(object): """union-find with union-by-rank and path compression""" def __init__(self, cap=100): """creates a disjoint forest with the given capacity""" self.__parent = [i for i in range(cap)] self.__rank = [0 for i in range(cap)] self.__count = [1 for i in range(cap)] self.__ccount = cap def __str__(self): """return the string representation of the disjoint forest""" return str(self.__parent) def __len__(self): """return the length of the disjoint forest""" return len(self.__parent) def find(self, x): """return the representative of x in the disjoint forest""" ans = self.__parent[x] if ans != x: self.__parent[x] = ans = self.find(ans) return ans def find_count(self, x): return self.__count[self.find(x)] def get_all_counts(self): return self.__count def union(self, x, y): """union of the trees of x and y""" (rx, ry) = (self.find(x), self.find(y)) if rx != ry: (kx, ky) = (self.__rank[rx], self.__rank[ry]) if kx >= ky: self.__parent[ry] = rx self.__count[rx] += self.__count[ry] if kx == ky: self.__rank[rx] += 1 else: self.__parent[rx] = ry self.__count[ry] += self.__count[rx] self.__ccount -= 1 def ccount(self): """return the number of trees in the dijoint forest""" return self.__ccount def to_matrix(self, rows): matrix = [] cols = len(self.__parent) // rows for r in range(rows): matrix.append([x for x in self.__parent[cols * r:cols * r + cols]]) return matrix def max_count_parent(self): return self.find(self.__count.index(max(self.__count))) def max_count(self): return max(self.__count) def set_count(self, x, count): """ Manually sets count """ self.__count[x] = count if __name__ == '__main__': forest = dforest(20) for i in range(19): pass print(forest.getAllCounts()) print(forest) print(forest.toMatrix(5))
load(":collect_export_declaration.bzl", "collect_export_declaration") load(":collect_header_declaration.bzl", "collect_header_declaration") load(":collect_link_declaration.bzl", "collect_link_declaration") load(":collect_umbrella_dir_declaration.bzl", "collect_umbrella_dir_declaration") load(":collection_results.bzl", "collection_results") load(":errors.bzl", "errors") load(":tokens.bzl", "tokens", rws = "reserved_words", tts = "token_types") load("@bazel_skylib//lib:sets.bzl", "sets") _unsupported_module_members = sets.make([ rws.config_macros, rws.conflict, rws.requires, rws.use, ]) def collect_module_members(parsed_tokens): tlen = len(parsed_tokens) members = [] consumed_count = 0 open_members_token, err = tokens.get_as(parsed_tokens, 0, tts.curly_bracket_open, count = tlen) if err != None: return None, err consumed_count += 1 skip_ahead = 0 collect_result = None prefix_tokens = [] for idx in range(consumed_count, tlen - consumed_count): consumed_count += 1 if skip_ahead > 0: skip_ahead -= 1 continue collect_result = None # Get next token token, err = tokens.get(parsed_tokens, idx, count = tlen) if err != None: return None, err # Process token if tokens.is_a(token, tts.curly_bracket_close): if len(prefix_tokens) > 0: return None, errors.new( "Unexpected prefix tokens found at end of module member block. tokens: %s" % (prefix_tokens), ) break elif tokens.is_a(token, tts.newline): if len(prefix_tokens) > 0: return None, errors.new( "Unexpected prefix tokens found before end of line. tokens: %s" % (prefix_tokens), ) elif tokens.is_a(token, tts.reserved, rws.umbrella): # The umbrella word can appear for umbrella headers or umbrella directories. # If the next token is header, then it is an umbrella header. Otherwise, it is an umbrella # directory. next_idx = idx + 1 next_token, err = tokens.get(parsed_tokens, next_idx, count = tlen) if err != None: return None, err if tokens.is_a(next_token, tts.reserved, rws.header): prefix_tokens.append(token) else: if len(prefix_tokens) > 0: return None, errors.new( "Unexpected prefix tokens found before end of line. tokens: %" % (prefix_tokens), ) collect_result, err = collect_umbrella_dir_declaration(parsed_tokens[idx:]) elif tokens.is_a(token, tts.reserved, rws.header): collect_result, err = collect_header_declaration(parsed_tokens[idx:], prefix_tokens) prefix_tokens = [] elif tokens.is_a(token, tts.reserved, rws.export): collect_result, err = collect_export_declaration(parsed_tokens[idx:]) elif tokens.is_a(token, tts.reserved, rws.link): collect_result, err = collect_link_declaration(parsed_tokens[idx:]) elif tokens.is_a(token, tts.reserved) and sets.contains(_unsupported_module_members, token.value): return None, errors.new("Unsupported module member token. token: %s" % (token)) else: # Store any unrecognized tokens as prefix tokens to be processed later prefix_tokens.append(token) # Handle index advancement. if err != None: return None, err if collect_result: members.extend(collect_result.declarations) skip_ahead = collect_result.count - 1 return collection_results.new(members, consumed_count), None
load(':collect_export_declaration.bzl', 'collect_export_declaration') load(':collect_header_declaration.bzl', 'collect_header_declaration') load(':collect_link_declaration.bzl', 'collect_link_declaration') load(':collect_umbrella_dir_declaration.bzl', 'collect_umbrella_dir_declaration') load(':collection_results.bzl', 'collection_results') load(':errors.bzl', 'errors') load(':tokens.bzl', 'tokens', rws='reserved_words', tts='token_types') load('@bazel_skylib//lib:sets.bzl', 'sets') _unsupported_module_members = sets.make([rws.config_macros, rws.conflict, rws.requires, rws.use]) def collect_module_members(parsed_tokens): tlen = len(parsed_tokens) members = [] consumed_count = 0 (open_members_token, err) = tokens.get_as(parsed_tokens, 0, tts.curly_bracket_open, count=tlen) if err != None: return (None, err) consumed_count += 1 skip_ahead = 0 collect_result = None prefix_tokens = [] for idx in range(consumed_count, tlen - consumed_count): consumed_count += 1 if skip_ahead > 0: skip_ahead -= 1 continue collect_result = None (token, err) = tokens.get(parsed_tokens, idx, count=tlen) if err != None: return (None, err) if tokens.is_a(token, tts.curly_bracket_close): if len(prefix_tokens) > 0: return (None, errors.new('Unexpected prefix tokens found at end of module member block. tokens: %s' % prefix_tokens)) break elif tokens.is_a(token, tts.newline): if len(prefix_tokens) > 0: return (None, errors.new('Unexpected prefix tokens found before end of line. tokens: %s' % prefix_tokens)) elif tokens.is_a(token, tts.reserved, rws.umbrella): next_idx = idx + 1 (next_token, err) = tokens.get(parsed_tokens, next_idx, count=tlen) if err != None: return (None, err) if tokens.is_a(next_token, tts.reserved, rws.header): prefix_tokens.append(token) else: if len(prefix_tokens) > 0: return (None, errors.new('Unexpected prefix tokens found before end of line. tokens: %' % prefix_tokens)) (collect_result, err) = collect_umbrella_dir_declaration(parsed_tokens[idx:]) elif tokens.is_a(token, tts.reserved, rws.header): (collect_result, err) = collect_header_declaration(parsed_tokens[idx:], prefix_tokens) prefix_tokens = [] elif tokens.is_a(token, tts.reserved, rws.export): (collect_result, err) = collect_export_declaration(parsed_tokens[idx:]) elif tokens.is_a(token, tts.reserved, rws.link): (collect_result, err) = collect_link_declaration(parsed_tokens[idx:]) elif tokens.is_a(token, tts.reserved) and sets.contains(_unsupported_module_members, token.value): return (None, errors.new('Unsupported module member token. token: %s' % token)) else: prefix_tokens.append(token) if err != None: return (None, err) if collect_result: members.extend(collect_result.declarations) skip_ahead = collect_result.count - 1 return (collection_results.new(members, consumed_count), None)
# GEPPETTO SERVLET MESSAGES class Servlet: LOAD_PROJECT_FROM_URL = 'load_project_from_url' RUN_EXPERIMENT = 'run_experiment' CLIENT_ID = 'client_id' PING = 'ping' class ServletResponse: PROJECT_LOADED = 'project_loaded' GEPPETTO_MODEL_LOADED = 'geppetto_model_loaded' EXPERIMENT_LOADED = 'experiment_loaded' ERROR_RUNNING_EXPERIMENT = 'error_running_experiment' GENERIC_ERROR = 'generic_error' ERROR_LOADING_PROJECT = 'error_loading_project' # GATEWAY MESSAGES class Income: LOAD_MODEL = 'load_model' class Outcome: ERROR = 'error' CONNECTION_CLOSED = 'connection_closed' GEPPETTO_RESPONSE_RECEIVED = 'geppetto_response_received' # ERRORS class PygeppettoDjangoError(): code = None message = None def __init__(self): return {'code': self.code, 'message': self.message} class UknownActionError(PygeppettoDjangoError): code = 400 message = 'UKNOWN_ACTION' class ActionNotFoundError(PygeppettoDjangoError): code = 404 message = 'ACTION_NOT_FOUND'
class Servlet: load_project_from_url = 'load_project_from_url' run_experiment = 'run_experiment' client_id = 'client_id' ping = 'ping' class Servletresponse: project_loaded = 'project_loaded' geppetto_model_loaded = 'geppetto_model_loaded' experiment_loaded = 'experiment_loaded' error_running_experiment = 'error_running_experiment' generic_error = 'generic_error' error_loading_project = 'error_loading_project' class Income: load_model = 'load_model' class Outcome: error = 'error' connection_closed = 'connection_closed' geppetto_response_received = 'geppetto_response_received' class Pygeppettodjangoerror: code = None message = None def __init__(self): return {'code': self.code, 'message': self.message} class Uknownactionerror(PygeppettoDjangoError): code = 400 message = 'UKNOWN_ACTION' class Actionnotfounderror(PygeppettoDjangoError): code = 404 message = 'ACTION_NOT_FOUND'
# 2. Using the dictionary created in the previous problem, allow the user to enter a dollar amount # and print out all the products whose price is less than that amount. print('To stop any phase, enter an empty product name.') product_dict = {} while True: product = input('Enter a product name to assign with a price: ') if product == '': break price = input('Enter the product price: ') while price == '': print('You must enter a price for the product.') price = input('Enter the product price: ') product_dict[product] = price amount = input('Enter an amount to check against: ') for product, price in product_dict.items(): if float(price) < float(amount): print(f'{product} costs ${price}')
print('To stop any phase, enter an empty product name.') product_dict = {} while True: product = input('Enter a product name to assign with a price: ') if product == '': break price = input('Enter the product price: ') while price == '': print('You must enter a price for the product.') price = input('Enter the product price: ') product_dict[product] = price amount = input('Enter an amount to check against: ') for (product, price) in product_dict.items(): if float(price) < float(amount): print(f'{product} costs ${price}')
reservation_day = int(input()) reservation_month = int(input()) accommodation_day = int(input()) accommodation_month = int(input()) leaving_day = int(input()) leaving_month = int(input()) discount = 0 price_per_night = 0 discount_days = accommodation_day - 10 days_staying = abs(accommodation_day - leaving_day) if reservation_day <= 1: pass
reservation_day = int(input()) reservation_month = int(input()) accommodation_day = int(input()) accommodation_month = int(input()) leaving_day = int(input()) leaving_month = int(input()) discount = 0 price_per_night = 0 discount_days = accommodation_day - 10 days_staying = abs(accommodation_day - leaving_day) if reservation_day <= 1: pass
# wordcount.py """Contains the wc(file) function.""" def wc(file): """Return the newline, word and character number.""" file = open(file, "r") nl, w, ch = 0, 0, 0 for line in file: nl += 1 w += line.count(" ") + 1 ch += len(line) return nl, w, ch
"""Contains the wc(file) function.""" def wc(file): """Return the newline, word and character number.""" file = open(file, 'r') (nl, w, ch) = (0, 0, 0) for line in file: nl += 1 w += line.count(' ') + 1 ch += len(line) return (nl, w, ch)
s, a, A = list(input()), list('abcdefghijklmnopqrstuvwxyz'), 26 s1, s2 = s[0:len(s) // 2], s[len(s) // 2:len(s)] s1_r, s2_r = sum([a.index(i.lower()) for i in s1]), sum([a.index(i.lower()) for i in s2]) for i in range(len(s1)): s1[i] = a[(s1_r + a.index(s1[i].lower())) % A] for i in range(len(s2)): s2[i] = a[(s2_r + a.index(s2[i].lower())) % A] for i in range(len(s1)): s1[i] = a[(a.index(s2[i].lower()) + a.index(s1[i].lower())) % A] print("".join(s1).upper())
(s, a, a) = (list(input()), list('abcdefghijklmnopqrstuvwxyz'), 26) (s1, s2) = (s[0:len(s) // 2], s[len(s) // 2:len(s)]) (s1_r, s2_r) = (sum([a.index(i.lower()) for i in s1]), sum([a.index(i.lower()) for i in s2])) for i in range(len(s1)): s1[i] = a[(s1_r + a.index(s1[i].lower())) % A] for i in range(len(s2)): s2[i] = a[(s2_r + a.index(s2[i].lower())) % A] for i in range(len(s1)): s1[i] = a[(a.index(s2[i].lower()) + a.index(s1[i].lower())) % A] print(''.join(s1).upper())
def test(): print('hello world') c = color(1,0.2,0.2, 1) print(c) print(c.r) print(c.g) print(c.b) print(c.a) c.a = 0.5 print(c.a) c.b += 0.1 print(c.b) d = c.darkened( 0.9 ) print(d) test()
def test(): print('hello world') c = color(1, 0.2, 0.2, 1) print(c) print(c.r) print(c.g) print(c.b) print(c.a) c.a = 0.5 print(c.a) c.b += 0.1 print(c.b) d = c.darkened(0.9) print(d) test()
out = [] digits =[ "0000001", "1001111", #1 "0010010", "0000110", #3 "1001100", "0100100", #5 "1100000", "0001111", #7 "0000000", "0001100", #9 ] for i in range(10000): s = "{:04d}".format(i) out += ["{:21d} 0 0 {} {} {} {}".format(i, digits[int(s[0])], digits[int(s[1])], digits[int(s[2])], digits[int(s[3])] ) ] f = open ("examples/count.out", "w") f.write("\n".join(out)) f.close()
out = [] digits = ['0000001', '1001111', '0010010', '0000110', '1001100', '0100100', '1100000', '0001111', '0000000', '0001100'] for i in range(10000): s = '{:04d}'.format(i) out += ['{:21d} 0 0 {} {} {} {}'.format(i, digits[int(s[0])], digits[int(s[1])], digits[int(s[2])], digits[int(s[3])])] f = open('examples/count.out', 'w') f.write('\n'.join(out)) f.close()
def factorial(n): """Does this function work? Hint: no.""" n_fact = n while n > 1: n -= 1 n_fact *= n return n_fact
def factorial(n): """Does this function work? Hint: no.""" n_fact = n while n > 1: n -= 1 n_fact *= n return n_fact
def isIPv4Address(inputString): # Method 1 if len(inputString.split(".")) != 4: return False for x in inputString.split("."): if not x or not x.isnumeric() or (x.isnumeric() and int(x) > 255): return False return True # # Method 2 # # Same as method 1, but with Python functions # p = s.split('.') # return len(p) == 4 and all(n.isdigit() and 0 <= int(n) < 256 for n in p) # # Method 3 # import ipaddress # try: # ipaddress.ip_address(inputString) # except: # return False # return True # # Method 4 # # Using regex # if re.match('\d+\.\d+\.\d+\.\d+$', inputString): # for i in inputString.split('.'): # if not 0<=int(i)<256: # return False # return True # return False inputString = "172.16.254.1" print(isIPv4Address(inputString)) inputString = "172.316.254.1" print(isIPv4Address(inputString)) inputString = ".254.255.0" print(isIPv4Address(inputString)) inputString = "1.1.1.1a" print(isIPv4Address(inputString)) inputString = "0.254.255.0" print(isIPv4Address(inputString)) inputString = "0..1.0" print(isIPv4Address(inputString)) inputString = "1.1.1.1.1" print(isIPv4Address(inputString)) inputString = "1.256.1.1" print(isIPv4Address(inputString)) inputString = "a0.1.1.1" print(isIPv4Address(inputString)) inputString = "0.1.1.256" print(isIPv4Address(inputString)) inputString = "7283728" print(isIPv4Address(inputString))
def is_i_pv4_address(inputString): if len(inputString.split('.')) != 4: return False for x in inputString.split('.'): if not x or not x.isnumeric() or (x.isnumeric() and int(x) > 255): return False return True input_string = '172.16.254.1' print(is_i_pv4_address(inputString)) input_string = '172.316.254.1' print(is_i_pv4_address(inputString)) input_string = '.254.255.0' print(is_i_pv4_address(inputString)) input_string = '1.1.1.1a' print(is_i_pv4_address(inputString)) input_string = '0.254.255.0' print(is_i_pv4_address(inputString)) input_string = '0..1.0' print(is_i_pv4_address(inputString)) input_string = '1.1.1.1.1' print(is_i_pv4_address(inputString)) input_string = '1.256.1.1' print(is_i_pv4_address(inputString)) input_string = 'a0.1.1.1' print(is_i_pv4_address(inputString)) input_string = '0.1.1.256' print(is_i_pv4_address(inputString)) input_string = '7283728' print(is_i_pv4_address(inputString))