content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Solution: def removeDuplicates(self, nums: List[int]) -> int: l = len(nums) if l == 1: return 1 index = 1 num = nums[0] for i in range(1, l): if nums[i] == num: continue num = nums[i] nums[index] = nums[i] index += 1 return index
class Solution: def remove_duplicates(self, nums: List[int]) -> int: l = len(nums) if l == 1: return 1 index = 1 num = nums[0] for i in range(1, l): if nums[i] == num: continue num = nums[i] nums[index] = nums[i] index += 1 return index
''' Define constraints (depends on your problem) https://stackoverflow.com/questions/42303470/scipy-optimize-inequality-constraint-which-side-of-the-inequality-is-considered [0.1268 0.467 0.5834 0.2103 -0.1268 -0.5425 -0.5096 0.0581] . The bounds are +/-30% of this. ''' t_base = [0.1268, 0.467, 0.5834, 0.2103, -0.1268, -0.5425, -0.5096, 0.0581] t_lower = [0.08876, 0.3269, 0.40838, 0.14721, -0.1648, -0.70525, -0.66248, 0.04067] t_upper = [0.1648, 0.6071, 0.75842, 0.27339, -0.08876, -0.37975, -0.35672, 0.07553] def f_factory(i): def f_lower(t): return t[i] - t_lower[i] def f_upper(t): return -t[i] + t_upper[i] return f_lower, f_upper functions = [] for i in range(len(t_base)): f_lower, f_upper = f_factory(i) functions.append(f_lower) functions.append(f_upper) cons=[] for ii in range(len(functions)): # the value of ii is set in each loop cons.append({'type': 'ineq', 'fun': functions[ii]}) if __name__ == '__main__': print('Constraints file')
""" Define constraints (depends on your problem) https://stackoverflow.com/questions/42303470/scipy-optimize-inequality-constraint-which-side-of-the-inequality-is-considered [0.1268 0.467 0.5834 0.2103 -0.1268 -0.5425 -0.5096 0.0581] . The bounds are +/-30% of this. """ t_base = [0.1268, 0.467, 0.5834, 0.2103, -0.1268, -0.5425, -0.5096, 0.0581] t_lower = [0.08876, 0.3269, 0.40838, 0.14721, -0.1648, -0.70525, -0.66248, 0.04067] t_upper = [0.1648, 0.6071, 0.75842, 0.27339, -0.08876, -0.37975, -0.35672, 0.07553] def f_factory(i): def f_lower(t): return t[i] - t_lower[i] def f_upper(t): return -t[i] + t_upper[i] return (f_lower, f_upper) functions = [] for i in range(len(t_base)): (f_lower, f_upper) = f_factory(i) functions.append(f_lower) functions.append(f_upper) cons = [] for ii in range(len(functions)): cons.append({'type': 'ineq', 'fun': functions[ii]}) if __name__ == '__main__': print('Constraints file')
__key_mapping = { 'return' : 'enter', 'up_arrow' : 'up', 'down_arrow' : 'down', 'left_arrow' : 'left', 'right_arrow' : 'right', 'page_up' : 'pageup', 'page_down' : 'pagedown', } def translate_key(e): if len(e.key) > 0: return __key_mapping[e.key] if e.key in __key_mapping else e.key else: if e.char == '\x08': return 'backspace' elif e.char == '\t': return 'tab' else: return e.key
__key_mapping = {'return': 'enter', 'up_arrow': 'up', 'down_arrow': 'down', 'left_arrow': 'left', 'right_arrow': 'right', 'page_up': 'pageup', 'page_down': 'pagedown'} def translate_key(e): if len(e.key) > 0: return __key_mapping[e.key] if e.key in __key_mapping else e.key elif e.char == '\x08': return 'backspace' elif e.char == '\t': return 'tab' else: return e.key
""" sentry.pool.base ~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ class Pool(object): def __init__(self, keyspace): self.keyspace = keyspace self.queue = [] def put(self, item): self.queue.append(item) def get(self): return self.queue.pop()
""" sentry.pool.base ~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ class Pool(object): def __init__(self, keyspace): self.keyspace = keyspace self.queue = [] def put(self, item): self.queue.append(item) def get(self): return self.queue.pop()
class Solution: def wordPattern(self, pattern: str, str: str) -> bool: lst = str.split() combo = zip(pattern, lst) return len(set(pattern)) == len(set(lst)) == len(set(combo)) and len(pattern) == len(lst)
class Solution: def word_pattern(self, pattern: str, str: str) -> bool: lst = str.split() combo = zip(pattern, lst) return len(set(pattern)) == len(set(lst)) == len(set(combo)) and len(pattern) == len(lst)
soma_idade=0 media_Idade=0 maior_idade_homem=0 nome_velho='' tot_mulher_20=0 for i in range(0,4): nome=str(input('Nome: ')).strip() idade=int(input('Idade: ')) sexo=str(input('Sexo: ')).strip() soma_idade+=idade if i==1 and sexo in 'Mm': maior_idade_homem=idade nome_velho=nome elif sexo in 'Mm' and idade>maior_idade_homem: maior_idade_homem=idade nome_velho=nome if sexo in 'Ff' and idade <20: tot_mulher_20+=1 media_Idade=soma_idade/4 print(media_Idade) print(maior_idade_homem,nome_velho) print(tot_mulher_20())
soma_idade = 0 media__idade = 0 maior_idade_homem = 0 nome_velho = '' tot_mulher_20 = 0 for i in range(0, 4): nome = str(input('Nome: ')).strip() idade = int(input('Idade: ')) sexo = str(input('Sexo: ')).strip() soma_idade += idade if i == 1 and sexo in 'Mm': maior_idade_homem = idade nome_velho = nome elif sexo in 'Mm' and idade > maior_idade_homem: maior_idade_homem = idade nome_velho = nome if sexo in 'Ff' and idade < 20: tot_mulher_20 += 1 media__idade = soma_idade / 4 print(media_Idade) print(maior_idade_homem, nome_velho) print(tot_mulher_20())
# -*- coding: utf-8 -*- """ Created on Fri Jan 31 11:53:09 2020 @author: aboutet """ def street_pattern_before(es, infos, insert): return {} def street_pattern(es, infos, data, documents): to_send = [] for json in data: if "LINK_ID" in json.keys(): link_id = "LINK_ID" else: link_id = "LINK_PVID" r = es.search(index=infos["here"], body={"query": {"match": {"LINK_ID": json[link_id]}}})["hits"]["hits"] json["TRAVEL_DIRECTION"] = True if json["TRAVEL_DIRECTION"] == "T" else False if r: if "geometry" in json: del json["geometry"] to_send.append({"update":{"_id":r[0]["_id"]}}) to_send.append({"doc": {key:value for key, value in json.items()}}) if to_send: resp = es.bulk(index=infos["here"], body=to_send, request_timeout=3000) def street_pattern_after(es, infos): return
""" Created on Fri Jan 31 11:53:09 2020 @author: aboutet """ def street_pattern_before(es, infos, insert): return {} def street_pattern(es, infos, data, documents): to_send = [] for json in data: if 'LINK_ID' in json.keys(): link_id = 'LINK_ID' else: link_id = 'LINK_PVID' r = es.search(index=infos['here'], body={'query': {'match': {'LINK_ID': json[link_id]}}})['hits']['hits'] json['TRAVEL_DIRECTION'] = True if json['TRAVEL_DIRECTION'] == 'T' else False if r: if 'geometry' in json: del json['geometry'] to_send.append({'update': {'_id': r[0]['_id']}}) to_send.append({'doc': {key: value for (key, value) in json.items()}}) if to_send: resp = es.bulk(index=infos['here'], body=to_send, request_timeout=3000) def street_pattern_after(es, infos): return
"""The LinkedList code from before is provided below. Add three functions to the LinkedList. "get_position" returns the element at a certain position. The "insert" function will add an element to a particular spot in the list. "delete" will delete the first element with that particular value. Then, use "Test Run" and "Submit" to run the test cases at the bottom.""" class Element(object): def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element def __get__(self, node, counter): if node is None: return None if counter == 0: return node return self.__get__(node.next, counter - 1) def get_position(self, position): """Get an element from a particular position. Assume the first position is "1". Return "None" if position is not in the list.""" return self.__get__(self.head, position - 1) def __insert__(self, node, new_element, counter): if node is None: return new_element if counter == 0: new_element.next = node return new_element node.next = self.__insert__(node.next, new_element, counter - 1) return node def insert(self, new_element, position): """Insert a new node at the given position. Assume the first position is "1". Inserting at position 3 means between the 2nd and 3rd elements.""" self.head = self.__insert__(self.head, new_element, position - 1) def __delete_position__(self, node, value): if node is None: return None if node.value == value: return node.next node.next = self.__delete_position__(node.next, value) return node def delete(self, value): self.head = self.__delete_position__(self.head, value) if __name__ == '__main__': # Test cases # Set up some Elements e1 = Element(1) e2 = Element(2) e3 = Element(3) e4 = Element(4) # Start setting up a LinkedList ll = LinkedList(e1) ll.append(e2) ll.append(e3) # Test get_position # Should print 3 print(ll.head.next.next.value) # Should also print 3 print(ll.get_position(3).value) # Test insert ll.insert(e4, 3) # Should print 4 now print(ll.get_position(3).value) # Test delete ll.delete(1) # Should print 2 now print(ll.get_position(1).value) # Should print 4 now print(ll.get_position(2).value) # Should print 3 now print(ll.get_position(3).value)
"""The LinkedList code from before is provided below. Add three functions to the LinkedList. "get_position" returns the element at a certain position. The "insert" function will add an element to a particular spot in the list. "delete" will delete the first element with that particular value. Then, use "Test Run" and "Submit" to run the test cases at the bottom.""" class Element(object): def __init__(self, value): self.value = value self.next = None class Linkedlist(object): def __init__(self, head=None): self.head = head def append(self, new_element): current = self.head if self.head: while current.next: current = current.next current.next = new_element else: self.head = new_element def __get__(self, node, counter): if node is None: return None if counter == 0: return node return self.__get__(node.next, counter - 1) def get_position(self, position): """Get an element from a particular position. Assume the first position is "1". Return "None" if position is not in the list.""" return self.__get__(self.head, position - 1) def __insert__(self, node, new_element, counter): if node is None: return new_element if counter == 0: new_element.next = node return new_element node.next = self.__insert__(node.next, new_element, counter - 1) return node def insert(self, new_element, position): """Insert a new node at the given position. Assume the first position is "1". Inserting at position 3 means between the 2nd and 3rd elements.""" self.head = self.__insert__(self.head, new_element, position - 1) def __delete_position__(self, node, value): if node is None: return None if node.value == value: return node.next node.next = self.__delete_position__(node.next, value) return node def delete(self, value): self.head = self.__delete_position__(self.head, value) if __name__ == '__main__': e1 = element(1) e2 = element(2) e3 = element(3) e4 = element(4) ll = linked_list(e1) ll.append(e2) ll.append(e3) print(ll.head.next.next.value) print(ll.get_position(3).value) ll.insert(e4, 3) print(ll.get_position(3).value) ll.delete(1) print(ll.get_position(1).value) print(ll.get_position(2).value) print(ll.get_position(3).value)
# -*- coding: utf-8 -*- """Top-level package for Medzibrod.""" __author__ = """Michal Nalevanko""" __email__ = 'michal.nalevanko@gmail.com' __version__ = '0.1.0'
"""Top-level package for Medzibrod.""" __author__ = 'Michal Nalevanko' __email__ = 'michal.nalevanko@gmail.com' __version__ = '0.1.0'
# Copyright (c) 2020 Samplasion <samplasion@gmail.com> # # This software is released under the MIT License. # https://opensource.org/licenses/MIT TARGET = 2020 def main(): print("=============") print("= AoC Day 1 =") print("=============") print() with open("input.txt") as f: file = f.read() numbers = sorted(list(map(int, file.split("\n")))) phase1(numbers) phase2(numbers) def phase1(numbers): min = 0 max = -1 number = numbers[min] + numbers[max] while number != TARGET: if number > TARGET: max -= 1 else: min += 1 number = numbers[min] + numbers[max] # else: print("There's no pair of numbers that amounts to {}".format(TARGET)) print(f"[Part 1] {numbers[min]} and {numbers[max]} are the numbers that amount to {TARGET}. " + f"Their product is {numbers[min]*numbers[max]}") def phase2(numbers): for i in numbers: for j in numbers: for k in numbers: if i + j + k == TARGET: print(f"[Part 2] {i}, {j} and {k} are the numbers that amount to {TARGET}. " + f"Their product is {i*j*k}") return print(f"There's no group of 3 numbers that sums to {TARGET}.") if __name__ == '__main__': main()
target = 2020 def main(): print('=============') print('= AoC Day 1 =') print('=============') print() with open('input.txt') as f: file = f.read() numbers = sorted(list(map(int, file.split('\n')))) phase1(numbers) phase2(numbers) def phase1(numbers): min = 0 max = -1 number = numbers[min] + numbers[max] while number != TARGET: if number > TARGET: max -= 1 else: min += 1 number = numbers[min] + numbers[max] print(f'[Part 1] {numbers[min]} and {numbers[max]} are the numbers that amount to {TARGET}. ' + f'Their product is {numbers[min] * numbers[max]}') def phase2(numbers): for i in numbers: for j in numbers: for k in numbers: if i + j + k == TARGET: print(f'[Part 2] {i}, {j} and {k} are the numbers that amount to {TARGET}. ' + f'Their product is {i * j * k}') return print(f"There's no group of 3 numbers that sums to {TARGET}.") if __name__ == '__main__': main()
SCHEMA = { # staff-and-student-information "all_students_count": "{short_code}PETALLC", "african_american_count": "{short_code}PETBLAC", "african_american_percent": "{short_code}PETBLAP", "american_indian_count": "{short_code}PETINDC", "american_indian_percent": "{short_code}PETINDP", "asian_count": "{short_code}PETASIC", "asian_percent": "{short_code}PETASIP", "hispanic_count": "{short_code}PETHISC", "hispanic_percent": "{short_code}PETHISP", "pacific_islander_count": "{short_code}PETPCIC", "pacific_islander_percent": "{short_code}PETPCIP", "two_or_more_races_count": "{short_code}PETTWOC", "two_or_more_races_percent": "{short_code}PETTWOP", "white_count": "{short_code}PETWHIC", "white_percent": "{short_code}PETWHIP", "early_childhood_education_count": "{short_code}PETGEEC", "early_childhood_education_percent": "{short_code}PETGEEP", "prek_count": "{short_code}PETGPKC", "prek_percent": "{short_code}PETGPKP", "kindergarten_count": "{short_code}PETGKNC", "kindergarten_percent": "{short_code}PETGKNP", "first_count": "{short_code}PETG01C", "first_percent": "{short_code}PETG01P", "second_count": "{short_code}PETG02C", "second_percent": "{short_code}PETG02P", "third_count": "{short_code}PETG03C", "third_percent": "{short_code}PETG03P", "fourth_count": "{short_code}PETG04C", "fourth_percent": "{short_code}PETG04P", "fifth_count": "{short_code}PETG05C", "fifth_percent": "{short_code}PETG05P", "sixth_count": "{short_code}PETG06C", "sixth_percent": "{short_code}PETG06P", "seventh_count": "{short_code}PETG07C", "seventh_percent": "{short_code}PETG07P", "eighth_count": "{short_code}PETG08C", "eighth_percent": "{short_code}PETG08P", "ninth_count": "{short_code}PETG09C", "ninth_percent": "{short_code}PETG09P", "tenth_count": "{short_code}PETG10C", "tenth_percent": "{short_code}PETG10P", "eleventh_count": "{short_code}PETG11C", "eleventh_percent": "{short_code}PETG11P", "twelfth_count": "{short_code}PETG12C", "twelfth_percent": "{short_code}PETG12P", "at_risk_count": "{short_code}PETRSKC", "at_risk_percent": "{short_code}PETRSKP", "economically_disadvantaged_count": "{short_code}PETECOC", "economically_disadvantaged_percent": "{short_code}PETECOP", "limited_english_proficient_count": "{short_code}PETLEPC", "limited_english_proficient_percent": "{short_code}PETLEPP", "bilingual_esl_count": "{short_code}PETBILC", "bilingual_esl_percent": "{short_code}PETBILP", "career_technical_education_count": "{short_code}PETVOCC", "career_technical_education_percent": "{short_code}PETVOCP", "gifted_and_talented_count": "{short_code}PETGIFC", "gifted_and_talented_percent": "{short_code}PETGIFP", "special_education_count": "{short_code}PETSPEC", "special_education_percent": "{short_code}PETSPEP", "class_size_avg_kindergarten": "{short_code}PCTGKGA", "class_size_avg_first": "{short_code}PCTG01A", "class_size_avg_second": "{short_code}PCTG02A", "class_size_avg_third": "{short_code}PCTG03A", "class_size_avg_fourth": "{short_code}PCTG04A", "class_size_avg_fifth": "{short_code}PCTG05A", "class_size_avg_sixth": "{short_code}PCTG06A", "class_size_avg_mixed_elementary": "{short_code}PCTGMEA", "class_size_avg_secondary_english": "{short_code}PCTENGA", "class_size_avg_secondary_foreign_language": "{short_code}PCTFLAA", "class_size_avg_secondary_math": "{short_code}PCTMATA", "class_size_avg_secondary_science": "{short_code}PCTSCIA", "class_size_avg_secondary_social_studies": "{short_code}PCTSOCA", "students_per_teacher": "{short_code}PSTKIDR", # teacher_avg_tenure is Average Years Experience of Teachers with District "teacher_avg_tenure": "{short_code}PSTTENA", # teacher_avg_experience is Average Years Experience of Teachers "teacher_avg_experience": "{short_code}PSTEXPA", "teacher_avg_base_salary": "{short_code}PSTTOSA", "teacher_avg_beginning_salary": "{short_code}PST00SA", "teacher_avg_1_to_5_year_salary": "{short_code}PST01SA", "teacher_avg_6_to_10_year_salary": "{short_code}PST06SA", "teacher_avg_11_to_20_year_salary": "{short_code}PST11SA", "teacher_avg_20_plus_year_salary": "{short_code}PST20SA", "teacher_total_fte_count": "{short_code}PSTTOFC", "teacher_african_american_fte_count": "{short_code}PSTBLFC", "teacher_american_indian_fte_count": "{short_code}PSTINFC", "teacher_asian_fte_count": "{short_code}PSTASFC", "teacher_hispanic_fte_count": "{short_code}PSTHIFC", "teacher_pacific_islander_fte_count": "{short_code}PSTPIFC", "teacher_two_or_more_races_fte_count": "{short_code}PSTTWFC", "teacher_white_fte_count": "{short_code}PSTWHFC", "teacher_total_fte_percent": "{short_code}PSTTOFC", "teacher_african_american_fte_percent": "{short_code}PSTBLFP", "teacher_american_indian_fte_percent": "{short_code}PSTINFP", "teacher_asian_fte_percent": "{short_code}PSTASFP", "teacher_hispanic_fte_percent": "{short_code}PSTHIFP", "teacher_pacific_islander_fte_percent": "{short_code}PSTPIFP", "teacher_two_or_more_races_fte_percent": "{short_code}PSTTWFP", "teacher_white_fte_percent": "{short_code}PSTWHFP", "teacher_no_degree_count": "{short_code}PSTNOFC", "teacher_bachelors_count": "{short_code}PSTBAFC", "teacher_masters_count": "{short_code}PSTMSFC", "teacher_doctorate_count": "{short_code}PSTPHFC", "teacher_no_degree_percent": "{short_code}PSTNOFP", "teacher_bachelors_percent": "{short_code}PSTBAFP", "teacher_masters_percent": "{short_code}PSTMSFP", "teacher_doctorate_percent": "{short_code}PSTPHFP", # postsecondary-readiness-and-non-staar-performance-indicators # 'college_ready_graduates_english_all_students_count': 'ACRR', "college_ready_graduates_english_all_students_percent": "{short_code}ACRR{year}R", # 'college_ready_graduates_english_african_american_count': 'BCRR', "college_ready_graduates_english_african_american_percent": "{short_code}BCRR{year}R", # 'college_ready_graduates_english_american_indian_count': 'ICRR', "college_ready_graduates_english_american_indian_percent": "{short_code}ICRR{year}R", # 'college_ready_graduates_english_asian_count': '3CRR', "college_ready_graduates_english_asian_percent": "{short_code}3CRR{year}R", # 'college_ready_graduates_english_hispanic_count': 'HCRR', "college_ready_graduates_english_hispanic_percent": "{short_code}HCRR{year}R", # 'college_ready_graduates_english_pacific_islander_count': '4CRR', "college_ready_graduates_english_pacific_islander_percent": "{short_code}4CRR{year}R", # 'college_ready_graduates_english_two_or_more_races_count': '2CRR', "college_ready_graduates_english_two_or_more_races_percent": "{short_code}2CRR{year}R", # 'college_ready_graduates_english_white_count': 'WCRR', "college_ready_graduates_english_white_percent": "{short_code}WCRR{year}R", # 'college_ready_graduates_english_economically_disadvantaged_count': 'ECRR', "college_ready_graduates_english_economically_disadvantaged_percent": "{short_code}ECRR{year}R", # 'college_ready_graduates_english_limited_english_proficient_count': 'LCRR', "college_ready_graduates_english_limited_english_proficient_percent": "{short_code}LCRR{year}R", # 'college_ready_graduates_english_at_risk_count': 'RCRR', "college_ready_graduates_english_at_risk_percent": "{short_code}RCRR{year}R", # 'college_ready_graduates_math_all_students_count': 'ACRM', "college_ready_graduates_math_all_students_percent": "{short_code}ACRM{year}R", # 'college_ready_graduates_math_african_american_count': 'BCRM', "college_ready_graduates_math_african_american_percent": "{short_code}BCRM{year}R", # 'college_ready_graduates_math_american_indian_count': 'ICRM', "college_ready_graduates_math_american_indian_percent": "{short_code}ICRM{year}R", # 'college_ready_graduates_math_asian_count': '3CRM', "college_ready_graduates_math_asian_percent": "{short_code}3CRM{year}R", # 'college_ready_graduates_math_hispanic_count': 'HCRM', "college_ready_graduates_math_hispanic_percent": "{short_code}HCRM{year}R", # 'college_ready_graduates_math_pacific_islander_count': '4CRM', "college_ready_graduates_math_pacific_islander_percent": "{short_code}4CRM{year}R", # 'college_ready_graduates_math_two_or_more_races_count': '2CRM', "college_ready_graduates_math_two_or_more_races_percent": "{short_code}2CRM{year}R", # 'college_ready_graduates_math_white_count': 'WCRM', "college_ready_graduates_math_white_percent": "{short_code}WCRM{year}R", # 'college_ready_graduates_math_economically_disadvantaged_count': 'ECRM', "college_ready_graduates_math_economically_disadvantaged_percent": "{short_code}ECRM{year}R", # 'college_ready_graduates_math_limited_english_proficient_count': 'LCRM', "college_ready_graduates_math_limited_english_proficient_percent": "{short_code}LCRM{year}R", # 'college_ready_graduates_math_at_risk_count': 'RCRM', "college_ready_graduates_math_at_risk_percent": "{short_code}RCRM{year}R", # 'college_ready_graduates_both_all_students_count': 'ACRB', "college_ready_graduates_both_all_students_percent": "{short_code}ACRB{year}R", # 'college_ready_graduates_both_african_american_count': 'BCRB', "college_ready_graduates_both_african_american_percent": "{short_code}BCRB{year}R", # 'college_ready_graduates_both_asian_count': '3CRB', "college_ready_graduates_both_asian_percent": "{short_code}3CRB{year}R", # 'college_ready_graduates_both_hispanic_count': 'HCRB', "college_ready_graduates_both_hispanic_percent": "{short_code}HCRB{year}R", # 'college_ready_graduates_both_american_indian_count': 'ICRB', "college_ready_graduates_both_american_indian_percent": "{short_code}ICRB{year}R", # 'college_ready_graduates_both_pacific_islander_count': '4CRB', "college_ready_graduates_both_pacific_islander_percent": "{short_code}4CRB{year}R", # 'college_ready_graduates_both_two_or_more_races_count': '2CRB', "college_ready_graduates_both_two_or_more_races_percent": "{short_code}2CRB{year}R", # 'college_ready_graduates_both_white_count': 'WCRB', "college_ready_graduates_both_white_percent": "{short_code}WCRB{year}R", # 'college_ready_graduates_both_economically_disadvantaged_count': 'ECRB', "college_ready_graduates_both_economically_disadvantaged_percent": "{short_code}ECRB{year}R", # 'college_ready_graduates_both_limited_english_proficient_count': 'LCRB', "college_ready_graduates_both_limited_english_proficient_percent": "{short_code}LCRB{year}R", # 'college_ready_graduates_both_at_risk_count': 'RCRB', "college_ready_graduates_both_at_risk_percent": "{short_code}RCRB{year}R", "avg_sat_score_all_students": "{short_code}A0CSA{year}R", "avg_sat_score_african_american": "{short_code}B0CSA{year}R", "avg_sat_score_american_indian": "{short_code}I0CSA{year}R", "avg_sat_score_asian": "{short_code}30CSA{year}R", "avg_sat_score_hispanic": "{short_code}H0CSA{year}R", "avg_sat_score_pacific_islander": "{short_code}40CSA{year}R", "avg_sat_score_two_or_more_races": "{short_code}20CSA{year}R", "avg_sat_score_white": "{short_code}W0CSA{year}R", "avg_sat_score_economically_disadvantaged": "{short_code}E0CSA{year}R", "avg_act_score_all_students": "{short_code}A0CAA{year}R", "avg_act_score_african_american": "{short_code}B0CAA{year}R", "avg_act_score_american_indian": "{short_code}I0CAA{year}R", "avg_act_score_asian": "{short_code}30CAA{year}R", "avg_act_score_hispanic": "{short_code}H0CAA{year}R", "avg_act_score_pacific_islander": "{short_code}40CAA{year}R", "avg_act_score_two_or_more_races": "{short_code}20CAA{year}R", "avg_act_score_white": "{short_code}W0CAA{year}R", "avg_act_score_economically_disadvantaged": "{short_code}E0CAA{year}R", # 'ap_ib_all_students_count_above_criterion': 'A0BKA', "ap_ib_all_students_percent_above_criterion": "{short_code}A0BKA{year}R", # 'ap_ib_african_american_count_above_criterion': 'B0BKA', "ap_ib_african_american_percent_above_criterion": "{short_code}B0BKA{year}R", # 'ap_ib_asian_count_above_criterion': '30BKA', "ap_ib_asian_percent_above_criterion": "{short_code}30BKA{year}R", # 'ap_ib_hispanic_count_above_criterion': 'H0BKA', "ap_ib_hispanic_percent_above_criterion": "{short_code}H0BKA{year}R", # 'ap_ib_american_indian_count_above_criterion': 'I0BKA', "ap_ib_american_indian_percent_above_criterion": "{short_code}I0BKA{year}R", # 'ap_ib_pacific_islander_count_above_criterion': '40BKA', "ap_ib_pacific_islander_percent_above_criterion": "{short_code}40BKA{year}R", # 'ap_ib_two_or_more_races_count_above_criterion': '20BKA', "ap_ib_two_or_more_races_percent_above_criterion": "{short_code}20BKA{year}R", # 'ap_ib_white_count_above_criterion': 'W0BKA', "ap_ib_white_percent_above_criterion": "{short_code}W0BKA{year}R", # 'ap_ib_economically_disadvantaged_count_above_criterion': 'E0BKA', "ap_ib_economically_disadvantaged_percent_above_criterion": "{short_code}E0BKA{year}R", "ap_ib_all_students_percent_taking": "{short_code}A0BTA{year}R", "ap_ib_african_american_percent_taking": "{short_code}B0BTA{year}R", "ap_ib_asian_percent_taking": "{short_code}30BTA{year}R", "ap_ib_hispanic_percent_taking": "{short_code}H0BTA{year}R", "ap_ib_american_indian_percent_taking": "{short_code}I0BTA{year}R", "ap_ib_pacific_islander_percent_taking": "{short_code}40BTA{year}R", "ap_ib_two_or_more_races_percent_taking": "{short_code}20BTA{year}R", "ap_ib_white_percent_taking": "{short_code}W0BTA{year}R", "ap_ib_economically_disadvantaged_percent_taking": "{short_code}E0BTA{year}R", # # 'dropout_all_students_count': 'A0912DR', # 'dropout_all_students_percent': 'A0912DR', # # 'dropout_african_american_count': 'B0912DR', # 'dropout_african_american_percent': 'B0912DR', # # 'dropout_asian_count': '30912DR', # 'dropout_asian_percent': '30912DR', # # 'dropout_hispanic_count': 'H0912DR', # 'dropout_hispanic_percent': 'H0912DR', # # 'dropout_american_indian_count': 'I0912DR', # 'dropout_american_indian_percent': 'I0912DR', # # 'dropout_pacific_islander_count': '40912DR', # 'dropout_pacific_islander_percent': '40912DR', # # 'dropout_two_or_more_races_count': '20912DR', # 'dropout_two_or_more_races_percent': '20912DR', # # 'dropout_white_count': 'W0912DR', # 'dropout_white_percent': 'W0912DR', # # 'dropout_at_risk_count': 'R0912DR', # 'dropout_at_risk_percent': 'R0912DR', # # 'dropout_economically_disadvantaged_count': 'E0912DR', # 'dropout_economically_disadvantaged_percent': 'E0912DR', # # 'dropout_limited_english_proficient_count': 'E0912DR', # 'dropout_limited_english_proficient_percent': 'E0912DR', # # 'four_year_graduate_all_students_count': 'AGC4X', # 'four_year_graduate_all_students_percent': 'AGC4X', # # 'four_year_graduate_african_american_count': 'BGC4X', # 'four_year_graduate_african_american_percent': 'BGC4X', # # 'four_year_graduate_american_indian_count': 'IGC4X', # 'four_year_graduate_american_indian_percent': 'IGC4X', # # 'four_year_graduate_asian_count': '3GC4X', # 'four_year_graduate_asian_percent': '3GC4X', # # 'four_year_graduate_hispanic_count': 'HGC4X', # 'four_year_graduate_hispanic_percent': 'HGC4X', # # 'four_year_graduate_pacific_islander_count': '4GC4X', # 'four_year_graduate_pacific_islander_percent': '4GC4X', # # 'four_year_graduate_two_or_more_races_count': '2GC4X', # 'four_year_graduate_two_or_more_races_percent': '2GC4X', # # 'four_year_graduate_white_count': 'WGC4X', # 'four_year_graduate_white_percent': 'WGC4X', # # 'four_year_graduate_at_risk_count': 'RGC4X', # 'four_year_graduate_at_risk_percent': 'RGC4X', # # 'four_year_graduate_economically_disadvantaged_count': 'EGC4X', # 'four_year_graduate_economically_disadvantaged_percent': 'EGC4X', # # 'four_year_graduate_limited_english_proficient_count': 'L3C4X', # 'four_year_graduate_limited_english_proficient_percent': 'L3C4X', # attendence "attendance_rate": "{short_code}A0AT{year}R", # longitudinal-rate # 'dropout_all_students_count': 'A0912DR', "dropout_all_students_percent": "{short_code}A0912DR{year}R", # 'dropout_african_american_count': 'B0912DR', "dropout_african_american_percent": "{short_code}B0912DR{year}R", # 'dropout_asian_count': '30912DR', "dropout_asian_percent": "{short_code}30912DR{year}R", # 'dropout_hispanic_count': 'H0912DR', "dropout_hispanic_percent": "{short_code}H0912DR{year}R", # 'dropout_american_indian_count': 'I0912DR', "dropout_american_indian_percent": "{short_code}I0912DR{year}R", # 'dropout_pacific_islander_count': '40912DR', "dropout_pacific_islander_percent": "{short_code}40912DR{year}R", # 'dropout_two_or_more_races_count': '20912DR', "dropout_two_or_more_races_percent": "{short_code}20912DR{year}R", # 'dropout_white_count': 'W0912DR', "dropout_white_percent": "{short_code}W0912DR{year}R", # 'dropout_at_risk_count': 'R0912DR', "dropout_at_risk_percent": "{short_code}R0912DR{year}R", # 'dropout_economically_disadvantaged_count': 'E0912DR', "dropout_economically_disadvantaged_percent": "{short_code}E0912DR{year}R", # 'dropout_limited_english_proficient_count': 'E0912DR', "dropout_limited_english_proficient_percent": "{short_code}E0912DR{year}R", # 'four_year_graduate_all_students_count': 'AGC4X', "four_year_graduate_all_students_percent": "{short_code}AGC4{suffix}{year}R", # 'four_year_graduate_african_american_count': 'BGC4X', "four_year_graduate_african_american_percent": "{short_code}BGC4{suffix}{year}R", # 'four_year_graduate_american_indian_count': 'IGC4X', "four_year_graduate_american_indian_percent": "{short_code}IGC4{suffix}{year}R", # 'four_year_graduate_asian_count': '3GC4X', "four_year_graduate_asian_percent": "{short_code}3GC4{suffix}{year}R", # 'four_year_graduate_hispanic_count': 'HGC4X', "four_year_graduate_hispanic_percent": "{short_code}HGC4{suffix}{year}R", # 'four_year_graduate_pacific_islander_count': '4GC4X', "four_year_graduate_pacific_islander_percent": "{short_code}4GC4{suffix}{year}R", # 'four_year_graduate_two_or_more_races_count': '2GC4X', "four_year_graduate_two_or_more_races_percent": "{short_code}2GC4{suffix}{year}R", # 'four_year_graduate_white_count': 'WGC4X', "four_year_graduate_white_percent": "{short_code}WGC4{suffix}{year}R", # 'four_year_graduate_at_risk_count': 'RGC4X', "four_year_graduate_at_risk_percent": "{short_code}RGC4{suffix}{year}R", # 'four_year_graduate_economically_disadvantaged_count': 'EGC4X', "four_year_graduate_economically_disadvantaged_percent": "{short_code}EGC4{suffix}{year}R", # 'four_year_graduate_limited_english_proficient_count': 'L3C4X', "four_year_graduate_limited_english_proficient_percent": "{short_code}L3C4{suffix}{year}R", # reference "accountability_rating": "{short_code}_RATING", # accountability "student_achievement_rating": "{short_code}D1G", "school_progress_rating": "{short_code}D2G", "closing_the_gaps_rating": "{short_code}D3G", }
schema = {'all_students_count': '{short_code}PETALLC', 'african_american_count': '{short_code}PETBLAC', 'african_american_percent': '{short_code}PETBLAP', 'american_indian_count': '{short_code}PETINDC', 'american_indian_percent': '{short_code}PETINDP', 'asian_count': '{short_code}PETASIC', 'asian_percent': '{short_code}PETASIP', 'hispanic_count': '{short_code}PETHISC', 'hispanic_percent': '{short_code}PETHISP', 'pacific_islander_count': '{short_code}PETPCIC', 'pacific_islander_percent': '{short_code}PETPCIP', 'two_or_more_races_count': '{short_code}PETTWOC', 'two_or_more_races_percent': '{short_code}PETTWOP', 'white_count': '{short_code}PETWHIC', 'white_percent': '{short_code}PETWHIP', 'early_childhood_education_count': '{short_code}PETGEEC', 'early_childhood_education_percent': '{short_code}PETGEEP', 'prek_count': '{short_code}PETGPKC', 'prek_percent': '{short_code}PETGPKP', 'kindergarten_count': '{short_code}PETGKNC', 'kindergarten_percent': '{short_code}PETGKNP', 'first_count': '{short_code}PETG01C', 'first_percent': '{short_code}PETG01P', 'second_count': '{short_code}PETG02C', 'second_percent': '{short_code}PETG02P', 'third_count': '{short_code}PETG03C', 'third_percent': '{short_code}PETG03P', 'fourth_count': '{short_code}PETG04C', 'fourth_percent': '{short_code}PETG04P', 'fifth_count': '{short_code}PETG05C', 'fifth_percent': '{short_code}PETG05P', 'sixth_count': '{short_code}PETG06C', 'sixth_percent': '{short_code}PETG06P', 'seventh_count': '{short_code}PETG07C', 'seventh_percent': '{short_code}PETG07P', 'eighth_count': '{short_code}PETG08C', 'eighth_percent': '{short_code}PETG08P', 'ninth_count': '{short_code}PETG09C', 'ninth_percent': '{short_code}PETG09P', 'tenth_count': '{short_code}PETG10C', 'tenth_percent': '{short_code}PETG10P', 'eleventh_count': '{short_code}PETG11C', 'eleventh_percent': '{short_code}PETG11P', 'twelfth_count': '{short_code}PETG12C', 'twelfth_percent': '{short_code}PETG12P', 'at_risk_count': '{short_code}PETRSKC', 'at_risk_percent': '{short_code}PETRSKP', 'economically_disadvantaged_count': '{short_code}PETECOC', 'economically_disadvantaged_percent': '{short_code}PETECOP', 'limited_english_proficient_count': '{short_code}PETLEPC', 'limited_english_proficient_percent': '{short_code}PETLEPP', 'bilingual_esl_count': '{short_code}PETBILC', 'bilingual_esl_percent': '{short_code}PETBILP', 'career_technical_education_count': '{short_code}PETVOCC', 'career_technical_education_percent': '{short_code}PETVOCP', 'gifted_and_talented_count': '{short_code}PETGIFC', 'gifted_and_talented_percent': '{short_code}PETGIFP', 'special_education_count': '{short_code}PETSPEC', 'special_education_percent': '{short_code}PETSPEP', 'class_size_avg_kindergarten': '{short_code}PCTGKGA', 'class_size_avg_first': '{short_code}PCTG01A', 'class_size_avg_second': '{short_code}PCTG02A', 'class_size_avg_third': '{short_code}PCTG03A', 'class_size_avg_fourth': '{short_code}PCTG04A', 'class_size_avg_fifth': '{short_code}PCTG05A', 'class_size_avg_sixth': '{short_code}PCTG06A', 'class_size_avg_mixed_elementary': '{short_code}PCTGMEA', 'class_size_avg_secondary_english': '{short_code}PCTENGA', 'class_size_avg_secondary_foreign_language': '{short_code}PCTFLAA', 'class_size_avg_secondary_math': '{short_code}PCTMATA', 'class_size_avg_secondary_science': '{short_code}PCTSCIA', 'class_size_avg_secondary_social_studies': '{short_code}PCTSOCA', 'students_per_teacher': '{short_code}PSTKIDR', 'teacher_avg_tenure': '{short_code}PSTTENA', 'teacher_avg_experience': '{short_code}PSTEXPA', 'teacher_avg_base_salary': '{short_code}PSTTOSA', 'teacher_avg_beginning_salary': '{short_code}PST00SA', 'teacher_avg_1_to_5_year_salary': '{short_code}PST01SA', 'teacher_avg_6_to_10_year_salary': '{short_code}PST06SA', 'teacher_avg_11_to_20_year_salary': '{short_code}PST11SA', 'teacher_avg_20_plus_year_salary': '{short_code}PST20SA', 'teacher_total_fte_count': '{short_code}PSTTOFC', 'teacher_african_american_fte_count': '{short_code}PSTBLFC', 'teacher_american_indian_fte_count': '{short_code}PSTINFC', 'teacher_asian_fte_count': '{short_code}PSTASFC', 'teacher_hispanic_fte_count': '{short_code}PSTHIFC', 'teacher_pacific_islander_fte_count': '{short_code}PSTPIFC', 'teacher_two_or_more_races_fte_count': '{short_code}PSTTWFC', 'teacher_white_fte_count': '{short_code}PSTWHFC', 'teacher_total_fte_percent': '{short_code}PSTTOFC', 'teacher_african_american_fte_percent': '{short_code}PSTBLFP', 'teacher_american_indian_fte_percent': '{short_code}PSTINFP', 'teacher_asian_fte_percent': '{short_code}PSTASFP', 'teacher_hispanic_fte_percent': '{short_code}PSTHIFP', 'teacher_pacific_islander_fte_percent': '{short_code}PSTPIFP', 'teacher_two_or_more_races_fte_percent': '{short_code}PSTTWFP', 'teacher_white_fte_percent': '{short_code}PSTWHFP', 'teacher_no_degree_count': '{short_code}PSTNOFC', 'teacher_bachelors_count': '{short_code}PSTBAFC', 'teacher_masters_count': '{short_code}PSTMSFC', 'teacher_doctorate_count': '{short_code}PSTPHFC', 'teacher_no_degree_percent': '{short_code}PSTNOFP', 'teacher_bachelors_percent': '{short_code}PSTBAFP', 'teacher_masters_percent': '{short_code}PSTMSFP', 'teacher_doctorate_percent': '{short_code}PSTPHFP', 'college_ready_graduates_english_all_students_percent': '{short_code}ACRR{year}R', 'college_ready_graduates_english_african_american_percent': '{short_code}BCRR{year}R', 'college_ready_graduates_english_american_indian_percent': '{short_code}ICRR{year}R', 'college_ready_graduates_english_asian_percent': '{short_code}3CRR{year}R', 'college_ready_graduates_english_hispanic_percent': '{short_code}HCRR{year}R', 'college_ready_graduates_english_pacific_islander_percent': '{short_code}4CRR{year}R', 'college_ready_graduates_english_two_or_more_races_percent': '{short_code}2CRR{year}R', 'college_ready_graduates_english_white_percent': '{short_code}WCRR{year}R', 'college_ready_graduates_english_economically_disadvantaged_percent': '{short_code}ECRR{year}R', 'college_ready_graduates_english_limited_english_proficient_percent': '{short_code}LCRR{year}R', 'college_ready_graduates_english_at_risk_percent': '{short_code}RCRR{year}R', 'college_ready_graduates_math_all_students_percent': '{short_code}ACRM{year}R', 'college_ready_graduates_math_african_american_percent': '{short_code}BCRM{year}R', 'college_ready_graduates_math_american_indian_percent': '{short_code}ICRM{year}R', 'college_ready_graduates_math_asian_percent': '{short_code}3CRM{year}R', 'college_ready_graduates_math_hispanic_percent': '{short_code}HCRM{year}R', 'college_ready_graduates_math_pacific_islander_percent': '{short_code}4CRM{year}R', 'college_ready_graduates_math_two_or_more_races_percent': '{short_code}2CRM{year}R', 'college_ready_graduates_math_white_percent': '{short_code}WCRM{year}R', 'college_ready_graduates_math_economically_disadvantaged_percent': '{short_code}ECRM{year}R', 'college_ready_graduates_math_limited_english_proficient_percent': '{short_code}LCRM{year}R', 'college_ready_graduates_math_at_risk_percent': '{short_code}RCRM{year}R', 'college_ready_graduates_both_all_students_percent': '{short_code}ACRB{year}R', 'college_ready_graduates_both_african_american_percent': '{short_code}BCRB{year}R', 'college_ready_graduates_both_asian_percent': '{short_code}3CRB{year}R', 'college_ready_graduates_both_hispanic_percent': '{short_code}HCRB{year}R', 'college_ready_graduates_both_american_indian_percent': '{short_code}ICRB{year}R', 'college_ready_graduates_both_pacific_islander_percent': '{short_code}4CRB{year}R', 'college_ready_graduates_both_two_or_more_races_percent': '{short_code}2CRB{year}R', 'college_ready_graduates_both_white_percent': '{short_code}WCRB{year}R', 'college_ready_graduates_both_economically_disadvantaged_percent': '{short_code}ECRB{year}R', 'college_ready_graduates_both_limited_english_proficient_percent': '{short_code}LCRB{year}R', 'college_ready_graduates_both_at_risk_percent': '{short_code}RCRB{year}R', 'avg_sat_score_all_students': '{short_code}A0CSA{year}R', 'avg_sat_score_african_american': '{short_code}B0CSA{year}R', 'avg_sat_score_american_indian': '{short_code}I0CSA{year}R', 'avg_sat_score_asian': '{short_code}30CSA{year}R', 'avg_sat_score_hispanic': '{short_code}H0CSA{year}R', 'avg_sat_score_pacific_islander': '{short_code}40CSA{year}R', 'avg_sat_score_two_or_more_races': '{short_code}20CSA{year}R', 'avg_sat_score_white': '{short_code}W0CSA{year}R', 'avg_sat_score_economically_disadvantaged': '{short_code}E0CSA{year}R', 'avg_act_score_all_students': '{short_code}A0CAA{year}R', 'avg_act_score_african_american': '{short_code}B0CAA{year}R', 'avg_act_score_american_indian': '{short_code}I0CAA{year}R', 'avg_act_score_asian': '{short_code}30CAA{year}R', 'avg_act_score_hispanic': '{short_code}H0CAA{year}R', 'avg_act_score_pacific_islander': '{short_code}40CAA{year}R', 'avg_act_score_two_or_more_races': '{short_code}20CAA{year}R', 'avg_act_score_white': '{short_code}W0CAA{year}R', 'avg_act_score_economically_disadvantaged': '{short_code}E0CAA{year}R', 'ap_ib_all_students_percent_above_criterion': '{short_code}A0BKA{year}R', 'ap_ib_african_american_percent_above_criterion': '{short_code}B0BKA{year}R', 'ap_ib_asian_percent_above_criterion': '{short_code}30BKA{year}R', 'ap_ib_hispanic_percent_above_criterion': '{short_code}H0BKA{year}R', 'ap_ib_american_indian_percent_above_criterion': '{short_code}I0BKA{year}R', 'ap_ib_pacific_islander_percent_above_criterion': '{short_code}40BKA{year}R', 'ap_ib_two_or_more_races_percent_above_criterion': '{short_code}20BKA{year}R', 'ap_ib_white_percent_above_criterion': '{short_code}W0BKA{year}R', 'ap_ib_economically_disadvantaged_percent_above_criterion': '{short_code}E0BKA{year}R', 'ap_ib_all_students_percent_taking': '{short_code}A0BTA{year}R', 'ap_ib_african_american_percent_taking': '{short_code}B0BTA{year}R', 'ap_ib_asian_percent_taking': '{short_code}30BTA{year}R', 'ap_ib_hispanic_percent_taking': '{short_code}H0BTA{year}R', 'ap_ib_american_indian_percent_taking': '{short_code}I0BTA{year}R', 'ap_ib_pacific_islander_percent_taking': '{short_code}40BTA{year}R', 'ap_ib_two_or_more_races_percent_taking': '{short_code}20BTA{year}R', 'ap_ib_white_percent_taking': '{short_code}W0BTA{year}R', 'ap_ib_economically_disadvantaged_percent_taking': '{short_code}E0BTA{year}R', 'attendance_rate': '{short_code}A0AT{year}R', 'dropout_all_students_percent': '{short_code}A0912DR{year}R', 'dropout_african_american_percent': '{short_code}B0912DR{year}R', 'dropout_asian_percent': '{short_code}30912DR{year}R', 'dropout_hispanic_percent': '{short_code}H0912DR{year}R', 'dropout_american_indian_percent': '{short_code}I0912DR{year}R', 'dropout_pacific_islander_percent': '{short_code}40912DR{year}R', 'dropout_two_or_more_races_percent': '{short_code}20912DR{year}R', 'dropout_white_percent': '{short_code}W0912DR{year}R', 'dropout_at_risk_percent': '{short_code}R0912DR{year}R', 'dropout_economically_disadvantaged_percent': '{short_code}E0912DR{year}R', 'dropout_limited_english_proficient_percent': '{short_code}E0912DR{year}R', 'four_year_graduate_all_students_percent': '{short_code}AGC4{suffix}{year}R', 'four_year_graduate_african_american_percent': '{short_code}BGC4{suffix}{year}R', 'four_year_graduate_american_indian_percent': '{short_code}IGC4{suffix}{year}R', 'four_year_graduate_asian_percent': '{short_code}3GC4{suffix}{year}R', 'four_year_graduate_hispanic_percent': '{short_code}HGC4{suffix}{year}R', 'four_year_graduate_pacific_islander_percent': '{short_code}4GC4{suffix}{year}R', 'four_year_graduate_two_or_more_races_percent': '{short_code}2GC4{suffix}{year}R', 'four_year_graduate_white_percent': '{short_code}WGC4{suffix}{year}R', 'four_year_graduate_at_risk_percent': '{short_code}RGC4{suffix}{year}R', 'four_year_graduate_economically_disadvantaged_percent': '{short_code}EGC4{suffix}{year}R', 'four_year_graduate_limited_english_proficient_percent': '{short_code}L3C4{suffix}{year}R', 'accountability_rating': '{short_code}_RATING', 'student_achievement_rating': '{short_code}D1G', 'school_progress_rating': '{short_code}D2G', 'closing_the_gaps_rating': '{short_code}D3G'}
# This problem was asked by Facebook. # Given an array of numbers representing the stock prices of a company in chronological # order and an integer k, return the maximum profit you can make from k buys and sells. # You must buy the stock before you can sell it, and you must sell the stock before you can buy it again. # For example, given k = 2 and the array [5, 2, 4, 0, 1], you should return 3. #### def get_max_profit(arr, k): a = arr + [-1] current_min = a[0] current_max = a[0] ends = [] # generate profit intervals # current_max == current_min denotes that the buying price was set during # the immediately previous loop (selling price not discovered yet) for i in range(1, len(a)): # more profit possible if a[i] > current_max: current_max = a[i] # the beginning of the next interval is found if a[i] < current_max and current_max != current_min: ends.append((current_min, current_max)) current_max = a[i] current_min = a[i] # buying cost is strictly decreasing (to calculate cheapest buying price) if a[i] < current_min and current_max == current_min: current_min = a[i] current_max = a[i] # merge smallest intervals to make number of intervals = k while k < len(ends): # get smallest interval pos, cur = min(list(enumerate(ends)), key = lambda x: x[1][1] - x[1][0]) # try merging with lower interval if pos != 0: lower = ends[pos-1] if cur[1] > lower[1]: ends[pos-1] = (lower[0], cur[1]) # try merging with upper interval if pos != len(ends)-1: upper = ends[pos+1] if cur[0] < upper[0]: ends[pos+1] = (cur[0], upper[1]) ends.remove(cur) return sum([y-x for x,y in ends]) #### print(get_max_profit([7, 9, 8, 11, 11, 10, 12, 15, 13, 10], 2))
def get_max_profit(arr, k): a = arr + [-1] current_min = a[0] current_max = a[0] ends = [] for i in range(1, len(a)): if a[i] > current_max: current_max = a[i] if a[i] < current_max and current_max != current_min: ends.append((current_min, current_max)) current_max = a[i] current_min = a[i] if a[i] < current_min and current_max == current_min: current_min = a[i] current_max = a[i] while k < len(ends): (pos, cur) = min(list(enumerate(ends)), key=lambda x: x[1][1] - x[1][0]) if pos != 0: lower = ends[pos - 1] if cur[1] > lower[1]: ends[pos - 1] = (lower[0], cur[1]) if pos != len(ends) - 1: upper = ends[pos + 1] if cur[0] < upper[0]: ends[pos + 1] = (cur[0], upper[1]) ends.remove(cur) return sum([y - x for (x, y) in ends]) print(get_max_profit([7, 9, 8, 11, 11, 10, 12, 15, 13, 10], 2))
def file_html(fname): fptr=open(fname,"r") to_send = "" for lines in fptr: to_send += lines; return to_send #file_html("myfile.html");
def file_html(fname): fptr = open(fname, 'r') to_send = '' for lines in fptr: to_send += lines return to_send
md = [0,0] facing = "E" def rotate(cw, val): idx = 4 + cw * int((val/90) % 4) mv = ['E','S','W','N'] c = mv.index(facing) return mv[(idx + c) % 4] def move(dr, val): global ew global ns global facing if dr == 'N': md[1] += val elif dr == 'S': md[1] -= val elif dr == 'E': md[0] += val elif dr == 'W': md[0] -= val elif dr == 'L': facing = rotate(-1,val) elif dr == 'R': facing = rotate(+1,val) elif dr == 'F': move(facing,val) ############################## for l in open("input.txt"): move(list(l)[0], int(''.join(list(l.strip())[1:]))) print("Manhattan distance =", abs(md[0]) + abs(md[1]))
md = [0, 0] facing = 'E' def rotate(cw, val): idx = 4 + cw * int(val / 90 % 4) mv = ['E', 'S', 'W', 'N'] c = mv.index(facing) return mv[(idx + c) % 4] def move(dr, val): global ew global ns global facing if dr == 'N': md[1] += val elif dr == 'S': md[1] -= val elif dr == 'E': md[0] += val elif dr == 'W': md[0] -= val elif dr == 'L': facing = rotate(-1, val) elif dr == 'R': facing = rotate(+1, val) elif dr == 'F': move(facing, val) for l in open('input.txt'): move(list(l)[0], int(''.join(list(l.strip())[1:]))) print('Manhattan distance =', abs(md[0]) + abs(md[1]))
for _ in range(int(input())): n,x = map(int,input().split()) l = list(map(int,input().split())) flag=2 if len(set(l)) == 1 and l[0] == x: flag=0 elif x in l or sum([i-x for i in l])==0: flag=1 if flag==0: print(0) elif flag==1: print(1) else: print(2)
for _ in range(int(input())): (n, x) = map(int, input().split()) l = list(map(int, input().split())) flag = 2 if len(set(l)) == 1 and l[0] == x: flag = 0 elif x in l or sum([i - x for i in l]) == 0: flag = 1 if flag == 0: print(0) elif flag == 1: print(1) else: print(2)
""" Take the block of text provided and strip off the whitespace at both ends. Split the text by newline (\n) using split. Loop through the lines and if the first character of each (stripped) line is lowercase, split the line into words and add the last word to the (given) results list, stripping the trailing dot (.) and exclamation mark (!) from the end of the word. At the end of the function return the results list. """ text = """ One really nice feature of Python is polymorphism: using the same operation on different types of objects. Let's talk about an elegant feature: slicing. You can use this on a string as well as a list for example 'pybites'[0:2] gives 'py'. The first value is inclusive and the last one is exclusive so here we grab indexes 0 and 1, the letter p and y. When you have a 0 index you can leave it out so can write this as 'pybites'[:2] but here is the kicker: you can use this on a list too! ['pybites', 'teaches', 'you', 'Python'][-2:] would gives ['you', 'Python'] and now you know about slicing from the end as well :) keep enjoying our bites! """ def slice_and_dice(text=text): results = [] strip_text = text.strip("\n") split_strip = strip_text.split("\n") for i in split_strip: i = i.strip(" ") if i[0].islower(): strip_i = i.strip('!.') split_i = strip_i.split(" ") results.append(split_i[-1]) return results
""" Take the block of text provided and strip off the whitespace at both ends. Split the text by newline ( ) using split. Loop through the lines and if the first character of each (stripped) line is lowercase, split the line into words and add the last word to the (given) results list, stripping the trailing dot (.) and exclamation mark (!) from the end of the word. At the end of the function return the results list. """ text = "\nOne really nice feature of Python is polymorphism: using the same operation\non different types of objects.\nLet's talk about an elegant feature: slicing.\nYou can use this on a string as well as a list for example\n'pybites'[0:2] gives 'py'.\nThe first value is inclusive and the last one is exclusive so\nhere we grab indexes 0 and 1, the letter p and y.\nWhen you have a 0 index you can leave it out so can write this as 'pybites'[:2]\nbut here is the kicker: you can use this on a list too!\n['pybites', 'teaches', 'you', 'Python'][-2:] would gives ['you', 'Python']\nand now you know about slicing from the end as well :)\nkeep enjoying our bites!\n" def slice_and_dice(text=text): results = [] strip_text = text.strip('\n') split_strip = strip_text.split('\n') for i in split_strip: i = i.strip(' ') if i[0].islower(): strip_i = i.strip('!.') split_i = strip_i.split(' ') results.append(split_i[-1]) return results
""" domonic.constants.keyboard ==================================== """ class KeyCode(): A = '65' #: ALTERNATE = '18' #: B = '66' #: BACKQUOTE = '192' #: BACKSLASH = '220' #: BACKSPACE = '8' #: C = '67' #: CAPS_LOCK = '20' #: COMMA = '188' #: COMMAND = '15' #: CONTROL = '17' #: D = '68' #: DELETE = '46' #: DOWN = '40' #: E = '69' #: END = '35' #: ENTER = '13' #: RETURN = '13' #: EQUAL = '187' #: ESCAPE = '27' #: F = '70' #: F1 = '112' #: F10 = '121' #: F11 = '122' #: F12 = '123' #: F13 = '124' #: F14 = '125' #: F15 = '126' #: F2 = '113' #: F3 = '114' #: F4 = '115' #: F5 = '116' #: F6 = '117' #: F7 = '118' #: F8 = '119' #: F9 = '120' #: G = '71' #: H = '72' #: HOME = '36' #: I = '73' #: INSERT = '45' #: J = '74' #: K = '75' #: L = '76' #: LEFT = '37' #: LEFTBRACKET = '219' #: M = '77' #: MINUS = '189' #: N = '78' #: NUMBER_0 = '48' #: NUMBER_1 = '49' #: NUMBER_2 = '50' #: NUMBER_3 = '51' #: NUMBER_4 = '52' #: NUMBER_5 = '53' #: NUMBER_6 = '54' #: NUMBER_7 = '55' #: NUMBER_8 = '56' #: NUMBER_9 = '57' #: NUMPAD = '21' #: NUMPAD_0 = '96' #: NUMPAD_1 = '97' #: NUMPAD_2 = '98' #: NUMPAD_3 = '99' #: NUMPAD_4 = '100' #: NUMPAD_5 = '101' #: NUMPAD_6 = '102' #: NUMPAD_7 = '103' #: NUMPAD_8 = '104' #: NUMPAD_9 = '105' #: NUMPAD_ADD = '107' #: NUMPAD_DECIMAL = '110' #: NUMPAD_DIVIDE = '111' #: NUMPAD_ENTER = '108' #: NUMPAD_MULTIPLY = '106' #: NUMPAD_SUBTRACT = '109' #: O = '79' #: P = '80' #: PAGE_DOWN = '34' #: PAGE_UP = '33' #: PERIOD = '190' #: Q = '81' #: QUOTE = '222' #: R = '82' #: RIGHT = '39' #: RIGHTBRACKET = '221' #: S = '83' #: SEMICOLON = '186' #: SHIFT = '16' #: ?? left or right or both? SLASH = '191' #: SPACE = '32' #: T = '84' #: TAB = '9' #: U = '85' #: UP = '38' #: V = '86' #: W = '87' #: X = '88' #: Y = '89' #: Z = '9' #: # TODO - do the modifiers # find attribute by value # def get_letter(self, attr): # for key, value in self.__dict__.iteritems(): # if value == attr: # return key # return None def __init__(self): """ constructor for the keyboard class """ pass
""" domonic.constants.keyboard ==================================== """ class Keycode: a = '65' alternate = '18' b = '66' backquote = '192' backslash = '220' backspace = '8' c = '67' caps_lock = '20' comma = '188' command = '15' control = '17' d = '68' delete = '46' down = '40' e = '69' end = '35' enter = '13' return = '13' equal = '187' escape = '27' f = '70' f1 = '112' f10 = '121' f11 = '122' f12 = '123' f13 = '124' f14 = '125' f15 = '126' f2 = '113' f3 = '114' f4 = '115' f5 = '116' f6 = '117' f7 = '118' f8 = '119' f9 = '120' g = '71' h = '72' home = '36' i = '73' insert = '45' j = '74' k = '75' l = '76' left = '37' leftbracket = '219' m = '77' minus = '189' n = '78' number_0 = '48' number_1 = '49' number_2 = '50' number_3 = '51' number_4 = '52' number_5 = '53' number_6 = '54' number_7 = '55' number_8 = '56' number_9 = '57' numpad = '21' numpad_0 = '96' numpad_1 = '97' numpad_2 = '98' numpad_3 = '99' numpad_4 = '100' numpad_5 = '101' numpad_6 = '102' numpad_7 = '103' numpad_8 = '104' numpad_9 = '105' numpad_add = '107' numpad_decimal = '110' numpad_divide = '111' numpad_enter = '108' numpad_multiply = '106' numpad_subtract = '109' o = '79' p = '80' page_down = '34' page_up = '33' period = '190' q = '81' quote = '222' r = '82' right = '39' rightbracket = '221' s = '83' semicolon = '186' shift = '16' slash = '191' space = '32' t = '84' tab = '9' u = '85' up = '38' v = '86' w = '87' x = '88' y = '89' z = '9' def __init__(self): """ constructor for the keyboard class """ pass
#!/usr/bin/env python # configure these settings to change projector behavior server_mount_path = '//192.168.42.11/PiShare' # shared folder on other pi user_name = 'pi' # shared drive login user name user_password = 'raspberry' # shared drive login password client_mount_path = '/mnt/pishare' # where to find the shared folder on this pi pics_folder = '/mnt/pishare/pics' # where to find the pics to display waittime = 2 # default time to wait between images (in seconds) use_prime = True # Set to true to show the prime slide, false if otherwise prime_slide = '/home/pi/photobooth/projector.png' # image to show regularly in slideshow prime_freq = 16 # how many pics to show before showing the prime slide again monitor_w = 800 # width in pixels of display (monitor or projector) monitor_h = 600 # height in pixels of display (monitor or projector) title = "SlideShow" # caption of the window...
server_mount_path = '//192.168.42.11/PiShare' user_name = 'pi' user_password = 'raspberry' client_mount_path = '/mnt/pishare' pics_folder = '/mnt/pishare/pics' waittime = 2 use_prime = True prime_slide = '/home/pi/photobooth/projector.png' prime_freq = 16 monitor_w = 800 monitor_h = 600 title = 'SlideShow'
class Solution: def boldWords(self, words, S): """ :type words: List[str] :type S: str :rtype: str """ m = len(S) flags = [False] * m for word in words: n = len(word) for i in range(m - n + 1): if S[i:i + n] == word: flags[i:i + n] = [True] * n ans = [] for i, (flag, ch) in enumerate(zip(flags, S)): if flag: if i == 0 or not flags[i - 1]: ans.append('<b>') ans.append(ch) if i == m - 1 or not flags[i + 1]: ans.append('</b>') else: ans.append(ch) return ''.join(ans)
class Solution: def bold_words(self, words, S): """ :type words: List[str] :type S: str :rtype: str """ m = len(S) flags = [False] * m for word in words: n = len(word) for i in range(m - n + 1): if S[i:i + n] == word: flags[i:i + n] = [True] * n ans = [] for (i, (flag, ch)) in enumerate(zip(flags, S)): if flag: if i == 0 or not flags[i - 1]: ans.append('<b>') ans.append(ch) if i == m - 1 or not flags[i + 1]: ans.append('</b>') else: ans.append(ch) return ''.join(ans)
data = ( 'E ', # 0x00 'Cheng ', # 0x01 'Xin ', # 0x02 'Ai ', # 0x03 'Lu ', # 0x04 'Zhui ', # 0x05 'Zhou ', # 0x06 'She ', # 0x07 'Pian ', # 0x08 'Kun ', # 0x09 'Tao ', # 0x0a 'Lai ', # 0x0b 'Zong ', # 0x0c 'Ke ', # 0x0d 'Qi ', # 0x0e 'Qi ', # 0x0f 'Yan ', # 0x10 'Fei ', # 0x11 'Sao ', # 0x12 'Yan ', # 0x13 'Jie ', # 0x14 'Yao ', # 0x15 'Wu ', # 0x16 'Pian ', # 0x17 'Cong ', # 0x18 'Pian ', # 0x19 'Qian ', # 0x1a 'Fei ', # 0x1b 'Huang ', # 0x1c 'Jian ', # 0x1d 'Huo ', # 0x1e 'Yu ', # 0x1f 'Ti ', # 0x20 'Quan ', # 0x21 'Xia ', # 0x22 'Zong ', # 0x23 'Kui ', # 0x24 'Rou ', # 0x25 'Si ', # 0x26 'Gua ', # 0x27 'Tuo ', # 0x28 'Kui ', # 0x29 'Sou ', # 0x2a 'Qian ', # 0x2b 'Cheng ', # 0x2c 'Zhi ', # 0x2d 'Liu ', # 0x2e 'Pang ', # 0x2f 'Teng ', # 0x30 'Xi ', # 0x31 'Cao ', # 0x32 'Du ', # 0x33 'Yan ', # 0x34 'Yuan ', # 0x35 'Zou ', # 0x36 'Sao ', # 0x37 'Shan ', # 0x38 'Li ', # 0x39 'Zhi ', # 0x3a 'Shuang ', # 0x3b 'Lu ', # 0x3c 'Xi ', # 0x3d 'Luo ', # 0x3e 'Zhang ', # 0x3f 'Mo ', # 0x40 'Ao ', # 0x41 'Can ', # 0x42 'Piao ', # 0x43 'Cong ', # 0x44 'Qu ', # 0x45 'Bi ', # 0x46 'Zhi ', # 0x47 'Yu ', # 0x48 'Xu ', # 0x49 'Hua ', # 0x4a 'Bo ', # 0x4b 'Su ', # 0x4c 'Xiao ', # 0x4d 'Lin ', # 0x4e 'Chan ', # 0x4f 'Dun ', # 0x50 'Liu ', # 0x51 'Tuo ', # 0x52 'Zeng ', # 0x53 'Tan ', # 0x54 'Jiao ', # 0x55 'Tie ', # 0x56 'Yan ', # 0x57 'Luo ', # 0x58 'Zhan ', # 0x59 'Jing ', # 0x5a 'Yi ', # 0x5b 'Ye ', # 0x5c 'Tuo ', # 0x5d 'Bin ', # 0x5e 'Zou ', # 0x5f 'Yan ', # 0x60 'Peng ', # 0x61 'Lu ', # 0x62 'Teng ', # 0x63 'Xiang ', # 0x64 'Ji ', # 0x65 'Shuang ', # 0x66 'Ju ', # 0x67 'Xi ', # 0x68 'Huan ', # 0x69 'Li ', # 0x6a 'Biao ', # 0x6b 'Ma ', # 0x6c 'Yu ', # 0x6d 'Tuo ', # 0x6e 'Xun ', # 0x6f 'Chi ', # 0x70 'Qu ', # 0x71 'Ri ', # 0x72 'Bo ', # 0x73 'Lu ', # 0x74 'Zang ', # 0x75 'Shi ', # 0x76 'Si ', # 0x77 'Fu ', # 0x78 'Ju ', # 0x79 'Zou ', # 0x7a 'Zhu ', # 0x7b 'Tuo ', # 0x7c 'Nu ', # 0x7d 'Jia ', # 0x7e 'Yi ', # 0x7f 'Tai ', # 0x80 'Xiao ', # 0x81 'Ma ', # 0x82 'Yin ', # 0x83 'Jiao ', # 0x84 'Hua ', # 0x85 'Luo ', # 0x86 'Hai ', # 0x87 'Pian ', # 0x88 'Biao ', # 0x89 'Li ', # 0x8a 'Cheng ', # 0x8b 'Yan ', # 0x8c 'Xin ', # 0x8d 'Qin ', # 0x8e 'Jun ', # 0x8f 'Qi ', # 0x90 'Qi ', # 0x91 'Ke ', # 0x92 'Zhui ', # 0x93 'Zong ', # 0x94 'Su ', # 0x95 'Can ', # 0x96 'Pian ', # 0x97 'Zhi ', # 0x98 'Kui ', # 0x99 'Sao ', # 0x9a 'Wu ', # 0x9b 'Ao ', # 0x9c 'Liu ', # 0x9d 'Qian ', # 0x9e 'Shan ', # 0x9f 'Piao ', # 0xa0 'Luo ', # 0xa1 'Cong ', # 0xa2 'Chan ', # 0xa3 'Zou ', # 0xa4 'Ji ', # 0xa5 'Shuang ', # 0xa6 'Xiang ', # 0xa7 'Gu ', # 0xa8 'Wei ', # 0xa9 'Wei ', # 0xaa 'Wei ', # 0xab 'Yu ', # 0xac 'Gan ', # 0xad 'Yi ', # 0xae 'Ang ', # 0xaf 'Tou ', # 0xb0 'Xie ', # 0xb1 'Bao ', # 0xb2 'Bi ', # 0xb3 'Chi ', # 0xb4 'Ti ', # 0xb5 'Di ', # 0xb6 'Ku ', # 0xb7 'Hai ', # 0xb8 'Qiao ', # 0xb9 'Gou ', # 0xba 'Kua ', # 0xbb 'Ge ', # 0xbc 'Tui ', # 0xbd 'Geng ', # 0xbe 'Pian ', # 0xbf 'Bi ', # 0xc0 'Ke ', # 0xc1 'Ka ', # 0xc2 'Yu ', # 0xc3 'Sui ', # 0xc4 'Lou ', # 0xc5 'Bo ', # 0xc6 'Xiao ', # 0xc7 'Pang ', # 0xc8 'Bo ', # 0xc9 'Ci ', # 0xca 'Kuan ', # 0xcb 'Bin ', # 0xcc 'Mo ', # 0xcd 'Liao ', # 0xce 'Lou ', # 0xcf 'Nao ', # 0xd0 'Du ', # 0xd1 'Zang ', # 0xd2 'Sui ', # 0xd3 'Ti ', # 0xd4 'Bin ', # 0xd5 'Kuan ', # 0xd6 'Lu ', # 0xd7 'Gao ', # 0xd8 'Gao ', # 0xd9 'Qiao ', # 0xda 'Kao ', # 0xdb 'Qiao ', # 0xdc 'Lao ', # 0xdd 'Zao ', # 0xde 'Biao ', # 0xdf 'Kun ', # 0xe0 'Kun ', # 0xe1 'Ti ', # 0xe2 'Fang ', # 0xe3 'Xiu ', # 0xe4 'Ran ', # 0xe5 'Mao ', # 0xe6 'Dan ', # 0xe7 'Kun ', # 0xe8 'Bin ', # 0xe9 'Fa ', # 0xea 'Tiao ', # 0xeb 'Peng ', # 0xec 'Zi ', # 0xed 'Fa ', # 0xee 'Ran ', # 0xef 'Ti ', # 0xf0 'Pao ', # 0xf1 'Pi ', # 0xf2 'Mao ', # 0xf3 'Fu ', # 0xf4 'Er ', # 0xf5 'Rong ', # 0xf6 'Qu ', # 0xf7 'Gong ', # 0xf8 'Xiu ', # 0xf9 'Gua ', # 0xfa 'Ji ', # 0xfb 'Peng ', # 0xfc 'Zhua ', # 0xfd 'Shao ', # 0xfe 'Sha ', # 0xff )
data = ('E ', 'Cheng ', 'Xin ', 'Ai ', 'Lu ', 'Zhui ', 'Zhou ', 'She ', 'Pian ', 'Kun ', 'Tao ', 'Lai ', 'Zong ', 'Ke ', 'Qi ', 'Qi ', 'Yan ', 'Fei ', 'Sao ', 'Yan ', 'Jie ', 'Yao ', 'Wu ', 'Pian ', 'Cong ', 'Pian ', 'Qian ', 'Fei ', 'Huang ', 'Jian ', 'Huo ', 'Yu ', 'Ti ', 'Quan ', 'Xia ', 'Zong ', 'Kui ', 'Rou ', 'Si ', 'Gua ', 'Tuo ', 'Kui ', 'Sou ', 'Qian ', 'Cheng ', 'Zhi ', 'Liu ', 'Pang ', 'Teng ', 'Xi ', 'Cao ', 'Du ', 'Yan ', 'Yuan ', 'Zou ', 'Sao ', 'Shan ', 'Li ', 'Zhi ', 'Shuang ', 'Lu ', 'Xi ', 'Luo ', 'Zhang ', 'Mo ', 'Ao ', 'Can ', 'Piao ', 'Cong ', 'Qu ', 'Bi ', 'Zhi ', 'Yu ', 'Xu ', 'Hua ', 'Bo ', 'Su ', 'Xiao ', 'Lin ', 'Chan ', 'Dun ', 'Liu ', 'Tuo ', 'Zeng ', 'Tan ', 'Jiao ', 'Tie ', 'Yan ', 'Luo ', 'Zhan ', 'Jing ', 'Yi ', 'Ye ', 'Tuo ', 'Bin ', 'Zou ', 'Yan ', 'Peng ', 'Lu ', 'Teng ', 'Xiang ', 'Ji ', 'Shuang ', 'Ju ', 'Xi ', 'Huan ', 'Li ', 'Biao ', 'Ma ', 'Yu ', 'Tuo ', 'Xun ', 'Chi ', 'Qu ', 'Ri ', 'Bo ', 'Lu ', 'Zang ', 'Shi ', 'Si ', 'Fu ', 'Ju ', 'Zou ', 'Zhu ', 'Tuo ', 'Nu ', 'Jia ', 'Yi ', 'Tai ', 'Xiao ', 'Ma ', 'Yin ', 'Jiao ', 'Hua ', 'Luo ', 'Hai ', 'Pian ', 'Biao ', 'Li ', 'Cheng ', 'Yan ', 'Xin ', 'Qin ', 'Jun ', 'Qi ', 'Qi ', 'Ke ', 'Zhui ', 'Zong ', 'Su ', 'Can ', 'Pian ', 'Zhi ', 'Kui ', 'Sao ', 'Wu ', 'Ao ', 'Liu ', 'Qian ', 'Shan ', 'Piao ', 'Luo ', 'Cong ', 'Chan ', 'Zou ', 'Ji ', 'Shuang ', 'Xiang ', 'Gu ', 'Wei ', 'Wei ', 'Wei ', 'Yu ', 'Gan ', 'Yi ', 'Ang ', 'Tou ', 'Xie ', 'Bao ', 'Bi ', 'Chi ', 'Ti ', 'Di ', 'Ku ', 'Hai ', 'Qiao ', 'Gou ', 'Kua ', 'Ge ', 'Tui ', 'Geng ', 'Pian ', 'Bi ', 'Ke ', 'Ka ', 'Yu ', 'Sui ', 'Lou ', 'Bo ', 'Xiao ', 'Pang ', 'Bo ', 'Ci ', 'Kuan ', 'Bin ', 'Mo ', 'Liao ', 'Lou ', 'Nao ', 'Du ', 'Zang ', 'Sui ', 'Ti ', 'Bin ', 'Kuan ', 'Lu ', 'Gao ', 'Gao ', 'Qiao ', 'Kao ', 'Qiao ', 'Lao ', 'Zao ', 'Biao ', 'Kun ', 'Kun ', 'Ti ', 'Fang ', 'Xiu ', 'Ran ', 'Mao ', 'Dan ', 'Kun ', 'Bin ', 'Fa ', 'Tiao ', 'Peng ', 'Zi ', 'Fa ', 'Ran ', 'Ti ', 'Pao ', 'Pi ', 'Mao ', 'Fu ', 'Er ', 'Rong ', 'Qu ', 'Gong ', 'Xiu ', 'Gua ', 'Ji ', 'Peng ', 'Zhua ', 'Shao ', 'Sha ')
"""Top-level package for ML Model Evaluation Toolkit.""" __author__ = """Nicolas Kaenzig""" __email__ = "nkaenzig@gmail.com" __version__ = "0.1.0"
"""Top-level package for ML Model Evaluation Toolkit.""" __author__ = 'Nicolas Kaenzig' __email__ = 'nkaenzig@gmail.com' __version__ = '0.1.0'
def remove_duplicated_keep_order(value_in_tuple): new_tuple = [] for i in value_in_tuple: if not (i in new_tuple): new_tuple.append(i) return new_tuple # return tuple(set(value_in_tuple))
def remove_duplicated_keep_order(value_in_tuple): new_tuple = [] for i in value_in_tuple: if not i in new_tuple: new_tuple.append(i) return new_tuple
# Licensed under a 3-clause BSD style license - see LICENSE.rst def get_package_data(): return { _ASTROPY_PACKAGE_NAME_ + '.tests': ['coveragerc', 'data/*.hdr'] # noqa }
def get_package_data(): return {_ASTROPY_PACKAGE_NAME_ + '.tests': ['coveragerc', 'data/*.hdr']}
exp.set('total_responses', 0) exp.set('total_correct', 0) exp.set('total_response_time', 0) exp.set('average_response_time', 'NA') exp.set('avg_rt', 'NA') exp.set('accuracy', 'NA') exp.set('acc', 'NA')
exp.set('total_responses', 0) exp.set('total_correct', 0) exp.set('total_response_time', 0) exp.set('average_response_time', 'NA') exp.set('avg_rt', 'NA') exp.set('accuracy', 'NA') exp.set('acc', 'NA')
def exception_test(assert_check_fn): try: def exception_wrapper(*arg, **kwarg): assert_check_fn(*arg, **kwarg) except Exception as e: pytest.failed(e)
def exception_test(assert_check_fn): try: def exception_wrapper(*arg, **kwarg): assert_check_fn(*arg, **kwarg) except Exception as e: pytest.failed(e)
""" Queries of issue queries """ def gql_issues(fragment): """ Return the GraphQL issues query """ return f''' query ($where: IssueWhere!, $first: PageSize!, $skip: Int!) {{ data: issues(where: $where, first: $first, skip: $skip) {{ {fragment} }} }} ''' GQL_ISSUES_COUNT = ''' query($where: IssueWhere!) { data: countIssues(where: $where) } '''
""" Queries of issue queries """ def gql_issues(fragment): """ Return the GraphQL issues query """ return f'\nquery ($where: IssueWhere!, $first: PageSize!, $skip: Int!) {{\n data: issues(where: $where, first: $first, skip: $skip) {{\n {fragment}\n }}\n}}\n' gql_issues_count = '\nquery($where: IssueWhere!) {\n data: countIssues(where: $where)\n}\n'
""" @desc Prints informations about the candidate : his/her profile and messages sent @params candidate: instance of Candidate """ def show_candidate_informations(candidate): print("## CANDIDATE PROFILE ##", end="\n\n") print("Firstname: {}".format(candidate.firstname)) print("Lastname: {}".format(candidate.lastname)) print("Email address: {}".format(candidate.email)) print("Job: {}".format(candidate.job), end="\n\n") print("## MESSAGE SENT ##", end="\n\n") for message in candidate.messages: print("{0} sent : {1}, {2} days ago".format( message["name"], message["ts_str"], message["diff_to_today"]) ) def show_candidates(candidates): for candidate in candidates: print("\nFirstname: {0}, Lastname: {1}, Email address: {2}, Job: {3}".format(candidate.firstname, candidate.lastname, candidate.email, candidate.job)) for message in candidate.messages: print("\t{0} sent : {1}, {2} days ago".format( message["name"], message["ts_str"], message["diff_to_today"]) )
""" @desc Prints informations about the candidate : his/her profile and messages sent @params candidate: instance of Candidate """ def show_candidate_informations(candidate): print('## CANDIDATE PROFILE ##', end='\n\n') print('Firstname: {}'.format(candidate.firstname)) print('Lastname: {}'.format(candidate.lastname)) print('Email address: {}'.format(candidate.email)) print('Job: {}'.format(candidate.job), end='\n\n') print('## MESSAGE SENT ##', end='\n\n') for message in candidate.messages: print('{0} sent : {1}, {2} days ago'.format(message['name'], message['ts_str'], message['diff_to_today'])) def show_candidates(candidates): for candidate in candidates: print('\nFirstname: {0}, Lastname: {1}, Email address: {2}, Job: {3}'.format(candidate.firstname, candidate.lastname, candidate.email, candidate.job)) for message in candidate.messages: print('\t{0} sent : {1}, {2} days ago'.format(message['name'], message['ts_str'], message['diff_to_today']))
class Korean: """Korean speaker""" def __init__(self): self.name = "Korean" def speak_korean(self): return "An-neyong?" class British: """English speaker""" def __init__(self): self.name = "British" #Note the different method name here! def speak_english(self): return "Hello!" class Adapter: """This changes the generic method name to individualized method names""" def __init__(self, object, **adapted_method): """Change the name of the method""" self._object = object #Add a new dictionary item that establishes the mapping between the generic method name: speak() and the concrete method #For example, speak() will be translated to speak_korean() if the mapping says so self.__dict__.update(adapted_method) def __getattr__(self, attr): """Simply return the rest of attributes!""" return getattr(self._object, attr) def main(): #List to store speaker objects objects = [] #Create a Korean object korean = Korean() #Create a British object british =British() #Append the objects to the objects list objects.append(Adapter(korean, speak=korean.speak_korean)) objects.append(Adapter(british, speak=british.speak_english)) for obj in objects: print("{} says '{}'\n".format(obj.name, obj.speak())) if __name__ == '__main__': main()
class Korean: """Korean speaker""" def __init__(self): self.name = 'Korean' def speak_korean(self): return 'An-neyong?' class British: """English speaker""" def __init__(self): self.name = 'British' def speak_english(self): return 'Hello!' class Adapter: """This changes the generic method name to individualized method names""" def __init__(self, object, **adapted_method): """Change the name of the method""" self._object = object self.__dict__.update(adapted_method) def __getattr__(self, attr): """Simply return the rest of attributes!""" return getattr(self._object, attr) def main(): objects = [] korean = korean() british = british() objects.append(adapter(korean, speak=korean.speak_korean)) objects.append(adapter(british, speak=british.speak_english)) for obj in objects: print("{} says '{}'\n".format(obj.name, obj.speak())) if __name__ == '__main__': main()
def green(text): return f"\033[92m{text}\033[0m" def yellow(text): return f"\033[93m{text}\033[0m"
def green(text): return f'\x1b[92m{text}\x1b[0m' def yellow(text): return f'\x1b[93m{text}\x1b[0m'
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.', 'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..', 'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.', 'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-', 'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--', '4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', '0':'-----', ', ':'--..--', '.':'.-.-.-', '?':'..--..', '/':'-..-.', '-':'-....-', '(':'-.--.', ')':'-.--.-'} # Function to encrypt the string # according to the morse code chart def encrypt(message): cipher = '' for letter in message: if letter != ' ': # Looks up the dictionary and adds the # correspponding morse code # along with a space to separate # morse codes for different characters cipher += MORSE_CODE_DICT[letter] + ' ' else: # 1 space indicates different characters # and 2 indicates different words cipher += ' ' return cipher # Hard-coded driver function to run the program def main(): message = input("Enter a Word or Phrase") result = encrypt(message.upper()) print (result) # Executes the main function if __name__ == '__main__': main()
morse_code_dict = {'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..', '1': '.----', '2': '..---', '3': '...--', '4': '....-', '5': '.....', '6': '-....', '7': '--...', '8': '---..', '9': '----.', '0': '-----', ', ': '--..--', '.': '.-.-.-', '?': '..--..', '/': '-..-.', '-': '-....-', '(': '-.--.', ')': '-.--.-'} def encrypt(message): cipher = '' for letter in message: if letter != ' ': cipher += MORSE_CODE_DICT[letter] + ' ' else: cipher += ' ' return cipher def main(): message = input('Enter a Word or Phrase') result = encrypt(message.upper()) print(result) if __name__ == '__main__': main()
# -*- coding: utf-8 -*- class MyClass: # The __init__ method doesn't return anything, so it gets return # type None just like any other method that doesn't return anything. def __init__(self) -> None: ... # For instance methods, omit `self`. def my_class_method(self, num: int, str1: str) -> str: return num * str1 # User-defined classes are written with just their own names. x = MyClass() # type: MyClass
class Myclass: def __init__(self) -> None: ... def my_class_method(self, num: int, str1: str) -> str: return num * str1 x = my_class()
expected_output = { "bridge_group": { "D": { "bridge_domain": { "D-w": { "ac": { "num_ac": 1, "num_ac_up": 1 }, "id": 0, "pbb": { "num_pbb": 0, "num_pbb_up": 0 }, "pw": { "num_pw": 1, "num_pw_up": 1 }, "state": "up", "vni": { "num_vni": 0, "num_vni_up": 0 } } } }, "GO-LEAFS": { "bridge_domain": { "GO": { "ac": { "num_ac": 3, "num_ac_up": 2 }, "id": 9, "pbb": { "num_pbb": 0, "num_pbb_up": 0 }, "pw": { "num_pw": 7, "num_pw_up": 5 }, "state": "up", "vni": { "num_vni": 0, "num_vni_up": 0 } } } }, "MGMT": { "bridge_domain": { "DSL-MGMT": { "ac": { "num_ac": 1, "num_ac_up": 0 }, "id": 2, "pbb": { "num_pbb": 0, "num_pbb_up": 0 }, "pw": { "num_pw": 0, "num_pw_up": 0 }, "state": "up", "vni": { "num_vni": 0, "num_vni_up": 0 } } } }, "WOrd": { "bridge_domain": { "CODE-123-4567": { "ac": { "num_ac": 1, "num_ac_up": 0 }, "id": 3, "pbb": { "num_pbb": 0, "num_pbb_up": 0 }, "pw": { "num_pw": 1, "num_pw_up": 0 }, "state": "up", "vni": { "num_vni": 0, "num_vni_up": 0 } } } }, "admin1": { "bridge_domain": { "domain1": { "ac": { "num_ac": 1, "num_ac_up": 0 }, "id": 6, "pbb": { "num_pbb": 0, "num_pbb_up": 0 }, "pw": { "num_pw": 1, "num_pw_up": 0 }, "state": "admin down", "vni": { "num_vni": 0, "num_vni_up": 0 } } } }, "d": { "bridge_domain": { "s-VLAN_20": { "ac": { "num_ac": 2, "num_ac_up": 2 }, "id": 1, "pbb": { "num_pbb": 0, "num_pbb_up": 0 }, "pw": { "num_pw": 1, "num_pw_up": 1 }, "state": "up", "vni": { "num_vni": 0, "num_vni_up": 0 } } } }, "g1": { "bridge_domain": { "bd1": { "ac": { "num_ac": 1, "num_ac_up": 1 }, "id": 0, "pw": { "num_pw": 1, "num_pw_up": 1 }, "state": "up" } } }, "woRD": { "bridge_domain": { "THING_PLACE_DIA-765_4321": { "ac": { "num_ac": 1, "num_ac_up": 1 }, "id": 4, "pbb": { "num_pbb": 0, "num_pbb_up": 0 }, "pw": { "num_pw": 1, "num_pw_up": 1 }, "state": "up", "vni": { "num_vni": 0, "num_vni_up": 0 } } } } } }
expected_output = {'bridge_group': {'D': {'bridge_domain': {'D-w': {'ac': {'num_ac': 1, 'num_ac_up': 1}, 'id': 0, 'pbb': {'num_pbb': 0, 'num_pbb_up': 0}, 'pw': {'num_pw': 1, 'num_pw_up': 1}, 'state': 'up', 'vni': {'num_vni': 0, 'num_vni_up': 0}}}}, 'GO-LEAFS': {'bridge_domain': {'GO': {'ac': {'num_ac': 3, 'num_ac_up': 2}, 'id': 9, 'pbb': {'num_pbb': 0, 'num_pbb_up': 0}, 'pw': {'num_pw': 7, 'num_pw_up': 5}, 'state': 'up', 'vni': {'num_vni': 0, 'num_vni_up': 0}}}}, 'MGMT': {'bridge_domain': {'DSL-MGMT': {'ac': {'num_ac': 1, 'num_ac_up': 0}, 'id': 2, 'pbb': {'num_pbb': 0, 'num_pbb_up': 0}, 'pw': {'num_pw': 0, 'num_pw_up': 0}, 'state': 'up', 'vni': {'num_vni': 0, 'num_vni_up': 0}}}}, 'WOrd': {'bridge_domain': {'CODE-123-4567': {'ac': {'num_ac': 1, 'num_ac_up': 0}, 'id': 3, 'pbb': {'num_pbb': 0, 'num_pbb_up': 0}, 'pw': {'num_pw': 1, 'num_pw_up': 0}, 'state': 'up', 'vni': {'num_vni': 0, 'num_vni_up': 0}}}}, 'admin1': {'bridge_domain': {'domain1': {'ac': {'num_ac': 1, 'num_ac_up': 0}, 'id': 6, 'pbb': {'num_pbb': 0, 'num_pbb_up': 0}, 'pw': {'num_pw': 1, 'num_pw_up': 0}, 'state': 'admin down', 'vni': {'num_vni': 0, 'num_vni_up': 0}}}}, 'd': {'bridge_domain': {'s-VLAN_20': {'ac': {'num_ac': 2, 'num_ac_up': 2}, 'id': 1, 'pbb': {'num_pbb': 0, 'num_pbb_up': 0}, 'pw': {'num_pw': 1, 'num_pw_up': 1}, 'state': 'up', 'vni': {'num_vni': 0, 'num_vni_up': 0}}}}, 'g1': {'bridge_domain': {'bd1': {'ac': {'num_ac': 1, 'num_ac_up': 1}, 'id': 0, 'pw': {'num_pw': 1, 'num_pw_up': 1}, 'state': 'up'}}}, 'woRD': {'bridge_domain': {'THING_PLACE_DIA-765_4321': {'ac': {'num_ac': 1, 'num_ac_up': 1}, 'id': 4, 'pbb': {'num_pbb': 0, 'num_pbb_up': 0}, 'pw': {'num_pw': 1, 'num_pw_up': 1}, 'state': 'up', 'vni': {'num_vni': 0, 'num_vni_up': 0}}}}}}
INPUT_TO_DWI_CONVERSION_EDGES = [("dwi_file", "in_file")] INPUT_TO_FMAP_CONVERSION_EDGES = [("fmap_file", "in_file")] LOCATE_ASSOCIATED_TO_COVERSION_EDGES = [ ("json_file", "json_import"), ("bvec_file", "in_bvec"), ("bval_file", "in_bval"), ] DWI_CONVERSION_TO_OUTPUT_EDGES = [("out_file", "dwi_file")] FMAP_CONVERSION_TO_OUTPUT_EDGES = [("out_file", "fmap_file")]
input_to_dwi_conversion_edges = [('dwi_file', 'in_file')] input_to_fmap_conversion_edges = [('fmap_file', 'in_file')] locate_associated_to_coversion_edges = [('json_file', 'json_import'), ('bvec_file', 'in_bvec'), ('bval_file', 'in_bval')] dwi_conversion_to_output_edges = [('out_file', 'dwi_file')] fmap_conversion_to_output_edges = [('out_file', 'fmap_file')]
almacen_api_config = { 'debug': { 'name': 'almacen_api', 'database': 'stage_01', 'debug': True, 'app': { 'DEBUG': True, 'UPLOAD_FOLDER': '/tmp', }, 'run': { # 'ssl_context': ('ssl/cert.pem', 'ssl/key.pem'), 'port': 8000, }, 'app_tokens': { 'TOKEN': { 'app': 'development', 'roles': ['super', 'tagger'], }, 'TOKEN': { 'app': 'longcat_api', 'roles': ['tagger'], }, }, }, 'development': { 'name': 'almacen_api', 'database': 'stage_01', 'run': { 'port': 8000, }, 'app_tokens': { 'TOKEN': { 'app': 'development', 'roles': ['super', 'tagger'], }, 'TOKEN': { 'app': 'longcat_api', 'roles': ['tagger'], }, 'TOKEN': { 'app': 'longcat_api', 'roles': ['reader'], }, }, 's3_query_results_bucket': { 'access_key_id': 'ACCESSKEY', 'secret_access_key': 'SECRET', 'bucket_name': 'almacen-entrega', 'bucket_region': 'us-east-2', 'bucket_directory': 'almacen_api/stage/query_results', }, }, 'production': { 'name': 'almacen_api', 'database': 'prod_01', 'app_tokens': { 'TOKEN': { 'app': 'longcat_api', 'roles': ['tagger'], }, }, }, 'testing': { 'name': 'almacen_api_test', 'database': 'stage_01', 'app_tokens': { 'TOKEN': { 'app': 'development', 'roles': ['super', 'tagger'], }, }, }, }
almacen_api_config = {'debug': {'name': 'almacen_api', 'database': 'stage_01', 'debug': True, 'app': {'DEBUG': True, 'UPLOAD_FOLDER': '/tmp'}, 'run': {'port': 8000}, 'app_tokens': {'TOKEN': {'app': 'development', 'roles': ['super', 'tagger']}, 'TOKEN': {'app': 'longcat_api', 'roles': ['tagger']}}}, 'development': {'name': 'almacen_api', 'database': 'stage_01', 'run': {'port': 8000}, 'app_tokens': {'TOKEN': {'app': 'development', 'roles': ['super', 'tagger']}, 'TOKEN': {'app': 'longcat_api', 'roles': ['tagger']}, 'TOKEN': {'app': 'longcat_api', 'roles': ['reader']}}, 's3_query_results_bucket': {'access_key_id': 'ACCESSKEY', 'secret_access_key': 'SECRET', 'bucket_name': 'almacen-entrega', 'bucket_region': 'us-east-2', 'bucket_directory': 'almacen_api/stage/query_results'}}, 'production': {'name': 'almacen_api', 'database': 'prod_01', 'app_tokens': {'TOKEN': {'app': 'longcat_api', 'roles': ['tagger']}}}, 'testing': {'name': 'almacen_api_test', 'database': 'stage_01', 'app_tokens': {'TOKEN': {'app': 'development', 'roles': ['super', 'tagger']}}}}
a=1 def change_integer(a): a = a+1 return a print (change_integer(a)) print (a) b=[1,2,3] def change_list(b): b[0]=b[0]+1 return b print (change_list(b)) print (b)
a = 1 def change_integer(a): a = a + 1 return a print(change_integer(a)) print(a) b = [1, 2, 3] def change_list(b): b[0] = b[0] + 1 return b print(change_list(b)) print(b)
number_1 = int(input()) number_2 = int(input()) if number_1 >= number_2: print(number_1) print(number_2) else: print(number_2) print(number_1)
number_1 = int(input()) number_2 = int(input()) if number_1 >= number_2: print(number_1) print(number_2) else: print(number_2) print(number_1)
#!/usr/bin/env python3 # CHECKED A = [[4.5, -1, -1, 1], [-1, 4.5, 1, -1], [-1, 2, 4.5, -1], [2, -1, -1, 4.5]] b = [1, -1, -1, 0] x = [0.25, 0.25, 0.25, 0.25] x_new = [0, 0, 0, 0] for k in range(2): for i in range(4): x_new[i] = b[i] for j in range(4): if j != i: x_new[i] -= A[i][j] * x[j] x_new[i] *= (1 / A[i][i]) print("Ans", k, "\n", x_new) x = x_new.copy()
a = [[4.5, -1, -1, 1], [-1, 4.5, 1, -1], [-1, 2, 4.5, -1], [2, -1, -1, 4.5]] b = [1, -1, -1, 0] x = [0.25, 0.25, 0.25, 0.25] x_new = [0, 0, 0, 0] for k in range(2): for i in range(4): x_new[i] = b[i] for j in range(4): if j != i: x_new[i] -= A[i][j] * x[j] x_new[i] *= 1 / A[i][i] print('Ans', k, '\n', x_new) x = x_new.copy()
class Solution: # @param num : a list of integer # @return : a list of integer def nextPermutation(self, num): # write your code here # Version 1 bp = -1 for i in range(len(num) - 1): if (num[i] < num[i + 1]): bp = i if (bp == -1): num.reverse() return num rest = num[bp:] local_max = None for i in rest: if (i > rest[0] and (local_max is None or i < local_max)): local_max = i rest.pop(rest.index(local_max)) rest = sorted(rest) return num[:bp] + [local_max] + rest # Version 2 # i = len(num) - 1 # target_index = None # second_index = None # while (i > 0): # if (num[i] > num[i - 1]): # target_index = i - 1 # break # i -= 1 # if (target_index is None): # return sorted(num) # i = len(num) - 1 # while (i > target_index): # if (num[i] > num[target_index]): # second_index = i # break # i -= 1 # temp = num[target_index] # num[target_index] = num[second_index] # num[second_index] = temp # return num[:target_index] + [num[target_index]] + sorted(num[target_index + 1:])
class Solution: def next_permutation(self, num): bp = -1 for i in range(len(num) - 1): if num[i] < num[i + 1]: bp = i if bp == -1: num.reverse() return num rest = num[bp:] local_max = None for i in rest: if i > rest[0] and (local_max is None or i < local_max): local_max = i rest.pop(rest.index(local_max)) rest = sorted(rest) return num[:bp] + [local_max] + rest
X = int(input()) a_list = [] for s in range(1, 32): for i in range(2, 10): a = s ** i if a > 1000: break a_list.append(a) a2 = sorted(list(set(a_list)), reverse=True) for n in a2: if n <= X: print(n) break
x = int(input()) a_list = [] for s in range(1, 32): for i in range(2, 10): a = s ** i if a > 1000: break a_list.append(a) a2 = sorted(list(set(a_list)), reverse=True) for n in a2: if n <= X: print(n) break
def presentacion_inicial(): print("*"*20) print("Que accion desea realizar : ") print("1) Insertar Persona : ") print("2) Insertar Empleado : ") print("3) Consultar las personas : ") print("4) Consultar por empleados : ") return int(input("Opcion necesitas : "))
def presentacion_inicial(): print('*' * 20) print('Que accion desea realizar : ') print('1) Insertar Persona : ') print('2) Insertar Empleado : ') print('3) Consultar las personas : ') print('4) Consultar por empleados : ') return int(input('Opcion necesitas : '))
class SEHException(ExternalException): """ Represents structured exception handling (SEH) errors. SEHException() SEHException(message: str) SEHException(message: str,inner: Exception) """ def ZZZ(self): """hardcoded/mock instance of the class""" return SEHException() instance=ZZZ() """hardcoded/returns an instance of the class""" def CanResume(self): """ CanResume(self: SEHException) -> bool Indicates whether the exception can be recovered from,and whether the code can continue from the point at which the exception was thrown. Returns: Always false,because resumable exceptions are not implemented. """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,message=None,inner=None): """ __new__(cls: type) __new__(cls: type,message: str) __new__(cls: type,message: str,inner: Exception) __new__(cls: type,info: SerializationInfo,context: StreamingContext) """ pass def __reduce_ex__(self,*args): pass def __str__(self,*args): pass SerializeObjectState=None
class Sehexception(ExternalException): """ Represents structured exception handling (SEH) errors. SEHException() SEHException(message: str) SEHException(message: str,inner: Exception) """ def zzz(self): """hardcoded/mock instance of the class""" return seh_exception() instance = zzz() 'hardcoded/returns an instance of the class' def can_resume(self): """ CanResume(self: SEHException) -> bool Indicates whether the exception can be recovered from,and whether the code can continue from the point at which the exception was thrown. Returns: Always false,because resumable exceptions are not implemented. """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self, message=None, inner=None): """ __new__(cls: type) __new__(cls: type,message: str) __new__(cls: type,message: str,inner: Exception) __new__(cls: type,info: SerializationInfo,context: StreamingContext) """ pass def __reduce_ex__(self, *args): pass def __str__(self, *args): pass serialize_object_state = None
# encoding: utf-8 # module Revit.References calls itself References # from RevitNodes,Version=1.2.1.3083,Culture=neutral,PublicKeyToken=null # by generator 1.145 # no doc # no imports # no functions # classes class RayBounce(object): # no doc @staticmethod def ByOriginDirection(origin, direction, maxBounces, view): """ ByOriginDirection(origin: Point,direction: Vector,maxBounces: int,view: View3D) -> Dictionary[str,object] Returns positions and elements hit by ray bounce from the specified origin point and direction """ pass __all__ = [ "ByOriginDirection", ]
class Raybounce(object): @staticmethod def by_origin_direction(origin, direction, maxBounces, view): """ ByOriginDirection(origin: Point,direction: Vector,maxBounces: int,view: View3D) -> Dictionary[str,object] Returns positions and elements hit by ray bounce from the specified origin point and direction """ pass __all__ = ['ByOriginDirection']
load("@io_bazel_rules_docker//go:image.bzl", go_image_repositories="repositories") load("@io_bazel_rules_docker//container:container.bzl", container_repositories = "repositories") def initialize_rules_docker(): container_repositories() go_image_repositories() load("@distroless//package_manager:package_manager.bzl", "package_manager_repositories",) def initialize_rules_package_manager(): package_manager_repositories()
load('@io_bazel_rules_docker//go:image.bzl', go_image_repositories='repositories') load('@io_bazel_rules_docker//container:container.bzl', container_repositories='repositories') def initialize_rules_docker(): container_repositories() go_image_repositories() load('@distroless//package_manager:package_manager.bzl', 'package_manager_repositories') def initialize_rules_package_manager(): package_manager_repositories()
""" 1. Problem Summary / Clarifications / TDD: output("abcd", "abecd") = "e" 2. Inuition: xor operator 3. Tests: output("abcd", "abecd") = "e": The added character is in the middle of t output("abcd", "abcde") = "e": The added character is at the end of t output("abcd", "eabcd") = "e": The added character is at the beginning of t Specific case output("aaa", "aaaa") = "a" Edge case: s is empty output("", "a") = "a" 3. Complexity Analysis: Time Complexity: O(|t|) Space Complexity: O(1) """ class Solution: def findTheDifference(self, s: str, t: str) -> str: xor_result = 0 for i in range(len(s)): xor_result ^= ord(s[i]) xor_result ^= ord(t[i]) xor_result ^= ord(t[-1]) return chr(xor_result)
""" 1. Problem Summary / Clarifications / TDD: output("abcd", "abecd") = "e" 2. Inuition: xor operator 3. Tests: output("abcd", "abecd") = "e": The added character is in the middle of t output("abcd", "abcde") = "e": The added character is at the end of t output("abcd", "eabcd") = "e": The added character is at the beginning of t Specific case output("aaa", "aaaa") = "a" Edge case: s is empty output("", "a") = "a" 3. Complexity Analysis: Time Complexity: O(|t|) Space Complexity: O(1) """ class Solution: def find_the_difference(self, s: str, t: str) -> str: xor_result = 0 for i in range(len(s)): xor_result ^= ord(s[i]) xor_result ^= ord(t[i]) xor_result ^= ord(t[-1]) return chr(xor_result)
# urls.py # urls for dash app url_paths = { "index": '/', "home": '/home', "scatter": '/apps/scatter-test', "combo": '/apps/combo-test' }
url_paths = {'index': '/', 'home': '/home', 'scatter': '/apps/scatter-test', 'combo': '/apps/combo-test'}
scoreboard_display = [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25'], ['51', '50', '49', '48', '47', '46', '45', '44', '43', '42', '41', '40', '39', '38', '37', '36', '35', '34', '33', '32', '31', '30', '29', '28', '27', '26'], ['52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77'], ['103', '102', '101', '100', '99', '98', '97', '96', '95', '94', '93', '92', '91', '90', '89', '88', '87', '86', '85', '84', '83', '82', '81', '80', '79', '78'], ['104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129'], ['155', '154', '153', '152', '151', '150', '149', '148', '147', '146', '145', '144', '143', '142', '141', '140', '139', '138', '137', '136', '135', '134', '133', '132', '131', '130'], ['156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181'], ['207', '206', '205', '204', '203', '202', '201', '200', '199', '198', '197', '196', '195', '194', '193', '192', '191', '190', '189', '188', '187', '186', '185', '184', '183', '182'], ['208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233'], ['259', '258', '257', '256', '255', '254', '253', '252', '251', '250', '249', '248', '247', '246', '245', '244', '243', '242', '241', '240', '239', '238', '237', '236', '235', '234'], ['260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285'], ['311', '310', '309', '308', '307', '306', '305', '304', '303', '302', '301', '300', '299', '298', '297', '296', '295', '294', '293', '292', '291', '290', '289', '288', '287', '286'], ['312', '313', '314', '315', '316', '317', '318', '319', '320', '321', '322', '323', '324', '325', '326', '327', '328', '329', '330', '331', '332', '333', '334', '335', '336', '337'], ['363', '362', '361', '360', '359', '358', '357', '356', '355', '354', '353', '352', '351', '350', '349', '348', '347', '346', '345', '344', '343', '342', '341', '340', '339', '338'], ['364', '365', '366', '367', '368', '369', '370', '371', '372', '373', '374', '375', '376', '377', '378', '379', '380', '381', '382', '383', '384', '385', '386', '387', '388', '389'], ['415', '414', '413', '412', '411', '410', '409', '408', '407', '406', '405', '404', '403', '402', '401', '400', '399', '398', '397', '396', '395', '394', '393', '392', '391', '390'], ['416', '417', '418', '419', '420', '421', '422', '423', '424', '425', '426', '427', '428', '429', '430', '431', '432', '433', '434', '435', '436', '437', '438', '439', '440', '441']]
scoreboard_display = [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25'], ['51', '50', '49', '48', '47', '46', '45', '44', '43', '42', '41', '40', '39', '38', '37', '36', '35', '34', '33', '32', '31', '30', '29', '28', '27', '26'], ['52', '53', '54', '55', '56', '57', '58', '59', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '70', '71', '72', '73', '74', '75', '76', '77'], ['103', '102', '101', '100', '99', '98', '97', '96', '95', '94', '93', '92', '91', '90', '89', '88', '87', '86', '85', '84', '83', '82', '81', '80', '79', '78'], ['104', '105', '106', '107', '108', '109', '110', '111', '112', '113', '114', '115', '116', '117', '118', '119', '120', '121', '122', '123', '124', '125', '126', '127', '128', '129'], ['155', '154', '153', '152', '151', '150', '149', '148', '147', '146', '145', '144', '143', '142', '141', '140', '139', '138', '137', '136', '135', '134', '133', '132', '131', '130'], ['156', '157', '158', '159', '160', '161', '162', '163', '164', '165', '166', '167', '168', '169', '170', '171', '172', '173', '174', '175', '176', '177', '178', '179', '180', '181'], ['207', '206', '205', '204', '203', '202', '201', '200', '199', '198', '197', '196', '195', '194', '193', '192', '191', '190', '189', '188', '187', '186', '185', '184', '183', '182'], ['208', '209', '210', '211', '212', '213', '214', '215', '216', '217', '218', '219', '220', '221', '222', '223', '224', '225', '226', '227', '228', '229', '230', '231', '232', '233'], ['259', '258', '257', '256', '255', '254', '253', '252', '251', '250', '249', '248', '247', '246', '245', '244', '243', '242', '241', '240', '239', '238', '237', '236', '235', '234'], ['260', '261', '262', '263', '264', '265', '266', '267', '268', '269', '270', '271', '272', '273', '274', '275', '276', '277', '278', '279', '280', '281', '282', '283', '284', '285'], ['311', '310', '309', '308', '307', '306', '305', '304', '303', '302', '301', '300', '299', '298', '297', '296', '295', '294', '293', '292', '291', '290', '289', '288', '287', '286'], ['312', '313', '314', '315', '316', '317', '318', '319', '320', '321', '322', '323', '324', '325', '326', '327', '328', '329', '330', '331', '332', '333', '334', '335', '336', '337'], ['363', '362', '361', '360', '359', '358', '357', '356', '355', '354', '353', '352', '351', '350', '349', '348', '347', '346', '345', '344', '343', '342', '341', '340', '339', '338'], ['364', '365', '366', '367', '368', '369', '370', '371', '372', '373', '374', '375', '376', '377', '378', '379', '380', '381', '382', '383', '384', '385', '386', '387', '388', '389'], ['415', '414', '413', '412', '411', '410', '409', '408', '407', '406', '405', '404', '403', '402', '401', '400', '399', '398', '397', '396', '395', '394', '393', '392', '391', '390'], ['416', '417', '418', '419', '420', '421', '422', '423', '424', '425', '426', '427', '428', '429', '430', '431', '432', '433', '434', '435', '436', '437', '438', '439', '440', '441']]
# flake8: noqa # in legacy datasets we need to put our sample data within the data dir legacy_datasets = ["cmu_small_region.svs"] # Registry of datafiles that can be downloaded along with their SHA256 hashes # To generate the SHA256 hash, use the command # openssl sha256 filename registry = { "histolab/broken.svs": "b1325916876afa17ad5e02d2e7298ee883e758ed25369470d85bc0990e928e11", "histolab/kidney.png": "5c6dc1b9ae10a2865302d9c8eda360362ec47732cb3e9766c38ed90cb9f4c371", "data/cmu_small_region.svs": "ed92d5a9f2e86df67640d6f92ce3e231419ce127131697fbbce42ad5e002c8a7", "aperio/JP2K-33003-1.svs": "6205ccf75a8fa6c32df7c5c04b7377398971a490fb6b320d50d91f7ba6a0e6fd", "aperio/JP2K-33003-2.svs": "1a13cef86b55b51127cebd94a1f6069f7de494c98e3e708640d1ce7181d9e3fd", "tcga/breast/TCGA-A8-A082-01A-01-TS1.3cad4a77-47a6-4658-becf-d8cffa161d3a.svs": "e955f47b83c8a5ae382ff8559493548f90f85c17c86315dd03134c041f44df70", "tcga/breast/TCGA-A1-A0SH-01Z-00-DX1.90E71B08-E1D9-4FC2-85AC-062E56DDF17C.svs": "6de90fe92400e592839ab7f87c15d9924bc539c61ee3b3bc8ef044f98d16031b", "tcga/breast/TCGA-E9-A24A-01Z-00-DX1.F0342837-5750-4172-B60D-5F902E2A02FD.svs": "55c694262c4d44b342e08eb3ef2082eeb9e9deeb3cb445e4776419bb9fa7dc21", "tcga/breast/TCGA-BH-A201-01Z-00-DX1.6D6E3224-50A0-45A2-B231-EEF27CA7EFD2.svs": "e1ccf3360078844abbec4b96c5da59a029a441c1ab6d7f694ec80d9d79bd3837", "tcga/prostate/TCGA-CH-5753-01A-01-BS1.4311c533-f9c1-4c6f-8b10-922daa3c2e3e.svs": "93ed7aa906c9e127c8241bc5da197902ebb71ccda4db280aefbe0ecd952b9089", "tcga/ovarian/TCGA-13-1404-01A-01-TS1.cecf7044-1d29-4d14-b137-821f8d48881e.svs": "6796e23af7cd219b9ff2274c087759912529fec9f49e2772a868ba9d85d389d6", "9798433/?format=tif": "7db49ff9fc3f6022ae334cf019e94ef4450f7d4cf0d71783e0f6ea82965d3a52", "9798554/?format=tif": "8a4318ac713b4cf50c3314760da41ab7653e10e90531ecd0c787f1386857a4ef", } APERIO_REPO_URL = "http://openslide.cs.cmu.edu/download/openslide-testdata/Aperio" TCGA_REPO_URL = "https://api.gdc.cancer.gov/data" IDR_REPO_URL = "https://idr.openmicroscopy.org/webclient/render_image_download" registry_urls = { "histolab/broken.svs": "https://raw.githubusercontent.com/histolab/histolab/master/tests/fixtures/svs-images/broken.svs", "histolab/kidney.png": "https://user-images.githubusercontent.com/4196091/100275351-132cc880-2f60-11eb-8cc8-7a3bf3723260.png", "aperio/JP2K-33003-1.svs": f"{APERIO_REPO_URL}/JP2K-33003-1.svs", "aperio/JP2K-33003-2.svs": f"{APERIO_REPO_URL}/JP2K-33003-2.svs", "tcga/breast/TCGA-A8-A082-01A-01-TS1.3cad4a77-47a6-4658-becf-d8cffa161d3a.svs": f"{TCGA_REPO_URL}/ad9ed74a-2725-49e6-bf7a-ef100e299989", "tcga/breast/TCGA-A1-A0SH-01Z-00-DX1.90E71B08-E1D9-4FC2-85AC-062E56DDF17C.svs": f"{TCGA_REPO_URL}/3845b8bd-cbe0-49cf-a418-a8120f6c23db", "tcga/breast/TCGA-E9-A24A-01Z-00-DX1.F0342837-5750-4172-B60D-5F902E2A02FD.svs": f"{TCGA_REPO_URL}/682e4d74-2200-4f34-9e96-8dee968b1568", "tcga/breast/TCGA-BH-A201-01Z-00-DX1.6D6E3224-50A0-45A2-B231-EEF27CA7EFD2.svs": f"{TCGA_REPO_URL}/e70c89a5-1c2f-43f8-b6be-589beea55338", "tcga/prostate/TCGA-CH-5753-01A-01-BS1.4311c533-f9c1-4c6f-8b10-922daa3c2e3e.svs": f"{TCGA_REPO_URL}/5a8ce04a-0178-49e2-904c-30e21fb4e41e", "tcga/ovarian/TCGA-13-1404-01A-01-TS1.cecf7044-1d29-4d14-b137-821f8d48881e.svs": f"{TCGA_REPO_URL}/e968375e-ef58-4607-b457-e6818b2e8431", "9798433/?format=tif": f"{IDR_REPO_URL}/9798433/?format=tif", "9798554/?format=tif": f"{IDR_REPO_URL}/9798554/?format=tif", } legacy_registry = { ("data/" + filename): registry["data/" + filename] for filename in legacy_datasets }
legacy_datasets = ['cmu_small_region.svs'] registry = {'histolab/broken.svs': 'b1325916876afa17ad5e02d2e7298ee883e758ed25369470d85bc0990e928e11', 'histolab/kidney.png': '5c6dc1b9ae10a2865302d9c8eda360362ec47732cb3e9766c38ed90cb9f4c371', 'data/cmu_small_region.svs': 'ed92d5a9f2e86df67640d6f92ce3e231419ce127131697fbbce42ad5e002c8a7', 'aperio/JP2K-33003-1.svs': '6205ccf75a8fa6c32df7c5c04b7377398971a490fb6b320d50d91f7ba6a0e6fd', 'aperio/JP2K-33003-2.svs': '1a13cef86b55b51127cebd94a1f6069f7de494c98e3e708640d1ce7181d9e3fd', 'tcga/breast/TCGA-A8-A082-01A-01-TS1.3cad4a77-47a6-4658-becf-d8cffa161d3a.svs': 'e955f47b83c8a5ae382ff8559493548f90f85c17c86315dd03134c041f44df70', 'tcga/breast/TCGA-A1-A0SH-01Z-00-DX1.90E71B08-E1D9-4FC2-85AC-062E56DDF17C.svs': '6de90fe92400e592839ab7f87c15d9924bc539c61ee3b3bc8ef044f98d16031b', 'tcga/breast/TCGA-E9-A24A-01Z-00-DX1.F0342837-5750-4172-B60D-5F902E2A02FD.svs': '55c694262c4d44b342e08eb3ef2082eeb9e9deeb3cb445e4776419bb9fa7dc21', 'tcga/breast/TCGA-BH-A201-01Z-00-DX1.6D6E3224-50A0-45A2-B231-EEF27CA7EFD2.svs': 'e1ccf3360078844abbec4b96c5da59a029a441c1ab6d7f694ec80d9d79bd3837', 'tcga/prostate/TCGA-CH-5753-01A-01-BS1.4311c533-f9c1-4c6f-8b10-922daa3c2e3e.svs': '93ed7aa906c9e127c8241bc5da197902ebb71ccda4db280aefbe0ecd952b9089', 'tcga/ovarian/TCGA-13-1404-01A-01-TS1.cecf7044-1d29-4d14-b137-821f8d48881e.svs': '6796e23af7cd219b9ff2274c087759912529fec9f49e2772a868ba9d85d389d6', '9798433/?format=tif': '7db49ff9fc3f6022ae334cf019e94ef4450f7d4cf0d71783e0f6ea82965d3a52', '9798554/?format=tif': '8a4318ac713b4cf50c3314760da41ab7653e10e90531ecd0c787f1386857a4ef'} aperio_repo_url = 'http://openslide.cs.cmu.edu/download/openslide-testdata/Aperio' tcga_repo_url = 'https://api.gdc.cancer.gov/data' idr_repo_url = 'https://idr.openmicroscopy.org/webclient/render_image_download' registry_urls = {'histolab/broken.svs': 'https://raw.githubusercontent.com/histolab/histolab/master/tests/fixtures/svs-images/broken.svs', 'histolab/kidney.png': 'https://user-images.githubusercontent.com/4196091/100275351-132cc880-2f60-11eb-8cc8-7a3bf3723260.png', 'aperio/JP2K-33003-1.svs': f'{APERIO_REPO_URL}/JP2K-33003-1.svs', 'aperio/JP2K-33003-2.svs': f'{APERIO_REPO_URL}/JP2K-33003-2.svs', 'tcga/breast/TCGA-A8-A082-01A-01-TS1.3cad4a77-47a6-4658-becf-d8cffa161d3a.svs': f'{TCGA_REPO_URL}/ad9ed74a-2725-49e6-bf7a-ef100e299989', 'tcga/breast/TCGA-A1-A0SH-01Z-00-DX1.90E71B08-E1D9-4FC2-85AC-062E56DDF17C.svs': f'{TCGA_REPO_URL}/3845b8bd-cbe0-49cf-a418-a8120f6c23db', 'tcga/breast/TCGA-E9-A24A-01Z-00-DX1.F0342837-5750-4172-B60D-5F902E2A02FD.svs': f'{TCGA_REPO_URL}/682e4d74-2200-4f34-9e96-8dee968b1568', 'tcga/breast/TCGA-BH-A201-01Z-00-DX1.6D6E3224-50A0-45A2-B231-EEF27CA7EFD2.svs': f'{TCGA_REPO_URL}/e70c89a5-1c2f-43f8-b6be-589beea55338', 'tcga/prostate/TCGA-CH-5753-01A-01-BS1.4311c533-f9c1-4c6f-8b10-922daa3c2e3e.svs': f'{TCGA_REPO_URL}/5a8ce04a-0178-49e2-904c-30e21fb4e41e', 'tcga/ovarian/TCGA-13-1404-01A-01-TS1.cecf7044-1d29-4d14-b137-821f8d48881e.svs': f'{TCGA_REPO_URL}/e968375e-ef58-4607-b457-e6818b2e8431', '9798433/?format=tif': f'{IDR_REPO_URL}/9798433/?format=tif', '9798554/?format=tif': f'{IDR_REPO_URL}/9798554/?format=tif'} legacy_registry = {'data/' + filename: registry['data/' + filename] for filename in legacy_datasets}
print('=' * 15, '\033[1;35mAULA 18 - Listas[Part #2]\033[m', '=' * 15) # -------------------------------------------------------------------- dados = [] pessoas = [] galera = [['Miguel', 25], ['Berta', 59], ['Joaquim', 20]] # -------------------------------------------------------------------- dados.append('Joaquim') dados.append(20) dados.append('Fernando') dados.append(23) dados.append('Maria') dados.append(19) pessoas.append(dados[:]) # galera.append(pessoas[:]) print(galera[0][0]) # Miguel print(galera[1][1]) # 59 print(galera[2][0]) # Joaquim print(galera[1]) # Berta + 59
print('=' * 15, '\x1b[1;35mAULA 18 - Listas[Part #2]\x1b[m', '=' * 15) dados = [] pessoas = [] galera = [['Miguel', 25], ['Berta', 59], ['Joaquim', 20]] dados.append('Joaquim') dados.append(20) dados.append('Fernando') dados.append(23) dados.append('Maria') dados.append(19) pessoas.append(dados[:]) print(galera[0][0]) print(galera[1][1]) print(galera[2][0]) print(galera[1])
P, D = list(map(int, input().split(' '))) totA, totB = 0, 0 dis = [[0,0,0,0] for i in range(D)] for i in range(P): a, b, c = map(int, input().split(' ')) k = (b+c)//2 + 1 dis[a-1][0] += b dis[a-1][1] += c for i, (ta, tb, _, _) in enumerate(dis): k = (ta + tb)//2 + 1 if ta > tb: wA = ta-k wB = tb else: wA = ta wB = tb-k dis[i][2] = wA dis[i][3] = wB print('A' if ta > tb else 'B', f"{wA} {wB}") tot = sum(a[0] + a[1] for a in dis) wA = sum(a[2] for a in dis) wB = sum(a[3] for a in dis) print(abs(wA - wB) / tot)
(p, d) = list(map(int, input().split(' '))) (tot_a, tot_b) = (0, 0) dis = [[0, 0, 0, 0] for i in range(D)] for i in range(P): (a, b, c) = map(int, input().split(' ')) k = (b + c) // 2 + 1 dis[a - 1][0] += b dis[a - 1][1] += c for (i, (ta, tb, _, _)) in enumerate(dis): k = (ta + tb) // 2 + 1 if ta > tb: w_a = ta - k w_b = tb else: w_a = ta w_b = tb - k dis[i][2] = wA dis[i][3] = wB print('A' if ta > tb else 'B', f'{wA} {wB}') tot = sum((a[0] + a[1] for a in dis)) w_a = sum((a[2] for a in dis)) w_b = sum((a[3] for a in dis)) print(abs(wA - wB) / tot)
# -*- coding: utf-8 -*- def _data_from_bar(ax, bar_label): """Given a matplotlib Axes object and a bar label, returns (x,y,w,h) data underlying the bar plot. Args: ax: The Axes object the data will be extracted from. bar_label: The bar label from which you want to extract the data. Returns: A list of (x,y,w,h) for this bar. """ data = [] # each bar is made of several rectangles (matplotlib "artists") # here we extract their coordinates from the bar label handles = ax.get_legend_handles_labels() # handles[0] is a list of list of artists (one per bar) # handles[1] is a list of bar labels bar_artists = handles[0][handles[1].index(bar_label)] # each artist of the bar is a rectangle for rectangle in bar_artists: data.append([ rectangle.get_x(), rectangle.get_y(), rectangle.get_width(), rectangle.get_height() ]) return data
def _data_from_bar(ax, bar_label): """Given a matplotlib Axes object and a bar label, returns (x,y,w,h) data underlying the bar plot. Args: ax: The Axes object the data will be extracted from. bar_label: The bar label from which you want to extract the data. Returns: A list of (x,y,w,h) for this bar. """ data = [] handles = ax.get_legend_handles_labels() bar_artists = handles[0][handles[1].index(bar_label)] for rectangle in bar_artists: data.append([rectangle.get_x(), rectangle.get_y(), rectangle.get_width(), rectangle.get_height()]) return data
baklava_price = float(input()) muffin_price = float(input()) shtolen_kg = float(input()) candy_kg = float(input()) bisquits_kg = int(input()) shtolen_price = baklava_price + baklava_price * 0.6 candy_price = muffin_price + muffin_price * 0.8 busquits_price = 7.50 shtolen_sum = shtolen_kg * shtolen_price candy_sum = candy_kg * candy_price bisquits_sum = bisquits_kg * busquits_price all_sum = shtolen_sum + candy_sum + bisquits_sum print(f'{all_sum:.2f}')
baklava_price = float(input()) muffin_price = float(input()) shtolen_kg = float(input()) candy_kg = float(input()) bisquits_kg = int(input()) shtolen_price = baklava_price + baklava_price * 0.6 candy_price = muffin_price + muffin_price * 0.8 busquits_price = 7.5 shtolen_sum = shtolen_kg * shtolen_price candy_sum = candy_kg * candy_price bisquits_sum = bisquits_kg * busquits_price all_sum = shtolen_sum + candy_sum + bisquits_sum print(f'{all_sum:.2f}')
""" Generic utilities """ def any(seq): for i in seq: if i: return True return False
""" Generic utilities """ def any(seq): for i in seq: if i: return True return False
x=int(input('Enter the number to convert: ')) print('Select the convertion') print(''' [ 1 ] Binary [ 1 ] Octal [ 3 ] HexaDeicmal ''') y=int(input('1 - Binary 2 - Octal 3 - Hexadecimal')) if y==1: bin(x)[2:] print('{}'.format(x)) elif y==2: oct(x) print('{}'.format(x)) elif y==3: hex(x) print(x) else: print('Invalid')
x = int(input('Enter the number to convert: ')) print('Select the convertion') print(' \n[ 1 ] Binary\n[ 1 ] Octal\n[ 3 ] HexaDeicmal\n') y = int(input('1 - Binary 2 - Octal 3 - Hexadecimal')) if y == 1: bin(x)[2:] print('{}'.format(x)) elif y == 2: oct(x) print('{}'.format(x)) elif y == 3: hex(x) print(x) else: print('Invalid')
# -*- coding: utf-8 -*- """ meetup.py ~~~~~~~~~ a mock for the Meetup APi client """ class MockMeetupGroup: def __init__(self, *args, **kwargs): self.name = "Mock Meetup Group" self.link = "https://www.meetup.com/MeetupGroup/" self.next_event = { "id": 0, "name": "Monthly Meetup", "venue": "Galvanize", "yes_rsvp_count": 9, "time": 1518571800000, # February 13, 2018 6:30PM "utc_offset": -25200000, } class MockMeetupEvents: def __init__(self, *args, **kwargs): self.results = [MockMeetupGroup().next_event] + [self.events(_) for _ in range(1, 6)] def events(self, idx): return {k: idx for k in ["id", "venue", "time", "utc_offset"]} class MockMeetup: api_key = "" def __init__(self, *args, **kwargs): return def GetGroup(self, *args, **kwargs): return MockMeetupGroup() def GetEvents(self, *args, **kwargs): return MockMeetupEvents()
""" meetup.py ~~~~~~~~~ a mock for the Meetup APi client """ class Mockmeetupgroup: def __init__(self, *args, **kwargs): self.name = 'Mock Meetup Group' self.link = 'https://www.meetup.com/MeetupGroup/' self.next_event = {'id': 0, 'name': 'Monthly Meetup', 'venue': 'Galvanize', 'yes_rsvp_count': 9, 'time': 1518571800000, 'utc_offset': -25200000} class Mockmeetupevents: def __init__(self, *args, **kwargs): self.results = [mock_meetup_group().next_event] + [self.events(_) for _ in range(1, 6)] def events(self, idx): return {k: idx for k in ['id', 'venue', 'time', 'utc_offset']} class Mockmeetup: api_key = '' def __init__(self, *args, **kwargs): return def get_group(self, *args, **kwargs): return mock_meetup_group() def get_events(self, *args, **kwargs): return mock_meetup_events()
#!/usr/bin/python3 def safe_print_list_integers(my_list=[], x=0): i = 0 for index in range(x): try: print("{:d}".format(my_list[index]), end="") i += 1 except (ValueError, TypeError): pass print() return i
def safe_print_list_integers(my_list=[], x=0): i = 0 for index in range(x): try: print('{:d}'.format(my_list[index]), end='') i += 1 except (ValueError, TypeError): pass print() return i
N = int(input()) A, B = ( zip(*(map(int, input().split()) for _ in range(N))) if N else ((), ()) ) ans = len({(min(a, b), max(a, b)) for a, b in zip(A, B)}) print(ans)
n = int(input()) (a, b) = zip(*(map(int, input().split()) for _ in range(N))) if N else ((), ()) ans = len({(min(a, b), max(a, b)) for (a, b) in zip(A, B)}) print(ans)
URLS = [ "url1" ] STATUSPAGE_API_KEY = "" STATUSPAGE_PAGE_ID = "" STATUSPAGE_METRICS = { "url": "metric_id" } STATUSPAGE_COMPONENTS = { "url": "component_id" } PING_WEBHOOKS = [] STATUS_WEBHOOKS = [] ESCALATION_IDS = [] POLL_TIME = 60 OUTAGE_CHANGE_AFTER = 10 DRY_MODE = False DEGRADED_PERFORMANCE_TARGET_PING = 500 TIMEOUT_PING = 30000
urls = ['url1'] statuspage_api_key = '' statuspage_page_id = '' statuspage_metrics = {'url': 'metric_id'} statuspage_components = {'url': 'component_id'} ping_webhooks = [] status_webhooks = [] escalation_ids = [] poll_time = 60 outage_change_after = 10 dry_mode = False degraded_performance_target_ping = 500 timeout_ping = 30000
{ 'application':{ 'type':'Application', 'name':'MulticolumnExample', 'backgrounds': [ { 'type':'Background', 'name':'bgMulticolumnExample', 'title':'Multicolumn Example PythonCard Application', 'size':( 620, 500 ), 'menubar': { 'type':'MenuBar', 'menus': [ { 'type':'Menu', 'name':'menuFile', 'label':'&File', 'items': [ { 'type':'MenuItem', 'name':'menuFileExit', 'label':'E&xit\tAlt+X', 'command':'exit' } ] } ] }, 'components': [ {'type':'Button', 'name':'demoButton', 'position':(510, 5), 'size':(85, 25), 'label':'Load Demo', }, {'type':'Button', 'name':'clearButton', 'position':(510, 30), 'size':(85, 25), 'label':'Clear', }, {'type':'Button', 'name':'loadButton', 'position':(510, 55), 'size':(85, 25), 'label':'Load CSV', }, {'type':'Button', 'name':'appendButton', 'position':(510, 80), 'size':(85, 25), 'label':'Append CSV', }, {'type':'Button', 'name':'swapButton', 'position':(510, 105), 'size':(85, 25), 'label':'Swap Lists', }, {'type':'Button', 'name':'prevButton', 'position':(510, 130), 'size':(85, 25), 'label':'Prev', }, {'type':'Button', 'name':'nextButton', 'position':(510, 155), 'size':(85, 25), 'label':'Next', }, {'type':'Button', 'name':'exitButton', 'position':(510, 180), 'size':(85, 25), 'label':'Exit', }, {'type':'MultiColumnList', 'name':'theList', 'position':(3, 3), #10, 305 'size':(500, 390), 'columnHeadings': ['Example List'], 'items':['Example 1','Example 2','Example 3'], }, {'type':'TextArea', 'name':'displayArea', 'position':(3, 398), 'size':(500, 40), 'font':{'family': 'monospace', 'size': 12}, }, {'type':'TextArea', 'name':'countArea', 'position':(507, 398), 'size':(85, 40), 'font':{'family': 'monospace', 'size': 12}, }, ] } ] } }
{'application': {'type': 'Application', 'name': 'MulticolumnExample', 'backgrounds': [{'type': 'Background', 'name': 'bgMulticolumnExample', 'title': 'Multicolumn Example PythonCard Application', 'size': (620, 500), 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'menuFile', 'label': '&File', 'items': [{'type': 'MenuItem', 'name': 'menuFileExit', 'label': 'E&xit\tAlt+X', 'command': 'exit'}]}]}, 'components': [{'type': 'Button', 'name': 'demoButton', 'position': (510, 5), 'size': (85, 25), 'label': 'Load Demo'}, {'type': 'Button', 'name': 'clearButton', 'position': (510, 30), 'size': (85, 25), 'label': 'Clear'}, {'type': 'Button', 'name': 'loadButton', 'position': (510, 55), 'size': (85, 25), 'label': 'Load CSV'}, {'type': 'Button', 'name': 'appendButton', 'position': (510, 80), 'size': (85, 25), 'label': 'Append CSV'}, {'type': 'Button', 'name': 'swapButton', 'position': (510, 105), 'size': (85, 25), 'label': 'Swap Lists'}, {'type': 'Button', 'name': 'prevButton', 'position': (510, 130), 'size': (85, 25), 'label': 'Prev'}, {'type': 'Button', 'name': 'nextButton', 'position': (510, 155), 'size': (85, 25), 'label': 'Next'}, {'type': 'Button', 'name': 'exitButton', 'position': (510, 180), 'size': (85, 25), 'label': 'Exit'}, {'type': 'MultiColumnList', 'name': 'theList', 'position': (3, 3), 'size': (500, 390), 'columnHeadings': ['Example List'], 'items': ['Example 1', 'Example 2', 'Example 3']}, {'type': 'TextArea', 'name': 'displayArea', 'position': (3, 398), 'size': (500, 40), 'font': {'family': 'monospace', 'size': 12}}, {'type': 'TextArea', 'name': 'countArea', 'position': (507, 398), 'size': (85, 40), 'font': {'family': 'monospace', 'size': 12}}]}]}}
#!/usr/bin/env python3 """ Models that maps to Cloudformation functions. """ def replace_fn(node): """Iteratively replace all Fn/Ref in the node""" if isinstance(node, list): return [replace_fn(item) for item in node] if isinstance(node, dict): return {name: replace_fn(value) for name, value in node.items()} if isinstance(node, (str, int, float)): return node if isinstance(node, Ref): return node.render() if hasattr(Fn, node.__class__.__name__): return node.render() raise ValueError(f"Invalid value specified in the code: {node}") class Ref: """Represents a ref function in Cloudformation.""" # This is our DSL, it's a very thin wrapper around dictionary. # pylint: disable=R0903 def __init__(self, target): """Creates a Ref node with a target.""" self.target = target def render(self): """Render the node as a dictionary.""" return {"Ref": self.target} class Base64: """Fn::Base64 function.""" # pylint: disable=R0903 def __init__(self, value): self.value = value def render(self): """Render the node with Fn::Base64.""" return {"Fn::Base64": replace_fn(self.value)} class Cidr: """Fn::Cidr function.""" # pylint: disable=R0903 def __init__(self, ipblock, count, cidr_bits): self.ipblock = ipblock self.count = count self.cidr_bits = cidr_bits def render(self): """Render the node with Fn::Cidr.""" return { "Fn::Cidr": [ replace_fn(self.ipblock), replace_fn(self.count), replace_fn(self.cidr_bits), ] } class And: """Fn::And function.""" # pylint: disable=R0903 def __init__(self, *args): self.conditions = list(args) def render(self): """Render the node with Fn::And.""" return {"Fn::And": replace_fn(self.conditions)} class Equals: """Fn::Equals function.""" # pylint: disable=R0903 def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def render(self): """Render the node with Fn::Equals.""" return {"Fn::Equals": [replace_fn(self.lhs), replace_fn(self.rhs)]} class If: """Fn::If function.""" # pylint: disable=R0903 def __init__(self, condition, true_value, false_value): self.condition = condition self.true_value = true_value self.false_value = false_value def render(self): """Render the node with Fn::If.""" return { "Fn::If": [ replace_fn(self.condition), replace_fn(self.true_value), replace_fn(self.false_value), ] } class Not: """Fn::Not function.""" # pylint: disable=R0903 def __init__(self, condition): self.condition = condition def render(self): """Render the node with Fn::Not.""" return {"Fn::Not": [replace_fn(self.condition)]} class Or: """Fn::Or function.""" # pylint: disable=R0903 def __init__(self, *args): self.conditions = list(args) def render(self): """Render the node with Fn::Or.""" return {"Fn::Or": replace_fn(self.conditions)} class FindInMap: """Fn::FindInMap function.""" # pylint: disable=R0903 def __init__(self, map_name, l1key, l2key): self.map_name = map_name self.l1key = l1key self.l2key = l2key def render(self): """Render the node with Fn::FindInMap.""" return { "Fn::FindInMap": [ replace_fn(self.map_name), replace_fn(self.l1key), replace_fn(self.l2key), ] } class GetAtt: """Fn::GetAtt function.""" # pylint: disable=R0903 def __init__(self, logical_name, attr): self.logical_name = logical_name self.attr = attr def render(self): """Render the node with Fn::GetAtt.""" return {"Fn::GetAtt": [replace_fn(self.logical_name), replace_fn(self.attr)]} class GetAZs: """Fn::GetAZs function.""" # pylint: disable=R0903 def __init__(self, region): self.region = region def render(self): """Render the node with Fn::GetAZs.""" return {"Fn::GetAZs": replace_fn(self.region)} class ImportValue: """Fn::ImportValue function.""" # pylint: disable=R0903 def __init__(self, export): self.export = export def render(self): """Render the node with Fn::ImportValue.""" return {"Fn::ImportValue": replace_fn(self.export)} class Join: """Fn::Join function.""" # pylint: disable=R0903 def __init__(self, delimiter, elements): self.delimiter = delimiter self.elements = elements def render(self): """Render the node with Fn::Join.""" return {"Fn::Join": [replace_fn(self.delimiter), replace_fn(self.elements)]} class Select: """Fn::Select function.""" # pylint: disable=R0903 def __init__(self, index, elements): self.index = index self.elements = elements def render(self): """Render the node with Fn::Select.""" return {"Fn::Select": [replace_fn(self.index), replace_fn(self.elements)]} class Split: """Fn::Split function.""" # pylint: disable=R0903 def __init__(self, delimiter, target): self.delimiter = delimiter self.target = target def render(self): """Render the node with Fn::Split.""" return {"Fn::Split": [replace_fn(self.delimiter), replace_fn(self.target)]} class Sub: """Fn::Sub function.""" # pylint: disable=R0903 def __init__(self, target, mapping=None): if not isinstance(target, str): raise ValueError( f"The first argument of Fn::Sub must be string: `{target}`" ) if mapping is None: self.mapping = {} self.target = target self.mapping = mapping def render(self): """Render the node with Fn::Sub.""" if self.mapping: return {"Fn::Sub": [replace_fn(self.target), replace_fn(self.mapping)]} return {"Fn::Sub": replace_fn(self.target)} class Transform: """Fn::Transform function.""" # pylint: disable=R0903 def __init__(self, construct): is_dict = isinstance(construct, dict) match_keys = set(construct.keys()) == {"Name", "Parameters"} if not is_dict or not match_keys: raise ValueError("Invalid Transform construct") self.construct = construct def render(self): """Render the node with Fn::Transform.""" return { "Fn::Transform": { "Name": replace_fn(self.construct["Name"]), "Parameters": replace_fn(self.construct["Parameters"]), } } class Fn: """ This is a container for all functions. Rationale is instead of having to import all the functions, we just import Fn and use any function as Fn.FuncName """ # pylint: disable=R0903 Base64 = Base64 Cidr = Cidr And = And Equals = Equals If = If Not = Not Or = Or FindInMap = FindInMap GetAtt = GetAtt GetAZs = GetAZs ImportValue = ImportValue Join = Join Select = Select Split = Split Sub = Sub Transform = Transform
""" Models that maps to Cloudformation functions. """ def replace_fn(node): """Iteratively replace all Fn/Ref in the node""" if isinstance(node, list): return [replace_fn(item) for item in node] if isinstance(node, dict): return {name: replace_fn(value) for (name, value) in node.items()} if isinstance(node, (str, int, float)): return node if isinstance(node, Ref): return node.render() if hasattr(Fn, node.__class__.__name__): return node.render() raise value_error(f'Invalid value specified in the code: {node}') class Ref: """Represents a ref function in Cloudformation.""" def __init__(self, target): """Creates a Ref node with a target.""" self.target = target def render(self): """Render the node as a dictionary.""" return {'Ref': self.target} class Base64: """Fn::Base64 function.""" def __init__(self, value): self.value = value def render(self): """Render the node with Fn::Base64.""" return {'Fn::Base64': replace_fn(self.value)} class Cidr: """Fn::Cidr function.""" def __init__(self, ipblock, count, cidr_bits): self.ipblock = ipblock self.count = count self.cidr_bits = cidr_bits def render(self): """Render the node with Fn::Cidr.""" return {'Fn::Cidr': [replace_fn(self.ipblock), replace_fn(self.count), replace_fn(self.cidr_bits)]} class And: """Fn::And function.""" def __init__(self, *args): self.conditions = list(args) def render(self): """Render the node with Fn::And.""" return {'Fn::And': replace_fn(self.conditions)} class Equals: """Fn::Equals function.""" def __init__(self, lhs, rhs): self.lhs = lhs self.rhs = rhs def render(self): """Render the node with Fn::Equals.""" return {'Fn::Equals': [replace_fn(self.lhs), replace_fn(self.rhs)]} class If: """Fn::If function.""" def __init__(self, condition, true_value, false_value): self.condition = condition self.true_value = true_value self.false_value = false_value def render(self): """Render the node with Fn::If.""" return {'Fn::If': [replace_fn(self.condition), replace_fn(self.true_value), replace_fn(self.false_value)]} class Not: """Fn::Not function.""" def __init__(self, condition): self.condition = condition def render(self): """Render the node with Fn::Not.""" return {'Fn::Not': [replace_fn(self.condition)]} class Or: """Fn::Or function.""" def __init__(self, *args): self.conditions = list(args) def render(self): """Render the node with Fn::Or.""" return {'Fn::Or': replace_fn(self.conditions)} class Findinmap: """Fn::FindInMap function.""" def __init__(self, map_name, l1key, l2key): self.map_name = map_name self.l1key = l1key self.l2key = l2key def render(self): """Render the node with Fn::FindInMap.""" return {'Fn::FindInMap': [replace_fn(self.map_name), replace_fn(self.l1key), replace_fn(self.l2key)]} class Getatt: """Fn::GetAtt function.""" def __init__(self, logical_name, attr): self.logical_name = logical_name self.attr = attr def render(self): """Render the node with Fn::GetAtt.""" return {'Fn::GetAtt': [replace_fn(self.logical_name), replace_fn(self.attr)]} class Getazs: """Fn::GetAZs function.""" def __init__(self, region): self.region = region def render(self): """Render the node with Fn::GetAZs.""" return {'Fn::GetAZs': replace_fn(self.region)} class Importvalue: """Fn::ImportValue function.""" def __init__(self, export): self.export = export def render(self): """Render the node with Fn::ImportValue.""" return {'Fn::ImportValue': replace_fn(self.export)} class Join: """Fn::Join function.""" def __init__(self, delimiter, elements): self.delimiter = delimiter self.elements = elements def render(self): """Render the node with Fn::Join.""" return {'Fn::Join': [replace_fn(self.delimiter), replace_fn(self.elements)]} class Select: """Fn::Select function.""" def __init__(self, index, elements): self.index = index self.elements = elements def render(self): """Render the node with Fn::Select.""" return {'Fn::Select': [replace_fn(self.index), replace_fn(self.elements)]} class Split: """Fn::Split function.""" def __init__(self, delimiter, target): self.delimiter = delimiter self.target = target def render(self): """Render the node with Fn::Split.""" return {'Fn::Split': [replace_fn(self.delimiter), replace_fn(self.target)]} class Sub: """Fn::Sub function.""" def __init__(self, target, mapping=None): if not isinstance(target, str): raise value_error(f'The first argument of Fn::Sub must be string: `{target}`') if mapping is None: self.mapping = {} self.target = target self.mapping = mapping def render(self): """Render the node with Fn::Sub.""" if self.mapping: return {'Fn::Sub': [replace_fn(self.target), replace_fn(self.mapping)]} return {'Fn::Sub': replace_fn(self.target)} class Transform: """Fn::Transform function.""" def __init__(self, construct): is_dict = isinstance(construct, dict) match_keys = set(construct.keys()) == {'Name', 'Parameters'} if not is_dict or not match_keys: raise value_error('Invalid Transform construct') self.construct = construct def render(self): """Render the node with Fn::Transform.""" return {'Fn::Transform': {'Name': replace_fn(self.construct['Name']), 'Parameters': replace_fn(self.construct['Parameters'])}} class Fn: """ This is a container for all functions. Rationale is instead of having to import all the functions, we just import Fn and use any function as Fn.FuncName """ base64 = Base64 cidr = Cidr and = And equals = Equals if = If not = Not or = Or find_in_map = FindInMap get_att = GetAtt get_a_zs = GetAZs import_value = ImportValue join = Join select = Select split = Split sub = Sub transform = Transform
"""Rule and corresponding provider that joins a label pointing to a TreeArtifact with a path nested within that directory """ load("//lib:utils.bzl", _to_label = "to_label") DirectoryPathInfo = provider( doc = "Joins a label pointing to a TreeArtifact with a path nested within that directory.", fields = { "directory": "a TreeArtifact (ctx.actions.declare_directory)", "path": "path relative to the directory", }, ) def _directory_path(ctx): if not ctx.file.directory.is_directory: fail("directory attribute must be created with Bazel declare_directory (TreeArtifact)") return [DirectoryPathInfo(path = ctx.attr.path, directory = ctx.file.directory)] directory_path = rule( doc = """Provide DirectoryPathInfo to reference some path within a directory. Otherwise there is no way to give a Bazel label for it.""", implementation = _directory_path, attrs = { "directory": attr.label( doc = "a TreeArtifact (ctx.actions.declare_directory)", mandatory = True, allow_single_file = True, ), "path": attr.string( doc = "path relative to the directory", mandatory = True, ), }, provides = [DirectoryPathInfo], ) def make_directory_path(name, directory, path, **kwargs): """Helper function to generate a directory_path target and return its label. Args: name: unique name for the generated `directory_path` target directory: `directory` attribute passed to generated `directory_path` target path: `path` attribute passed to generated `directory_path` target **kwargs: parameters to pass to generated `output_files` target Returns: The label `name` """ directory_path( name = name, directory = directory, path = path, **kwargs ) return _to_label(name) def make_directory_paths(name, dict, **kwargs): """Helper function to convert a dict of directory to path mappings to directory_path targets and labels. For example, ``` make_directory_paths("my_name", { "//directory/artifact:target_1": "file/path", "//directory/artifact:target_2": ["file/path1", "file/path2"], }) ``` generates the targets, ``` directory_path( name = "my_name_0", directory = "//directory/artifact:target_1", path = "file/path" ) directory_path( name = "my_name_1", directory = "//directory/artifact:target_2", path = "file/path1" ) directory_path( name = "my_name_2", directory = "//directory/artifact:target_2", path = "file/path2" ) ``` and the list of targets is returned, ``` [ "my_name_0", "my_name_1", "my_name_2", ] ``` Args: name: The target name to use for the generated targets & labels. The names are generated as zero-indexed `name + "_" + i` dict: The dictionary of directory keys to path or path list values. **kwargs: additional parameters to pass to each generated target Returns: The label of the generated `directory_path` targets named `name + "_" + i` """ labels = [] pairs = [] for directory, val in dict.items(): if type(val) == "list": for path in val: pairs.append((directory, path)) elif type(val) == "string": pairs.append((directory, val)) else: fail("Value must be a list or string") for i, pair in enumerate(pairs): directory, path = pair labels.append(make_directory_path( "%s_%d" % (name, i), directory, path, **kwargs )) return labels
"""Rule and corresponding provider that joins a label pointing to a TreeArtifact with a path nested within that directory """ load('//lib:utils.bzl', _to_label='to_label') directory_path_info = provider(doc='Joins a label pointing to a TreeArtifact with a path nested within that directory.', fields={'directory': 'a TreeArtifact (ctx.actions.declare_directory)', 'path': 'path relative to the directory'}) def _directory_path(ctx): if not ctx.file.directory.is_directory: fail('directory attribute must be created with Bazel declare_directory (TreeArtifact)') return [directory_path_info(path=ctx.attr.path, directory=ctx.file.directory)] directory_path = rule(doc='Provide DirectoryPathInfo to reference some path within a directory.\n\nOtherwise there is no way to give a Bazel label for it.', implementation=_directory_path, attrs={'directory': attr.label(doc='a TreeArtifact (ctx.actions.declare_directory)', mandatory=True, allow_single_file=True), 'path': attr.string(doc='path relative to the directory', mandatory=True)}, provides=[DirectoryPathInfo]) def make_directory_path(name, directory, path, **kwargs): """Helper function to generate a directory_path target and return its label. Args: name: unique name for the generated `directory_path` target directory: `directory` attribute passed to generated `directory_path` target path: `path` attribute passed to generated `directory_path` target **kwargs: parameters to pass to generated `output_files` target Returns: The label `name` """ directory_path(name=name, directory=directory, path=path, **kwargs) return _to_label(name) def make_directory_paths(name, dict, **kwargs): """Helper function to convert a dict of directory to path mappings to directory_path targets and labels. For example, ``` make_directory_paths("my_name", { "//directory/artifact:target_1": "file/path", "//directory/artifact:target_2": ["file/path1", "file/path2"], }) ``` generates the targets, ``` directory_path( name = "my_name_0", directory = "//directory/artifact:target_1", path = "file/path" ) directory_path( name = "my_name_1", directory = "//directory/artifact:target_2", path = "file/path1" ) directory_path( name = "my_name_2", directory = "//directory/artifact:target_2", path = "file/path2" ) ``` and the list of targets is returned, ``` [ "my_name_0", "my_name_1", "my_name_2", ] ``` Args: name: The target name to use for the generated targets & labels. The names are generated as zero-indexed `name + "_" + i` dict: The dictionary of directory keys to path or path list values. **kwargs: additional parameters to pass to each generated target Returns: The label of the generated `directory_path` targets named `name + "_" + i` """ labels = [] pairs = [] for (directory, val) in dict.items(): if type(val) == 'list': for path in val: pairs.append((directory, path)) elif type(val) == 'string': pairs.append((directory, val)) else: fail('Value must be a list or string') for (i, pair) in enumerate(pairs): (directory, path) = pair labels.append(make_directory_path('%s_%d' % (name, i), directory, path, **kwargs)) return labels
# Find algorithm that sorts the stack of size n in O(log(n)) time. It is allowed to use operations # provided only by the stack interface: push(), pop(), top(), isEmpty() and additional stacks. class Stack: def __init__(self): self.stack = [] def push(self, value): self.stack.append(value) def pop(self): return self.stack.pop() def top(self): return self.stack[-1] def isEmpty(self): if self.stack == []: return True else: return False def sort_stack(stack): temporary_stack = Stack() while not stack.isEmpty(): value = stack.pop() while not temporary_stack.isEmpty() and temporary_stack.top() > value: stack.push(temporary_stack.pop()) temporary_stack.push(value) while not temporary_stack.isEmpty(): stack.push(temporary_stack.pop()) result = [] while not stack.isEmpty(): result.append(stack.pop()) return result def create_stack(T): stack = Stack() for i in range(len(T)): stack.push(T[i]) return stack T = [7, 10, 7, 87, 5, 53, 10, 15, 49, 1, 73, 14, 8, 68, 2, 32, 23, 41, 35, 98, 26] stack = create_stack(T) print(sort_stack(stack))
class Stack: def __init__(self): self.stack = [] def push(self, value): self.stack.append(value) def pop(self): return self.stack.pop() def top(self): return self.stack[-1] def is_empty(self): if self.stack == []: return True else: return False def sort_stack(stack): temporary_stack = stack() while not stack.isEmpty(): value = stack.pop() while not temporary_stack.isEmpty() and temporary_stack.top() > value: stack.push(temporary_stack.pop()) temporary_stack.push(value) while not temporary_stack.isEmpty(): stack.push(temporary_stack.pop()) result = [] while not stack.isEmpty(): result.append(stack.pop()) return result def create_stack(T): stack = stack() for i in range(len(T)): stack.push(T[i]) return stack t = [7, 10, 7, 87, 5, 53, 10, 15, 49, 1, 73, 14, 8, 68, 2, 32, 23, 41, 35, 98, 26] stack = create_stack(T) print(sort_stack(stack))
N = int(input()) MAX, VAR, FIX = range(3) # latest=9 r=3 b=4 # max_variable_fixed_values = [ # 3 4 5 # 2 3 3 # 2 1 5 # 2 4 2 # 2 2 4 # 2 5 1 # ] def try_to_beat(latest_score, r, b, max_var_fixed): our_score = 0 while b > 0: if not r: return -1 best_c_max_b, best_max_b = 0, 0 for max_b, variable, fixed in max_var_fixed: this_c_max = min( max_b, b, (latest_score - fixed - 1)//variable ) if this_c_max > best_max_b: # and this_c_max > 0 best_c_max_b, best_max_b = ([max_b, variable, fixed], this_c_max) if not best_max_b: return -1 max_var_fixed.remove(best_c_max_b) b -= best_max_b r -= 1 our_score = max( our_score, best_c_max_b[FIX] + best_max_b*best_c_max_b[VAR] ) return our_score def initial_total_time(b, max_var_fixed): initial_best_time = 0 for max_b, variable, fixed in max_var_fixed: passed_bits = min(b, max_b) b -= passed_bits initial_best_time = max( initial_best_time, fixed + variable*passed_bits ) if not b: return initial_best_time for case_id in range(1, N + 1): r, b, c = map(int, input().split()) max_variable_fixed_values = sorted([ [*map(int, input().split())] for _ in range(c) ], key=lambda item: item[MAX], reverse=True) total_time = initial_total_time(b, max_variable_fixed_values) print(total_time) while True: new_attempt = try_to_beat(total_time, r, b, max_variable_fixed_values.copy()) print(new_attempt) if new_attempt == -1: break else: total_time = new_attempt print('Case #{}: {}'.format(case_id, total_time))
n = int(input()) (max, var, fix) = range(3) def try_to_beat(latest_score, r, b, max_var_fixed): our_score = 0 while b > 0: if not r: return -1 (best_c_max_b, best_max_b) = (0, 0) for (max_b, variable, fixed) in max_var_fixed: this_c_max = min(max_b, b, (latest_score - fixed - 1) // variable) if this_c_max > best_max_b: (best_c_max_b, best_max_b) = ([max_b, variable, fixed], this_c_max) if not best_max_b: return -1 max_var_fixed.remove(best_c_max_b) b -= best_max_b r -= 1 our_score = max(our_score, best_c_max_b[FIX] + best_max_b * best_c_max_b[VAR]) return our_score def initial_total_time(b, max_var_fixed): initial_best_time = 0 for (max_b, variable, fixed) in max_var_fixed: passed_bits = min(b, max_b) b -= passed_bits initial_best_time = max(initial_best_time, fixed + variable * passed_bits) if not b: return initial_best_time for case_id in range(1, N + 1): (r, b, c) = map(int, input().split()) max_variable_fixed_values = sorted([[*map(int, input().split())] for _ in range(c)], key=lambda item: item[MAX], reverse=True) total_time = initial_total_time(b, max_variable_fixed_values) print(total_time) while True: new_attempt = try_to_beat(total_time, r, b, max_variable_fixed_values.copy()) print(new_attempt) if new_attempt == -1: break else: total_time = new_attempt print('Case #{}: {}'.format(case_id, total_time))
# # PySNMP MIB module CTRON-CHASSIS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-CHASSIS-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:44:24 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint") ctronChassis, = mibBuilder.importSymbols("CTRON-MIB-NAMES", "ctronChassis") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, Integer32, Counter32, Counter64, NotificationType, ObjectIdentity, iso, MibIdentifier, ModuleIdentity, Unsigned32, Bits, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "Integer32", "Counter32", "Counter64", "NotificationType", "ObjectIdentity", "iso", "MibIdentifier", "ModuleIdentity", "Unsigned32", "Bits", "Gauge32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ctChas = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1)) ctEnviron = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2)) ctFanModule = MibIdentifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3)) ctChasFNB = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("absent", 1), ("present", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: ctChasFNB.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFNB.setDescription('Denotes the presence or absence of the FNB.') ctChasAlarmEna = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2), ("notSupported", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: ctChasAlarmEna.setStatus('mandatory') if mibBuilder.loadTexts: ctChasAlarmEna.setDescription('Allow an audible alarm to be either enabled or dis- abled. Setting this object to disable(1) will prevent an audible alarm from being heard and will also stop the sound from a current audible alarm. Setting this object to enable(2) will allow an audible alarm to be heard and will also enable the sound from a current audible alarm, if it has previously been disabled. This object will read with the current setting.') chassisAlarmState = MibScalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("chassisNoFaultCondition", 1), ("chassisFaultCondition", 2), ("notSupported", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisAlarmState.setStatus('mandatory') if mibBuilder.loadTexts: chassisAlarmState.setDescription('Denotes the current condition of the power supply fault detection circuit. This object will read with the value of chassisNoFaultCondition(1) when the chassis is currently operating with no power faults detected. This object will read with the value of chassisFaultCondition(2) when the chassis is currently in a power fault condition.') ctChasPowerTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1), ) if mibBuilder.loadTexts: ctChasPowerTable.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerTable.setDescription('A list of power supply entries.') ctChasPowerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1), ).setIndexNames((0, "CTRON-CHASSIS-MIB", "ctChasPowerSupplyNum")) if mibBuilder.loadTexts: ctChasPowerEntry.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerEntry.setDescription('An entry in the powerTable providing objects for a power supply.') ctChasPowerSupplyNum = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ctChasPowerSupplyNum.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyNum.setDescription('Denotes the power supply.') ctChasPowerSupplyState = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("infoNotAvailable", 1), ("notInstalled", 2), ("installedAndOperating", 3), ("installedAndNotOperating", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: ctChasPowerSupplyState.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyState.setDescription("Denotes the power supply's state.") ctChasPowerSupplyType = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("ac-dc", 1), ("dc-dc", 2), ("notSupported", 3), ("highOutput", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: ctChasPowerSupplyType.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyType.setDescription('Denotes the power supply type.') ctChasPowerSupplyRedundancy = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("redundant", 1), ("notRedundant", 2), ("notSupported", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: ctChasPowerSupplyRedundancy.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyRedundancy.setDescription('Denotes whether or not the power supply is redundant.') ctChasFanModuleTable = MibTable((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1), ) if mibBuilder.loadTexts: ctChasFanModuleTable.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleTable.setDescription('A list of fan module entries.') ctChasFanModuleEntry = MibTableRow((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1), ).setIndexNames((0, "CTRON-CHASSIS-MIB", "ctChasFanModuleNum")) if mibBuilder.loadTexts: ctChasFanModuleEntry.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleEntry.setDescription('An entry in the fan module Table providing objects for a fan module.') ctChasFanModuleNum = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: ctChasFanModuleNum.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleNum.setDescription('Denotes the Fan module that may have failed.') ctChasFanModuleState = MibTableColumn((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("infoNotAvailable", 1), ("notInstalled", 2), ("installedAndOperating", 3), ("installedAndNotOperating", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: ctChasFanModuleState.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleState.setDescription('Denotes the fan modules state.') mibBuilder.exportSymbols("CTRON-CHASSIS-MIB", ctEnviron=ctEnviron, ctChasPowerSupplyNum=ctChasPowerSupplyNum, ctChasFanModuleState=ctChasFanModuleState, ctChasPowerEntry=ctChasPowerEntry, ctChasPowerSupplyState=ctChasPowerSupplyState, chassisAlarmState=chassisAlarmState, ctChasPowerSupplyType=ctChasPowerSupplyType, ctChas=ctChas, ctChasFanModuleEntry=ctChasFanModuleEntry, ctChasFanModuleTable=ctChasFanModuleTable, ctChasFNB=ctChasFNB, ctChasPowerTable=ctChasPowerTable, ctChasPowerSupplyRedundancy=ctChasPowerSupplyRedundancy, ctChasAlarmEna=ctChasAlarmEna, ctChasFanModuleNum=ctChasFanModuleNum, ctFanModule=ctFanModule)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint') (ctron_chassis,) = mibBuilder.importSymbols('CTRON-MIB-NAMES', 'ctronChassis') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, time_ticks, integer32, counter32, counter64, notification_type, object_identity, iso, mib_identifier, module_identity, unsigned32, bits, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'TimeTicks', 'Integer32', 'Counter32', 'Counter64', 'NotificationType', 'ObjectIdentity', 'iso', 'MibIdentifier', 'ModuleIdentity', 'Unsigned32', 'Bits', 'Gauge32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') ct_chas = mib_identifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1)) ct_environ = mib_identifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2)) ct_fan_module = mib_identifier((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3)) ct_chas_fnb = mib_scalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('absent', 1), ('present', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: ctChasFNB.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFNB.setDescription('Denotes the presence or absence of the FNB.') ct_chas_alarm_ena = mib_scalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('disable', 1), ('enable', 2), ('notSupported', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: ctChasAlarmEna.setStatus('mandatory') if mibBuilder.loadTexts: ctChasAlarmEna.setDescription('Allow an audible alarm to be either enabled or dis- abled. Setting this object to disable(1) will prevent an audible alarm from being heard and will also stop the sound from a current audible alarm. Setting this object to enable(2) will allow an audible alarm to be heard and will also enable the sound from a current audible alarm, if it has previously been disabled. This object will read with the current setting.') chassis_alarm_state = mib_scalar((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('chassisNoFaultCondition', 1), ('chassisFaultCondition', 2), ('notSupported', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisAlarmState.setStatus('mandatory') if mibBuilder.loadTexts: chassisAlarmState.setDescription('Denotes the current condition of the power supply fault detection circuit. This object will read with the value of chassisNoFaultCondition(1) when the chassis is currently operating with no power faults detected. This object will read with the value of chassisFaultCondition(2) when the chassis is currently in a power fault condition.') ct_chas_power_table = mib_table((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1)) if mibBuilder.loadTexts: ctChasPowerTable.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerTable.setDescription('A list of power supply entries.') ct_chas_power_entry = mib_table_row((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1)).setIndexNames((0, 'CTRON-CHASSIS-MIB', 'ctChasPowerSupplyNum')) if mibBuilder.loadTexts: ctChasPowerEntry.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerEntry.setDescription('An entry in the powerTable providing objects for a power supply.') ct_chas_power_supply_num = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: ctChasPowerSupplyNum.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyNum.setDescription('Denotes the power supply.') ct_chas_power_supply_state = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('infoNotAvailable', 1), ('notInstalled', 2), ('installedAndOperating', 3), ('installedAndNotOperating', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: ctChasPowerSupplyState.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyState.setDescription("Denotes the power supply's state.") ct_chas_power_supply_type = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('ac-dc', 1), ('dc-dc', 2), ('notSupported', 3), ('highOutput', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: ctChasPowerSupplyType.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyType.setDescription('Denotes the power supply type.') ct_chas_power_supply_redundancy = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 2, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('redundant', 1), ('notRedundant', 2), ('notSupported', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: ctChasPowerSupplyRedundancy.setStatus('mandatory') if mibBuilder.loadTexts: ctChasPowerSupplyRedundancy.setDescription('Denotes whether or not the power supply is redundant.') ct_chas_fan_module_table = mib_table((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1)) if mibBuilder.loadTexts: ctChasFanModuleTable.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleTable.setDescription('A list of fan module entries.') ct_chas_fan_module_entry = mib_table_row((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1)).setIndexNames((0, 'CTRON-CHASSIS-MIB', 'ctChasFanModuleNum')) if mibBuilder.loadTexts: ctChasFanModuleEntry.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleEntry.setDescription('An entry in the fan module Table providing objects for a fan module.') ct_chas_fan_module_num = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: ctChasFanModuleNum.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleNum.setDescription('Denotes the Fan module that may have failed.') ct_chas_fan_module_state = mib_table_column((1, 3, 6, 1, 4, 1, 52, 4, 3, 1, 3, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('infoNotAvailable', 1), ('notInstalled', 2), ('installedAndOperating', 3), ('installedAndNotOperating', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: ctChasFanModuleState.setStatus('mandatory') if mibBuilder.loadTexts: ctChasFanModuleState.setDescription('Denotes the fan modules state.') mibBuilder.exportSymbols('CTRON-CHASSIS-MIB', ctEnviron=ctEnviron, ctChasPowerSupplyNum=ctChasPowerSupplyNum, ctChasFanModuleState=ctChasFanModuleState, ctChasPowerEntry=ctChasPowerEntry, ctChasPowerSupplyState=ctChasPowerSupplyState, chassisAlarmState=chassisAlarmState, ctChasPowerSupplyType=ctChasPowerSupplyType, ctChas=ctChas, ctChasFanModuleEntry=ctChasFanModuleEntry, ctChasFanModuleTable=ctChasFanModuleTable, ctChasFNB=ctChasFNB, ctChasPowerTable=ctChasPowerTable, ctChasPowerSupplyRedundancy=ctChasPowerSupplyRedundancy, ctChasAlarmEna=ctChasAlarmEna, ctChasFanModuleNum=ctChasFanModuleNum, ctFanModule=ctFanModule)
class BaseDataset: def __init__(self, data=list()): self.data = data def __getitem__(self, idx): return self.data[idx] def __len__(self): return len(self.data)
class Basedataset: def __init__(self, data=list()): self.data = data def __getitem__(self, idx): return self.data[idx] def __len__(self): return len(self.data)
"""Calculators for different values. In order to approximate the emissions for a single kWh of produced energy, per power source we look at the following 2016 data sets. * Detailed EIA-923 emissions survey data (https://www.eia.gov/electricity/data/state/emission_annual.xls) * Net Generation by State by Type of Producer by Energy Source (EIA-906, EIA-920, and EIA-923) (https://www.eia.gov/electricity/data/state/annual_generation_state.xls) The NY Numbers for 2016 on power generation are (power in MWh) 2016 NY Total Electric Power Industry Total 134,417,107 2016 NY Total Electric Power Industry Coal 1,770,238 2016 NY Total Electric Power Industry Pumped Storage -470,932 2016 NY Total Electric Power Industry Hydroelectric Conventional 26,888,234 2016 NY Total Electric Power Industry Natural Gas 56,793,336 2016 NY Total Electric Power Industry Nuclear 41,570,990 2016 NY Total Electric Power Industry Other Gases 0 2016 NY Total Electric Power Industry Other 898,989 2016 NY Total Electric Power Industry Petroleum 642,952 2016 NY Total Electric Power Industry Solar Thermal and Photovoltaic 139,611 2016 NY Total Electric Power Industry Other Biomass 1,604,650 2016 NY Total Electric Power Industry Wind 3,940,180 2016 NY Total Electric Power Industry Wood and Wood Derived Fuels 638,859 The NY Numbers on Emissions are (metric tons of CO2, SO2, NOx) 2016 NY Total Electric Power Industry All Sources 31,295,191 18,372 32,161 2016 NY Total Electric Power Industry Coal 2,145,561 10,744 2,635 2016 NY Total Electric Power Industry Natural Gas 26,865,277 122 14,538 2016 NY Total Electric Power Industry Other Biomass 0 1 8,966 2016 NY Total Electric Power Industry Other 1,660,517 960 3,991 2016 NY Total Electric Power Industry Petroleum 623,836 1,688 930 2016 NY Total Electric Power Industry Wood and Wood Derived Fuels 0 4,857 1,101 Duel Fuel systems are interesting, they are designed to burn either Natural Gas, or Petroleum when access to NG is limited by price or capacity. (Under extreme cold conditions NG supply is prioritized for heating) We then make the following simplifying assumptions (given access to the data): * All natural gas generation is the same from emissions perspective * The duel fuel systems burned 30% of the total NG in the state, and all of the Petroleum. Based on eyeballing the Duel Fuel systems, they tend to be running slightly less than straight NG systems. * The mix of NG / Oil burned in duel fuel plants is constant throughout the year. This is clearly not true, but there is no better time resolution information available. * All other fossil fuels means Coal. All Coal is equivalent from emissions perspective. """ # PWR in MWh # CO2 in Metric Tons # # TODO(sdague): add in FUEL_2016 = { "Petroleum": { "Power": 642952, "CO2": 623836 }, "Natural Gas": { "Power": 56793336, "CO2": 26865277 }, "Other Fossil Fuels": { "Power": 1770238, "CO2": 2145561 } } # assume Dual Fuel systems consume 30% of state NG. That's probably low. FUEL_2016["Dual Fuel"] = { "Power": (FUEL_2016["Petroleum"]["Power"] + (FUEL_2016["Natural Gas"]["Power"] * .3)), "CO2": (FUEL_2016["Petroleum"]["CO2"] + (FUEL_2016["Natural Gas"]["CO2"] * .3)), } # Calculate CO2 per kWh usage def co2_for_fuel(fuel): "Returns metric tons per / MWh, or kg / kWh" if fuel in FUEL_2016: hpow = FUEL_2016[fuel]["Power"] hco2 = FUEL_2016[fuel]["CO2"] co2per = float(hco2) / float(hpow) return co2per else: return 0.0 def co2_rollup(rows): total_kW = 0 total_co2 = 0 for row in rows: fuel_name = row[2] kW = int(float(row[3])) total_kW += kW total_co2 += kW * co2_for_fuel(fuel_name) co2_per_kW = total_co2 / total_kW return co2_per_kW
"""Calculators for different values. In order to approximate the emissions for a single kWh of produced energy, per power source we look at the following 2016 data sets. * Detailed EIA-923 emissions survey data (https://www.eia.gov/electricity/data/state/emission_annual.xls) * Net Generation by State by Type of Producer by Energy Source (EIA-906, EIA-920, and EIA-923) (https://www.eia.gov/electricity/data/state/annual_generation_state.xls) The NY Numbers for 2016 on power generation are (power in MWh) 2016 NY Total Electric Power Industry Total 134,417,107 2016 NY Total Electric Power Industry Coal 1,770,238 2016 NY Total Electric Power Industry Pumped Storage -470,932 2016 NY Total Electric Power Industry Hydroelectric Conventional 26,888,234 2016 NY Total Electric Power Industry Natural Gas 56,793,336 2016 NY Total Electric Power Industry Nuclear 41,570,990 2016 NY Total Electric Power Industry Other Gases 0 2016 NY Total Electric Power Industry Other 898,989 2016 NY Total Electric Power Industry Petroleum 642,952 2016 NY Total Electric Power Industry Solar Thermal and Photovoltaic 139,611 2016 NY Total Electric Power Industry Other Biomass 1,604,650 2016 NY Total Electric Power Industry Wind 3,940,180 2016 NY Total Electric Power Industry Wood and Wood Derived Fuels 638,859 The NY Numbers on Emissions are (metric tons of CO2, SO2, NOx) 2016 NY Total Electric Power Industry All Sources 31,295,191 18,372 32,161 2016 NY Total Electric Power Industry Coal 2,145,561 10,744 2,635 2016 NY Total Electric Power Industry Natural Gas 26,865,277 122 14,538 2016 NY Total Electric Power Industry Other Biomass 0 1 8,966 2016 NY Total Electric Power Industry Other 1,660,517 960 3,991 2016 NY Total Electric Power Industry Petroleum 623,836 1,688 930 2016 NY Total Electric Power Industry Wood and Wood Derived Fuels 0 4,857 1,101 Duel Fuel systems are interesting, they are designed to burn either Natural Gas, or Petroleum when access to NG is limited by price or capacity. (Under extreme cold conditions NG supply is prioritized for heating) We then make the following simplifying assumptions (given access to the data): * All natural gas generation is the same from emissions perspective * The duel fuel systems burned 30% of the total NG in the state, and all of the Petroleum. Based on eyeballing the Duel Fuel systems, they tend to be running slightly less than straight NG systems. * The mix of NG / Oil burned in duel fuel plants is constant throughout the year. This is clearly not true, but there is no better time resolution information available. * All other fossil fuels means Coal. All Coal is equivalent from emissions perspective. """ fuel_2016 = {'Petroleum': {'Power': 642952, 'CO2': 623836}, 'Natural Gas': {'Power': 56793336, 'CO2': 26865277}, 'Other Fossil Fuels': {'Power': 1770238, 'CO2': 2145561}} FUEL_2016['Dual Fuel'] = {'Power': FUEL_2016['Petroleum']['Power'] + FUEL_2016['Natural Gas']['Power'] * 0.3, 'CO2': FUEL_2016['Petroleum']['CO2'] + FUEL_2016['Natural Gas']['CO2'] * 0.3} def co2_for_fuel(fuel): """Returns metric tons per / MWh, or kg / kWh""" if fuel in FUEL_2016: hpow = FUEL_2016[fuel]['Power'] hco2 = FUEL_2016[fuel]['CO2'] co2per = float(hco2) / float(hpow) return co2per else: return 0.0 def co2_rollup(rows): total_k_w = 0 total_co2 = 0 for row in rows: fuel_name = row[2] k_w = int(float(row[3])) total_k_w += kW total_co2 += kW * co2_for_fuel(fuel_name) co2_per_k_w = total_co2 / total_kW return co2_per_kW
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the message will be displayed assert 'DecisionTreeClassifier' in __solution__, "Make sure you are specifying a 'DecisionTreeClassifier'." assert model.get_params()['random_state'] == 1, "Make sure you are settting the model's 'random_state' to 1." assert 'model.fit' in __solution__, "Make sure you are using the '.fit()' function to fit 'X' and 'y'." assert 'model.predict(X)' in __solution__, "Make sure you are using the model to predict on 'X'." assert list(predicted).count('Canada') == 6, "Your predicted values are incorrect. Are you fitting the model properly?" assert list(predicted).count('Both') == 8, "Your predicted values are incorrect. Are you fitting the model properly?" assert list(predicted).count('America') == 11, "Your predicted values are incorrect. Are you fitting the model properly?" __msg__.good("Nice work, well done!")
def test(): assert 'DecisionTreeClassifier' in __solution__, "Make sure you are specifying a 'DecisionTreeClassifier'." assert model.get_params()['random_state'] == 1, "Make sure you are settting the model's 'random_state' to 1." assert 'model.fit' in __solution__, "Make sure you are using the '.fit()' function to fit 'X' and 'y'." assert 'model.predict(X)' in __solution__, "Make sure you are using the model to predict on 'X'." assert list(predicted).count('Canada') == 6, 'Your predicted values are incorrect. Are you fitting the model properly?' assert list(predicted).count('Both') == 8, 'Your predicted values are incorrect. Are you fitting the model properly?' assert list(predicted).count('America') == 11, 'Your predicted values are incorrect. Are you fitting the model properly?' __msg__.good('Nice work, well done!')
"""EXCEPTIONS Exceptions used on the project """ __all__ = ("VigoBusAPIException", "StopNotExist", "StopNotFound") class VigoBusAPIException(Exception): """Base exception for the project custom exceptions""" pass class StopNotExist(VigoBusAPIException): """The Stop does not physically exist (as reported by an external trusted API/data source)""" pass class StopNotFound(VigoBusAPIException): """The Stop was not found on a local data source, but might physically exist""" pass
"""EXCEPTIONS Exceptions used on the project """ __all__ = ('VigoBusAPIException', 'StopNotExist', 'StopNotFound') class Vigobusapiexception(Exception): """Base exception for the project custom exceptions""" pass class Stopnotexist(VigoBusAPIException): """The Stop does not physically exist (as reported by an external trusted API/data source)""" pass class Stopnotfound(VigoBusAPIException): """The Stop was not found on a local data source, but might physically exist""" pass
def foo(): ''' >>> from mod import CamelCase as CONST ''' pass
def foo(): """ >>> from mod import CamelCase as CONST """ pass
#! python3 ############################################################################### # Copyright (c) 2021, PulseRain Technology LLC # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License (LGPL) as # published by the Free Software Foundation, either version 3 of the License, # or (at your option) any later version. # # This program is distributed in the hope that it will be useful, but # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY # or FITNESS FOR A PARTICULAR PURPOSE. # See the GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################### ############################################################################### # References: # https://en.wikipedia.org/wiki/Pseudorandom_binary_sequence ############################################################################### class PRBS: def reset(self, prbs_length, start_value): if (prbs_length == 7): self.poly = 0xC1 >> 1 elif (prbs_length == 9): self.poly = 0x221 >> 1 elif (prbs_length == 11): self.poly = 0xA01 >> 1 elif (prbs_length == 15): self.poly = 0xC001 >> 1 elif (prbs_length == 20): self.poly = 0x80005 >> 1 elif (prbs_length == 23): self.poly = 0x840001 >> 1 else: assert (prbs_length == 31) self.poly = 0xA0000001 >> 1 self.state = start_value self.prbs_length = prbs_length def __init__ (self, prbs_length, start_value): self.reset (prbs_length, start_value) def get_next (self): next_bit = 0 for i in range(self.prbs_length): if ((self.poly >> i) & 1): next_bit = next_bit ^ ((self.state >> i) & 1) self.state = ((self.state << 1) | next_bit) & ((2**(self.prbs_length + 1)) - 1) return self.state def main(): init = 2 p = PRBS (15, init) i = 0 while(1): x = p.get_next() print ("%d 0x%x" % (i, x)) if (x == init): print ("period = %d" % (i + 1)) break i = i + 1 if __name__ == "__main__": main()
class Prbs: def reset(self, prbs_length, start_value): if prbs_length == 7: self.poly = 193 >> 1 elif prbs_length == 9: self.poly = 545 >> 1 elif prbs_length == 11: self.poly = 2561 >> 1 elif prbs_length == 15: self.poly = 49153 >> 1 elif prbs_length == 20: self.poly = 524293 >> 1 elif prbs_length == 23: self.poly = 8650753 >> 1 else: assert prbs_length == 31 self.poly = 2684354561 >> 1 self.state = start_value self.prbs_length = prbs_length def __init__(self, prbs_length, start_value): self.reset(prbs_length, start_value) def get_next(self): next_bit = 0 for i in range(self.prbs_length): if self.poly >> i & 1: next_bit = next_bit ^ self.state >> i & 1 self.state = (self.state << 1 | next_bit) & 2 ** (self.prbs_length + 1) - 1 return self.state def main(): init = 2 p = prbs(15, init) i = 0 while 1: x = p.get_next() print('%d 0x%x' % (i, x)) if x == init: print('period = %d' % (i + 1)) break i = i + 1 if __name__ == '__main__': main()
class AVLNode: def __init__(self, key): self.key = key self.parent = None self.left = None self.right = None self.balance = 0 def has_left(self): return self.left is not None def has_right(self): return self.right is not None def has_no_children(self): return not (self.has_left() or self.has_right()) def is_root(self): return isinstance(self.parent, AVLTree) def is_left(self): return self is self.parent.left def is_right(self): return self is self.parent.right def is_unbalanced(self): return abs(self.balance) > 1 def set_left(self, key): self.left = AVLNode(key) self.left.parent = self self.left.update_balance() def set_right(self, key): self.right = AVLNode(key) self.right.parent = self self.right.update_balance() def update_balance(self): if self.is_unbalanced(): return self.new_balance() if not self.is_root(): parent = self.parent if self.is_left(): parent.balance += 1 elif self.is_right(): parent.balance -= 1 if parent.balance != 0: parent.update_balance() def new_balance(self): if self.balance < 0: if self.right.balance > 0: self.right.rotate_right() self.rotate_left() else: self.rotate_left() elif self.balance > 0: if self.left.balance < 0: self.left.rotate_left() self.rotate_right() else: self.rotate_right() def rotate_left(self): parent = self.parent if self.is_root(): parent.root = self.__rotate_left() elif self.is_left(): parent.left = self.__rotate_left() elif self.is_right(): parent.right = self.__rotate_left() def __rotate_left(self): pivot = self.right self.right = pivot.left if pivot.has_left(): pivot.left.parent = self pivot.left = self parent = self.parent self.parent = pivot pivot.parent = parent self.balance = self.balance + 1 - min(0, pivot.balance) pivot.balance = pivot.balance + 1 + max(0, self.balance) return pivot def rotate_right(self): parent = self.parent if self.is_root(): parent.root = self.__rotate_right() elif self.is_left(): parent.left = self.__rotate_right() elif self.is_right(): parent.right = self.__rotate_right() def __rotate_right(self): pivot = self.left self.left = pivot.right if pivot.has_right(): pivot.right.parent = self pivot.right = self parent = self.parent self.parent = pivot pivot.parent = parent self.balance = self.balance - 1 - max(0, pivot.balance) pivot.balance = pivot.balance - 1 + min(0, self.balance) return pivot def search(self, key): node = self while True: if key == node.key: return node elif key < node.key: if node.has_left(): node = node.left else: break else: if node.has_right(): node = node.right else: break def search_max(self): node = self while node.has_right(): node = node.right return node def update_balance_on_delete(self, came_from_left): if came_from_left: self.balance -= 1 else: self.balance += 1 if self.is_unbalanced(): self.new_balance() if not self.is_root(): if self.parent.balance == 0 and not self.parent.is_root(): self.parent.parent.update_balance_on_delete(self.parent.is_left()) elif self.balance == 0 and not self.is_root(): self.parent.update_balance_on_delete(self.is_left()) def delete(self, node_or_key): if isinstance(node_or_key, AVLNode): node = node_or_key else: node = self.search(node_or_key) if node is None: return parent = node.parent if node.has_no_children(): if node.is_root(): parent.root = None elif node.is_left(): parent.left = None parent.update_balance_on_delete(True) elif node.is_right(): parent.right = None parent.update_balance_on_delete(False) elif node.has_left() and not node.has_right(): if node.is_root(): parent.root = node.left node.left.parent = parent elif node.is_left(): parent.left = node.left node.left.parent = parent parent.update_balance_on_delete(True) elif node.is_right(): parent.right = node.left node.left.parent = parent parent.update_balance_on_delete(False) elif node.has_right() and not node.has_left(): if node.is_root(): parent.root = node.right node.right.parent = parent elif node.is_left(): parent.left = node.right node.right.parent = parent parent.update_balance_on_delete(True) elif node.is_right(): parent.right = node.right node.right.parent = parent parent.update_balance_on_delete(False) else: left_max = node.left.search_max() node.key = left_max.key node.left.delete(left_max) def exists(self, key): return bool(self.search(key)) def insert(self, key): tmp_node = self while True: if key == tmp_node.key: break elif key < tmp_node.key: if tmp_node.has_left(): tmp_node = tmp_node.left else: tmp_node.set_left(key) break else: if tmp_node.has_right(): tmp_node = tmp_node.right else: tmp_node.set_right(key) break @staticmethod def next(tree, x): if tree is None or (tree.key == x and not tree.has_right()): return 'none' elif tree.key > x: k = AVLNode.next(tree.left, x) if k == 'none': return tree.key else: return k elif tree.key < x: return AVLNode.next(tree.right, x) elif tree.key == x: return AVLNode.next(tree.right, x) @staticmethod def prev(tree, x): if tree is None or (tree.key == x and not tree.has_left()): return 'none' elif tree.key < x: k = AVLNode.prev(tree.right, x) if k == 'none': return tree.key else: return k elif tree.key > x: return AVLNode.prev(tree.left, x) elif tree.key == x: return AVLNode.prev(tree.left, x) @staticmethod def kth(tree, ind, nodes_lst): if tree is None or nodes_lst[0] >= ind: return 'none' left = AVLNode.kth(tree.left, ind, nodes_lst) if left != 'none': return left nodes_lst[0] += 1 if nodes_lst[0] == ind: return tree.key return AVLNode.kth(tree.right, ind, nodes_lst) class AVLTree: def __init__(self): self.root = None def is_empty(self): return self.root is None def insert(self, key): if self.is_empty(): self.root = AVLNode(key) self.root.parent = self else: self.root.insert(key) def exists(self, key): if self.is_empty(): return 'false' else: return 'true' if self.root.exists(key) else 'false' def delete(self, key): if not self.is_empty(): self.root.delete(key) def next(self, x): if not self.is_empty(): return AVLNode.next(self.root, x) else: return 'none' def prev(self, x): if not self.is_empty(): return AVLNode.prev(self.root, x) else: return 'none' def kth(self, i): if not self.is_empty(): return AVLNode.kth(self.root, i, [0]) else: return 'none' if __name__ == "__main__": root = AVLTree() while True: try: cmd, arg = input().split() except: break if cmd == 'insert': root.insert(int(arg)) elif cmd == 'delete': root.delete(int(arg)) elif cmd == 'exists': print(root.exists(int(arg))) elif cmd == 'next': print(root.next(int(arg))) elif cmd == 'prev': print(root.prev(int(arg))) elif cmd == 'kth': print(root.kth(int(arg)))
class Avlnode: def __init__(self, key): self.key = key self.parent = None self.left = None self.right = None self.balance = 0 def has_left(self): return self.left is not None def has_right(self): return self.right is not None def has_no_children(self): return not (self.has_left() or self.has_right()) def is_root(self): return isinstance(self.parent, AVLTree) def is_left(self): return self is self.parent.left def is_right(self): return self is self.parent.right def is_unbalanced(self): return abs(self.balance) > 1 def set_left(self, key): self.left = avl_node(key) self.left.parent = self self.left.update_balance() def set_right(self, key): self.right = avl_node(key) self.right.parent = self self.right.update_balance() def update_balance(self): if self.is_unbalanced(): return self.new_balance() if not self.is_root(): parent = self.parent if self.is_left(): parent.balance += 1 elif self.is_right(): parent.balance -= 1 if parent.balance != 0: parent.update_balance() def new_balance(self): if self.balance < 0: if self.right.balance > 0: self.right.rotate_right() self.rotate_left() else: self.rotate_left() elif self.balance > 0: if self.left.balance < 0: self.left.rotate_left() self.rotate_right() else: self.rotate_right() def rotate_left(self): parent = self.parent if self.is_root(): parent.root = self.__rotate_left() elif self.is_left(): parent.left = self.__rotate_left() elif self.is_right(): parent.right = self.__rotate_left() def __rotate_left(self): pivot = self.right self.right = pivot.left if pivot.has_left(): pivot.left.parent = self pivot.left = self parent = self.parent self.parent = pivot pivot.parent = parent self.balance = self.balance + 1 - min(0, pivot.balance) pivot.balance = pivot.balance + 1 + max(0, self.balance) return pivot def rotate_right(self): parent = self.parent if self.is_root(): parent.root = self.__rotate_right() elif self.is_left(): parent.left = self.__rotate_right() elif self.is_right(): parent.right = self.__rotate_right() def __rotate_right(self): pivot = self.left self.left = pivot.right if pivot.has_right(): pivot.right.parent = self pivot.right = self parent = self.parent self.parent = pivot pivot.parent = parent self.balance = self.balance - 1 - max(0, pivot.balance) pivot.balance = pivot.balance - 1 + min(0, self.balance) return pivot def search(self, key): node = self while True: if key == node.key: return node elif key < node.key: if node.has_left(): node = node.left else: break elif node.has_right(): node = node.right else: break def search_max(self): node = self while node.has_right(): node = node.right return node def update_balance_on_delete(self, came_from_left): if came_from_left: self.balance -= 1 else: self.balance += 1 if self.is_unbalanced(): self.new_balance() if not self.is_root(): if self.parent.balance == 0 and (not self.parent.is_root()): self.parent.parent.update_balance_on_delete(self.parent.is_left()) elif self.balance == 0 and (not self.is_root()): self.parent.update_balance_on_delete(self.is_left()) def delete(self, node_or_key): if isinstance(node_or_key, AVLNode): node = node_or_key else: node = self.search(node_or_key) if node is None: return parent = node.parent if node.has_no_children(): if node.is_root(): parent.root = None elif node.is_left(): parent.left = None parent.update_balance_on_delete(True) elif node.is_right(): parent.right = None parent.update_balance_on_delete(False) elif node.has_left() and (not node.has_right()): if node.is_root(): parent.root = node.left node.left.parent = parent elif node.is_left(): parent.left = node.left node.left.parent = parent parent.update_balance_on_delete(True) elif node.is_right(): parent.right = node.left node.left.parent = parent parent.update_balance_on_delete(False) elif node.has_right() and (not node.has_left()): if node.is_root(): parent.root = node.right node.right.parent = parent elif node.is_left(): parent.left = node.right node.right.parent = parent parent.update_balance_on_delete(True) elif node.is_right(): parent.right = node.right node.right.parent = parent parent.update_balance_on_delete(False) else: left_max = node.left.search_max() node.key = left_max.key node.left.delete(left_max) def exists(self, key): return bool(self.search(key)) def insert(self, key): tmp_node = self while True: if key == tmp_node.key: break elif key < tmp_node.key: if tmp_node.has_left(): tmp_node = tmp_node.left else: tmp_node.set_left(key) break elif tmp_node.has_right(): tmp_node = tmp_node.right else: tmp_node.set_right(key) break @staticmethod def next(tree, x): if tree is None or (tree.key == x and (not tree.has_right())): return 'none' elif tree.key > x: k = AVLNode.next(tree.left, x) if k == 'none': return tree.key else: return k elif tree.key < x: return AVLNode.next(tree.right, x) elif tree.key == x: return AVLNode.next(tree.right, x) @staticmethod def prev(tree, x): if tree is None or (tree.key == x and (not tree.has_left())): return 'none' elif tree.key < x: k = AVLNode.prev(tree.right, x) if k == 'none': return tree.key else: return k elif tree.key > x: return AVLNode.prev(tree.left, x) elif tree.key == x: return AVLNode.prev(tree.left, x) @staticmethod def kth(tree, ind, nodes_lst): if tree is None or nodes_lst[0] >= ind: return 'none' left = AVLNode.kth(tree.left, ind, nodes_lst) if left != 'none': return left nodes_lst[0] += 1 if nodes_lst[0] == ind: return tree.key return AVLNode.kth(tree.right, ind, nodes_lst) class Avltree: def __init__(self): self.root = None def is_empty(self): return self.root is None def insert(self, key): if self.is_empty(): self.root = avl_node(key) self.root.parent = self else: self.root.insert(key) def exists(self, key): if self.is_empty(): return 'false' else: return 'true' if self.root.exists(key) else 'false' def delete(self, key): if not self.is_empty(): self.root.delete(key) def next(self, x): if not self.is_empty(): return AVLNode.next(self.root, x) else: return 'none' def prev(self, x): if not self.is_empty(): return AVLNode.prev(self.root, x) else: return 'none' def kth(self, i): if not self.is_empty(): return AVLNode.kth(self.root, i, [0]) else: return 'none' if __name__ == '__main__': root = avl_tree() while True: try: (cmd, arg) = input().split() except: break if cmd == 'insert': root.insert(int(arg)) elif cmd == 'delete': root.delete(int(arg)) elif cmd == 'exists': print(root.exists(int(arg))) elif cmd == 'next': print(root.next(int(arg))) elif cmd == 'prev': print(root.prev(int(arg))) elif cmd == 'kth': print(root.kth(int(arg)))
# Project Euler Problem 11 # Created on: 2012-06-14 # Created by: William McDonald # Return the minimum number that can be present in # a solution set of four numbers def getMin(cap, min): k = 99 * 99 * 99 for i in range(min, 99): if i * k > cap: return i def importGrid(): f = open("problem11.txt") grid = [] for line in f: str = line lon = str.split(" ") i = 0 for n in lon: lon[i] = int(n) i += 1 grid.append(lon) f.close() return grid def transpose(g): return map(list, zip(*g)) def makeDiagGrid(g): n = [] for i in range(3, len(g)): temp = [] for j in range(i, -1, -1): temp.append(g[j][i - j]) n.append(temp) for i in range(1, len(g) - 3): temp = [] for j in range(0, len(g) - i): temp.append(g[i + j][len(g) - 1 - j]) n.append(temp) return n def getAns(): # Cursory examination: 94 * 99 * 71 * 61 max = 94 * 99 * 71 * 61 min = getMin(max, 0) udg = importGrid() lrg = transpose(udg) dg1 = makeDiagGrid(lrg) lrg.reverse() dg2 = makeDiagGrid(lrg) grids = [udg, lrg, dg1, dg2] for g in grids: prod = 1 i = 0 while i < len(g): j = 0 lst = g[i] while j < (len(lst) - 3): for k in range(4): if lst[j + k] < min: j += k break else: prod *= lst[j + k] else: if prod > max: max = prod min = getMin(max, min) j += 1 prod = 1 i += 1 return max ans = getAns() print(ans)
def get_min(cap, min): k = 99 * 99 * 99 for i in range(min, 99): if i * k > cap: return i def import_grid(): f = open('problem11.txt') grid = [] for line in f: str = line lon = str.split(' ') i = 0 for n in lon: lon[i] = int(n) i += 1 grid.append(lon) f.close() return grid def transpose(g): return map(list, zip(*g)) def make_diag_grid(g): n = [] for i in range(3, len(g)): temp = [] for j in range(i, -1, -1): temp.append(g[j][i - j]) n.append(temp) for i in range(1, len(g) - 3): temp = [] for j in range(0, len(g) - i): temp.append(g[i + j][len(g) - 1 - j]) n.append(temp) return n def get_ans(): max = 94 * 99 * 71 * 61 min = get_min(max, 0) udg = import_grid() lrg = transpose(udg) dg1 = make_diag_grid(lrg) lrg.reverse() dg2 = make_diag_grid(lrg) grids = [udg, lrg, dg1, dg2] for g in grids: prod = 1 i = 0 while i < len(g): j = 0 lst = g[i] while j < len(lst) - 3: for k in range(4): if lst[j + k] < min: j += k break else: prod *= lst[j + k] else: if prod > max: max = prod min = get_min(max, min) j += 1 prod = 1 i += 1 return max ans = get_ans() print(ans)
def get_final_line( filepath: str ) -> str: with open(filepath) as fs_r: for line in fs_r: pass return line def get_final_line__readlines( filepath: str ) -> str: with open(filepath) as fs_r: return fs_r.readlines()[-1] def main(): filepath = 'file.txt' final_line_content = get_final_line(filepath) print(f'Final line content: [{final_line_content}]') if __name__ == '__main__': main()
def get_final_line(filepath: str) -> str: with open(filepath) as fs_r: for line in fs_r: pass return line def get_final_line__readlines(filepath: str) -> str: with open(filepath) as fs_r: return fs_r.readlines()[-1] def main(): filepath = 'file.txt' final_line_content = get_final_line(filepath) print(f'Final line content: [{final_line_content}]') if __name__ == '__main__': main()
price = float(input("Digite o preco do produto: ")) discount = (5/100) * price total = price - discount print("O valor com desconto eh: {:.2f}".format(total))
price = float(input('Digite o preco do produto: ')) discount = 5 / 100 * price total = price - discount print('O valor com desconto eh: {:.2f}'.format(total))
def soma(n1, n2): return n1 + n2 def subtracao(n1,n2): return n1 - n2 def multiplicacao(n1, n2): return n1 * n2 def divisao(n1, n2): return n1 / n2
def soma(n1, n2): return n1 + n2 def subtracao(n1, n2): return n1 - n2 def multiplicacao(n1, n2): return n1 * n2 def divisao(n1, n2): return n1 / n2
# noinspection PyUnusedLocal # skus = unicode string price_table = { 'A': {'Price': 50, 'Offers': ['3A', 130]}, 'B': {'Price': 30, 'Offers': ['2b', 45]}, 'C': {'Price': 20, 'Offers': []}, 'D': {'Price': 15, 'Offers': []} } def checkout(skus): if ((skus.isalpha() and skus.isupper()) or skus == ''): order_dict = build_orders(skus) running_total = 0 for order in order_dict: cur_total = get_price(order, order_dict[order]) running_total += cur_total return running_total else: return -1 def get_price(stock, units): try: item = price_table.get(stock) running_total = 0 offers = item.get('Offers', []) if item.get('Offers', []) != []: offer = int(offers[0][0]) if units >= offer: offer_quantity = int(units / int(offer)) running_total += (offers[1] * offer_quantity) units -= int(offer_quantity * offer) amount = units * item['Price'] running_total += amount return running_total except Exception as e: return 0 def build_orders(orders): order_dict = {} for order in orders: quantity = order_dict.get(order.upper(), 0) quantity += 1 order_dict.update({order.upper(): quantity}) return order_dict
price_table = {'A': {'Price': 50, 'Offers': ['3A', 130]}, 'B': {'Price': 30, 'Offers': ['2b', 45]}, 'C': {'Price': 20, 'Offers': []}, 'D': {'Price': 15, 'Offers': []}} def checkout(skus): if skus.isalpha() and skus.isupper() or skus == '': order_dict = build_orders(skus) running_total = 0 for order in order_dict: cur_total = get_price(order, order_dict[order]) running_total += cur_total return running_total else: return -1 def get_price(stock, units): try: item = price_table.get(stock) running_total = 0 offers = item.get('Offers', []) if item.get('Offers', []) != []: offer = int(offers[0][0]) if units >= offer: offer_quantity = int(units / int(offer)) running_total += offers[1] * offer_quantity units -= int(offer_quantity * offer) amount = units * item['Price'] running_total += amount return running_total except Exception as e: return 0 def build_orders(orders): order_dict = {} for order in orders: quantity = order_dict.get(order.upper(), 0) quantity += 1 order_dict.update({order.upper(): quantity}) return order_dict
""" Add `Django Filebrowser`_ to your project so you can use a centralized interface to manage the uploaded files to be used with other components (`cms`_, `zinnia`_, etc.). The version used is a special version called *no grappelli* that can be used outside of the *django-grapelli* environment. Filebrowser manage files with a nice interface to centralize them and also manage image resizing versions (original, small, medium, etc..), you can edit these versions or add new ones in the settings. .. note:: Don't try to use other resizing app like sorl-thumbnails or easy-thumbnails, they will not work with Image fields managed with Filebrowser. """
""" Add `Django Filebrowser`_ to your project so you can use a centralized interface to manage the uploaded files to be used with other components (`cms`_, `zinnia`_, etc.). The version used is a special version called *no grappelli* that can be used outside of the *django-grapelli* environment. Filebrowser manage files with a nice interface to centralize them and also manage image resizing versions (original, small, medium, etc..), you can edit these versions or add new ones in the settings. .. note:: Don't try to use other resizing app like sorl-thumbnails or easy-thumbnails, they will not work with Image fields managed with Filebrowser. """
def first_non_consecutive(arr: list) -> int: ''' This function returns the first element of an array that is not consecutive. ''' if len(arr) < 2: return None non_consecutive = [] for i in range(len(arr) - 1): if arr[i+1] - arr[i] != 1: non_consecutive.append(arr[i+1]) if len(non_consecutive) == 0: return None return int(''.join(map(str, non_consecutive[:1])))
def first_non_consecutive(arr: list) -> int: """ This function returns the first element of an array that is not consecutive. """ if len(arr) < 2: return None non_consecutive = [] for i in range(len(arr) - 1): if arr[i + 1] - arr[i] != 1: non_consecutive.append(arr[i + 1]) if len(non_consecutive) == 0: return None return int(''.join(map(str, non_consecutive[:1])))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @author: Jared """ # LATTICE VARIATION lattice_mul = 20 #how many lattice variations to perform lattice_variation_percent = 10 keep_aspect = False # COMPOSITION VARIATION # upper limit to sim num lattice_comp_num = 500 #how many crystals to generate (random mixing) lattice_init = [11.7, 5.4, 11.7] #lattice_init = [12.5, 6.19, 12.5] # ATOMIC VARIATION fnum = 20 # how many atomic randomizations for a given crystal atomic_position_variation_percent = 3 resolution = [1, 1, 2] #cannot change to [4, 4, 12] due to itertools overflow # possible elements # Asite = ['Rb', 'Cs', 'K', 'Na'] # Bsite = ['Sn', 'Ge'] # Xsite = ['Cl', 'Br', 'I'] #test compound trend Asite = ['Cs', 'Rb', 'K', 'Na'] Bsite = ['Sn', 'Ge'] Xsite = ['I', 'Cl', 'Br'] #fname = 'builderOutput.csv' #path = './bin/'
""" @author: Jared """ lattice_mul = 20 lattice_variation_percent = 10 keep_aspect = False lattice_comp_num = 500 lattice_init = [11.7, 5.4, 11.7] fnum = 20 atomic_position_variation_percent = 3 resolution = [1, 1, 2] asite = ['Cs', 'Rb', 'K', 'Na'] bsite = ['Sn', 'Ge'] xsite = ['I', 'Cl', 'Br']
try: print('enter try statement') raise Exception() print('exit try statement') except Exception as inst: print(inst.__class__.__name__)
try: print('enter try statement') raise exception() print('exit try statement') except Exception as inst: print(inst.__class__.__name__)
def solution(M, A): # write your code in Python 3.6 seen = [0] * (M + 1) count = 0 i,j = 0,0 while(i < len(A) and j < len(A)): if seen[A[j]]: seen[A[i]] = 0 i += 1 else: seen[A[j]] = 1 count += j - i + 1 j += 1 if count > 1e9: return int(1e9) return count
def solution(M, A): seen = [0] * (M + 1) count = 0 (i, j) = (0, 0) while i < len(A) and j < len(A): if seen[A[j]]: seen[A[i]] = 0 i += 1 else: seen[A[j]] = 1 count += j - i + 1 j += 1 if count > 1000000000.0: return int(1000000000.0) return count
# Time: O(n) # Space: O(1) # 978 # A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if: # - For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even; # - OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd. # That is, the subarray is turbulent if the comparison sign flips between each adjacent # pair of elements in the subarray. # # Return the length of a maximum size turbulent subarray of A. # # Example 1: # Input: [9,4,2,10,7,8,8,1,9] # Output: 5 # Explanation: (A[1] > A[2] < A[3] > A[4] < A[5]) class Solution(object): # Solution: sliding window # If we are at the end of a window (last elements OR it stopped alternating), then we # record the length of that window as our candidate answer, and set the start of a new window. def maxTurbulenceSize(self, A): """ :type A: List[int] :rtype: int """ ans = 1 start = 0 for i in xrange(1, len(A)): c = cmp(A[i-1], A[i]) if c == 0: start = i elif i == len(A)-1 or c * cmp(A[i], A[i+1]) != -1: ans = max(ans, i-start+1) start = i return ans # Dynamic programming. Time O(n), Space O(n). Many values stored in dp array are not needed. # E.g up/down values followed by a comma is not useful. # A = [9, 4,2,10,7,8,8,1,9] # up= 1 1 1,3 1,5 1 1,3 # down= 1, 2 2 1, 4 1,1,2 1, def maxTurbulenceSize_dp(self, A): N = len(A) up, down, ans = [1]*N, [1]*N, 1 for i in xrange(1, len(A)): if A[i] > A[i-1]: up[i] = down[i-1] + 1 elif A[i] < A[i-1]: down[i] = up[i-1] + 1 ans = max(ans, up[i], down[i]) return ans print(Solution().maxTurbulenceSize([1,1,1,1,1]))
class Solution(object): def max_turbulence_size(self, A): """ :type A: List[int] :rtype: int """ ans = 1 start = 0 for i in xrange(1, len(A)): c = cmp(A[i - 1], A[i]) if c == 0: start = i elif i == len(A) - 1 or c * cmp(A[i], A[i + 1]) != -1: ans = max(ans, i - start + 1) start = i return ans def max_turbulence_size_dp(self, A): n = len(A) (up, down, ans) = ([1] * N, [1] * N, 1) for i in xrange(1, len(A)): if A[i] > A[i - 1]: up[i] = down[i - 1] + 1 elif A[i] < A[i - 1]: down[i] = up[i - 1] + 1 ans = max(ans, up[i], down[i]) return ans print(solution().maxTurbulenceSize([1, 1, 1, 1, 1]))
class TitleItem: def __init__(self, title='', title_type='', genre='', directors='', actors='', run_time='', release_date='', cover_url=''): """ :param title: String. The title of the movie/tv show. :param title_type: String. Options: feature or tv_series. :param genre: String. A list of genres the title belongs to. :param directors: String. A list of director(s). :param actors: String. A list of actor(s). :param run_time: String. The runtime of the movie. :param release_date: String. The release date of the movie. :param cover_url: String. The URL of the media cover. """ self.title = title self.title_type = title_type self.genre = genre self.directors = directors self.actors = actors self.run_time = run_time self.release_date = release_date self.cover_url = cover_url
class Titleitem: def __init__(self, title='', title_type='', genre='', directors='', actors='', run_time='', release_date='', cover_url=''): """ :param title: String. The title of the movie/tv show. :param title_type: String. Options: feature or tv_series. :param genre: String. A list of genres the title belongs to. :param directors: String. A list of director(s). :param actors: String. A list of actor(s). :param run_time: String. The runtime of the movie. :param release_date: String. The release date of the movie. :param cover_url: String. The URL of the media cover. """ self.title = title self.title_type = title_type self.genre = genre self.directors = directors self.actors = actors self.run_time = run_time self.release_date = release_date self.cover_url = cover_url
class Earth: """ Class used to represent Earth. Values are defined using EGM96 geopotential model. Constant naming convention is intentionally not used since the values defined here may be updated in the future by introducing other geopotential models """ mu = 3.986004415e5 #km^3/s^2 equatorial_radius = 6378.1363 #km
class Earth: """ Class used to represent Earth. Values are defined using EGM96 geopotential model. Constant naming convention is intentionally not used since the values defined here may be updated in the future by introducing other geopotential models """ mu = 398600.4415 equatorial_radius = 6378.1363
# # PySNMP MIB module Wellfleet-DS1-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-DS1-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:39:54 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, Gauge32, Counter64, MibIdentifier, Unsigned32, Integer32, ModuleIdentity, NotificationType, ObjectIdentity, Counter32, mgmt, MibScalar, MibTable, MibTableRow, MibTableColumn, mib_2, NotificationType, IpAddress, Bits, enterprises, Opaque, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "Counter64", "MibIdentifier", "Unsigned32", "Integer32", "ModuleIdentity", "NotificationType", "ObjectIdentity", "Counter32", "mgmt", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "mib-2", "NotificationType", "IpAddress", "Bits", "enterprises", "Opaque", "TimeTicks") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") wfDs1Group, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfDs1Group") wfDs1Config = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1), ) if mibBuilder.loadTexts: wfDs1Config.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Config.setDescription('The DS1 Configuration table') wfDs1ConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1LineIndex")) if mibBuilder.loadTexts: wfDs1ConfigEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1ConfigEntry.setDescription('per circuit DS1 configuration objects; wfDs1LineIndex corresponds to Wellfleet circuit number') wfDs1LineIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1LineIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LineIndex.setDescription('this corresponds to the Wellfleet circuit number') wfDs1TimeElapsed = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TimeElapsed.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TimeElapsed.setDescription('1..900 seconds within the current 15-minute interval') wfDs1ValidIntervals = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1ValidIntervals.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1ValidIntervals.setDescription('0..96 previous intervals that valid data were collected. This is 96 unless the CSU device was brought on line within the last 24 hours.') wfDs1LineType = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4))).clone(namedValues=NamedValues(("ds1ansi-esf", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1LineType.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LineType.setDescription('the variety of DS1 implementing this circuit') wfDs1ZeroCoding = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2, 5))).clone(namedValues=NamedValues(("ds1b8zs", 2), ("ds1zbtsi", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1ZeroCoding.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1ZeroCoding.setDescription('the variety of Zero Code Suppression used on the link') wfDs1SendCode = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2))).clone(namedValues=NamedValues(("ds1sendnocode", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1SendCode.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1SendCode.setDescription('the type of code being sent across the DS1 circuit by the CSU') wfDs1CircuitIdentifier = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 7), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CircuitIdentifier.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CircuitIdentifier.setDescription("the transmission vendor's circuit identifier") wfDs1LoopbackConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("ds1noloop", 1), ("ds1mgrpayloadloop", 2), ("ds1mgrlineloop", 3), ("ds1netreqpayloadloop", 4), ("ds1netreqlineloop", 5), ("ds1otherloop", 6)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1LoopbackConfig.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LoopbackConfig.setDescription('the loopback state of the CSU') wfDs1LineStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 4, 8, 16, 32))).clone(namedValues=NamedValues(("ds1noalarm", 1), ("ds1farendalarm", 2), ("ds1alarmindicationsignal", 4), ("ds1lossofframe", 8), ("ds1lossofsignal", 16), ("ds1loopbackstate", 32)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1LineStatus.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LineStatus.setDescription('the state of the DS1 line') wfDs1Current = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2), ) if mibBuilder.loadTexts: wfDs1Current.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Current.setDescription('The DS1 Current table') wfDs1CurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1CurrentIndex")) if mibBuilder.loadTexts: wfDs1CurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentEntry.setDescription('per circuit DS1 current objects - wfDs1CurrentIndex corresponds to Wellfleet circuit number') wfDs1CurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentIndex.setDescription('this corresponds to the Wellfleet circuit number') wfDs1CurrentESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CurrentESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentESs.setDescription('the count of errored seconds in the current interval') wfDs1CurrentSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CurrentSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentSESs.setDescription('the count of severely errored seconds in the current interval') wfDs1CurrentSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CurrentSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentSEFs.setDescription('the count of severely errored framing seconds in the current interval') wfDs1CurrentUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CurrentUASs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentUASs.setDescription('the number of unavailable seconds in the current interval') wfDs1CurrentBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CurrentBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentBPVs.setDescription('the count of bipolar violations in the current interval') wfDs1CurrentCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1CurrentCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentCVs.setDescription('the count of code violation error events in the current interval') wfDs1Interval = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3), ) if mibBuilder.loadTexts: wfDs1Interval.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Interval.setDescription('The DS1 Interval table') wfDs1IntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1IntervalIndex"), (0, "Wellfleet-DS1-MIB", "wfDs1IntervalNumber")) if mibBuilder.loadTexts: wfDs1IntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalEntry.setDescription('per circuit DS1 interval objects - wfDs1IntervalIndex corresponds to Wellfleet circuit number, wfDs1IntervalNumber is the numbered previous 15-minute interval') wfDs1IntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalIndex.setDescription('this corresponds to the Wellfleet circuit number') wfDs1IntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalNumber.setDescription('1..96 where 1 is the most recent 15-minute interval and 96 is the least') wfDs1IntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalESs.setDescription('the count of errored seconds in the specified interval') wfDs1IntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalSESs.setDescription('the count of severely errored seconds in the specified interval') wfDs1IntervalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalSEFs.setDescription('the count of severely errored framing seconds in the specified interval') wfDs1IntervalUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalUASs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalUASs.setDescription('the number of unavailable seconds in the specified interval') wfDs1IntervalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalBPVs.setDescription('the count of bipolar violations in the specified interval') wfDs1IntervalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 8), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1IntervalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalCVs.setDescription('the count of code violation error events in the specified interval') wfDs1Total = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4), ) if mibBuilder.loadTexts: wfDs1Total.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Total.setDescription('The DS1 Total table') wfDs1TotalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1TotalIndex")) if mibBuilder.loadTexts: wfDs1TotalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalEntry.setDescription('per circuit DS1 total objects - wfDs1TotalIndex corresponds to Wellfleet circuit number') wfDs1TotalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TotalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalIndex.setDescription('this corresponds to the Wellfleet circuit number') wfDs1TotalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TotalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalESs.setDescription('total count of errored seconds') wfDs1TotalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TotalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalSESs.setDescription('total count of severely errored seconds') wfDs1TotalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TotalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalSEFs.setDescription('total count of severely errored framing seconds') wfDs1TotalUASs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TotalUASs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalUASs.setDescription('total number of unavailable seconds') wfDs1TotalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TotalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalBPVs.setDescription('total count of bipolar violations') wfDs1TotalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1TotalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalCVs.setDescription('total count of code violation error events') wfDs1FeCurrent = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5), ) if mibBuilder.loadTexts: wfDs1FeCurrent.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrent.setDescription('The DS1 Far End Current table') wfDs1FeCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1FeCurrentIndex")) if mibBuilder.loadTexts: wfDs1FeCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentEntry.setDescription('per circuit DS1 far end current objects wfDs1CurrentIndex corresponds to Wellfleet circuit number') wfDs1FeCurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentIndex.setDescription('this corresponds to the Wellfleet circuit number') wfDs1FeCurrentESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 2), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeCurrentESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentESs.setDescription('the count of errored seconds in the current interval') wfDs1FeCurrentSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 3), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeCurrentSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentSESs.setDescription('the count of severely errored seconds in the current interval') wfDs1FeCurrentSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 4), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeCurrentSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentSEFs.setDescription('the count of severely errored framing seconds in the current interval') wfDs1FeCurrentBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeCurrentBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentBPVs.setDescription('the count of bipolar violations in the current interval') wfDs1FeCurrentCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeCurrentCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentCVs.setDescription('the count of code violation error events in the current interval') wfDs1FeInterval = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6), ) if mibBuilder.loadTexts: wfDs1FeInterval.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeInterval.setDescription('The DS1 Far End Interval table') wfDs1FeIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1FeIntervalIndex"), (0, "Wellfleet-DS1-MIB", "wfDs1FeIntervalNumber")) if mibBuilder.loadTexts: wfDs1FeIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalEntry.setDescription('per circuit DS1 far end interval objects - wfDs1FeIntervalIndex corresponds to Wellfleet circuit number, wfDs1FeIntervalNumber is the numbered previous 15-minute interval') wfDs1FeIntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalIndex.setDescription('this corresponds to the Wellfleet circuit number') wfDs1FeIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 96))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalNumber.setDescription('1..96 where 1 is the most recent 15-minute interval and 96 is the least') wfDs1FeIntervalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeIntervalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalESs.setDescription('the count of errored seconds in the specified interval') wfDs1FeIntervalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeIntervalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalSESs.setDescription('the count of severely errored seconds in the specified interval') wfDs1FeIntervalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeIntervalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalSEFs.setDescription('the count of severely errored framing seconds in the specified interval') wfDs1FeIntervalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeIntervalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalBPVs.setDescription('the count of bipolar violations in the specified interval') wfDs1FeIntervalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeIntervalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalCVs.setDescription('the count of code violation error events in the specified interval') wfDs1FeTotal = MibTable((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7), ) if mibBuilder.loadTexts: wfDs1FeTotal.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotal.setDescription('The DS1 Far End Total table') wfDs1FeTotalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1), ).setIndexNames((0, "Wellfleet-DS1-MIB", "wfDs1FeTotalIndex")) if mibBuilder.loadTexts: wfDs1FeTotalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalEntry.setDescription('per circuit DS1 far end total objects - wfDs1FeTotalIndex corresponds to Wellfleet circuit number') wfDs1FeTotalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeTotalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalIndex.setDescription('this corresponds to the Wellfleet circuit number') wfDs1FeTotalESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 2), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeTotalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalESs.setDescription('total count of errored seconds') wfDs1FeTotalSESs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeTotalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalSESs.setDescription('total count of severely errored seconds') wfDs1FeTotalSEFs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeTotalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalSEFs.setDescription('total count of severely errored framing seconds') wfDs1FeTotalBPVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeTotalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalBPVs.setDescription('total count of bipolar violations') wfDs1FeTotalCVs = MibTableColumn((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wfDs1FeTotalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalCVs.setDescription('total count of code violation error events') mibBuilder.exportSymbols("Wellfleet-DS1-MIB", wfDs1FeIntervalNumber=wfDs1FeIntervalNumber, wfDs1Config=wfDs1Config, wfDs1CurrentIndex=wfDs1CurrentIndex, wfDs1TotalSESs=wfDs1TotalSESs, wfDs1FeIntervalIndex=wfDs1FeIntervalIndex, wfDs1IntervalUASs=wfDs1IntervalUASs, wfDs1FeTotalIndex=wfDs1FeTotalIndex, wfDs1FeTotalEntry=wfDs1FeTotalEntry, wfDs1IntervalESs=wfDs1IntervalESs, wfDs1CurrentEntry=wfDs1CurrentEntry, wfDs1CurrentCVs=wfDs1CurrentCVs, wfDs1FeTotalESs=wfDs1FeTotalESs, wfDs1LineStatus=wfDs1LineStatus, wfDs1CurrentBPVs=wfDs1CurrentBPVs, wfDs1FeIntervalSEFs=wfDs1FeIntervalSEFs, wfDs1TotalEntry=wfDs1TotalEntry, wfDs1ValidIntervals=wfDs1ValidIntervals, wfDs1IntervalCVs=wfDs1IntervalCVs, wfDs1FeCurrentEntry=wfDs1FeCurrentEntry, wfDs1IntervalNumber=wfDs1IntervalNumber, wfDs1Interval=wfDs1Interval, wfDs1TotalCVs=wfDs1TotalCVs, wfDs1FeTotal=wfDs1FeTotal, wfDs1CurrentSEFs=wfDs1CurrentSEFs, wfDs1TotalSEFs=wfDs1TotalSEFs, wfDs1CurrentESs=wfDs1CurrentESs, wfDs1LineIndex=wfDs1LineIndex, wfDs1SendCode=wfDs1SendCode, wfDs1IntervalIndex=wfDs1IntervalIndex, wfDs1ZeroCoding=wfDs1ZeroCoding, wfDs1IntervalSESs=wfDs1IntervalSESs, wfDs1CircuitIdentifier=wfDs1CircuitIdentifier, wfDs1FeTotalCVs=wfDs1FeTotalCVs, wfDs1Total=wfDs1Total, wfDs1FeCurrentESs=wfDs1FeCurrentESs, wfDs1FeInterval=wfDs1FeInterval, wfDs1FeTotalSESs=wfDs1FeTotalSESs, wfDs1FeCurrent=wfDs1FeCurrent, wfDs1FeCurrentBPVs=wfDs1FeCurrentBPVs, wfDs1FeTotalSEFs=wfDs1FeTotalSEFs, wfDs1CurrentSESs=wfDs1CurrentSESs, wfDs1IntervalBPVs=wfDs1IntervalBPVs, wfDs1FeIntervalSESs=wfDs1FeIntervalSESs, wfDs1FeIntervalBPVs=wfDs1FeIntervalBPVs, wfDs1FeIntervalCVs=wfDs1FeIntervalCVs, wfDs1FeIntervalEntry=wfDs1FeIntervalEntry, wfDs1ConfigEntry=wfDs1ConfigEntry, wfDs1TimeElapsed=wfDs1TimeElapsed, wfDs1FeTotalBPVs=wfDs1FeTotalBPVs, wfDs1FeCurrentIndex=wfDs1FeCurrentIndex, wfDs1Current=wfDs1Current, wfDs1TotalESs=wfDs1TotalESs, wfDs1CurrentUASs=wfDs1CurrentUASs, wfDs1FeIntervalESs=wfDs1FeIntervalESs, wfDs1FeCurrentSESs=wfDs1FeCurrentSESs, wfDs1LineType=wfDs1LineType, wfDs1TotalUASs=wfDs1TotalUASs, wfDs1TotalIndex=wfDs1TotalIndex, wfDs1IntervalSEFs=wfDs1IntervalSEFs, wfDs1IntervalEntry=wfDs1IntervalEntry, wfDs1FeCurrentSEFs=wfDs1FeCurrentSEFs, wfDs1FeCurrentCVs=wfDs1FeCurrentCVs, wfDs1LoopbackConfig=wfDs1LoopbackConfig, wfDs1TotalBPVs=wfDs1TotalBPVs)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, constraints_union, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (iso, gauge32, counter64, mib_identifier, unsigned32, integer32, module_identity, notification_type, object_identity, counter32, mgmt, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_2, notification_type, ip_address, bits, enterprises, opaque, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Gauge32', 'Counter64', 'MibIdentifier', 'Unsigned32', 'Integer32', 'ModuleIdentity', 'NotificationType', 'ObjectIdentity', 'Counter32', 'mgmt', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'mib-2', 'NotificationType', 'IpAddress', 'Bits', 'enterprises', 'Opaque', 'TimeTicks') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (wf_ds1_group,) = mibBuilder.importSymbols('Wellfleet-COMMON-MIB', 'wfDs1Group') wf_ds1_config = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1)) if mibBuilder.loadTexts: wfDs1Config.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Config.setDescription('The DS1 Configuration table') wf_ds1_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1)).setIndexNames((0, 'Wellfleet-DS1-MIB', 'wfDs1LineIndex')) if mibBuilder.loadTexts: wfDs1ConfigEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1ConfigEntry.setDescription('per circuit DS1 configuration objects; wfDs1LineIndex corresponds to Wellfleet circuit number') wf_ds1_line_index = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1LineIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LineIndex.setDescription('this corresponds to the Wellfleet circuit number') wf_ds1_time_elapsed = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TimeElapsed.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TimeElapsed.setDescription('1..900 seconds within the current 15-minute interval') wf_ds1_valid_intervals = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1ValidIntervals.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1ValidIntervals.setDescription('0..96 previous intervals that valid data were collected. This is 96 unless the CSU device was brought on line within the last 24 hours.') wf_ds1_line_type = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(4))).clone(namedValues=named_values(('ds1ansi-esf', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1LineType.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LineType.setDescription('the variety of DS1 implementing this circuit') wf_ds1_zero_coding = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(2, 5))).clone(namedValues=named_values(('ds1b8zs', 2), ('ds1zbtsi', 5)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1ZeroCoding.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1ZeroCoding.setDescription('the variety of Zero Code Suppression used on the link') wf_ds1_send_code = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(2))).clone(namedValues=named_values(('ds1sendnocode', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1SendCode.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1SendCode.setDescription('the type of code being sent across the DS1 circuit by the CSU') wf_ds1_circuit_identifier = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 7), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CircuitIdentifier.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CircuitIdentifier.setDescription("the transmission vendor's circuit identifier") wf_ds1_loopback_config = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('ds1noloop', 1), ('ds1mgrpayloadloop', 2), ('ds1mgrlineloop', 3), ('ds1netreqpayloadloop', 4), ('ds1netreqlineloop', 5), ('ds1otherloop', 6)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1LoopbackConfig.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LoopbackConfig.setDescription('the loopback state of the CSU') wf_ds1_line_status = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 4, 8, 16, 32))).clone(namedValues=named_values(('ds1noalarm', 1), ('ds1farendalarm', 2), ('ds1alarmindicationsignal', 4), ('ds1lossofframe', 8), ('ds1lossofsignal', 16), ('ds1loopbackstate', 32)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1LineStatus.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1LineStatus.setDescription('the state of the DS1 line') wf_ds1_current = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2)) if mibBuilder.loadTexts: wfDs1Current.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Current.setDescription('The DS1 Current table') wf_ds1_current_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1)).setIndexNames((0, 'Wellfleet-DS1-MIB', 'wfDs1CurrentIndex')) if mibBuilder.loadTexts: wfDs1CurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentEntry.setDescription('per circuit DS1 current objects - wfDs1CurrentIndex corresponds to Wellfleet circuit number') wf_ds1_current_index = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentIndex.setDescription('this corresponds to the Wellfleet circuit number') wf_ds1_current_e_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CurrentESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentESs.setDescription('the count of errored seconds in the current interval') wf_ds1_current_se_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 3), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CurrentSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentSESs.setDescription('the count of severely errored seconds in the current interval') wf_ds1_current_se_fs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 4), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CurrentSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentSEFs.setDescription('the count of severely errored framing seconds in the current interval') wf_ds1_current_ua_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 5), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CurrentUASs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentUASs.setDescription('the number of unavailable seconds in the current interval') wf_ds1_current_bp_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 6), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CurrentBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentBPVs.setDescription('the count of bipolar violations in the current interval') wf_ds1_current_c_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 2, 1, 7), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1CurrentCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1CurrentCVs.setDescription('the count of code violation error events in the current interval') wf_ds1_interval = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3)) if mibBuilder.loadTexts: wfDs1Interval.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Interval.setDescription('The DS1 Interval table') wf_ds1_interval_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1)).setIndexNames((0, 'Wellfleet-DS1-MIB', 'wfDs1IntervalIndex'), (0, 'Wellfleet-DS1-MIB', 'wfDs1IntervalNumber')) if mibBuilder.loadTexts: wfDs1IntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalEntry.setDescription('per circuit DS1 interval objects - wfDs1IntervalIndex corresponds to Wellfleet circuit number, wfDs1IntervalNumber is the numbered previous 15-minute interval') wf_ds1_interval_index = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalIndex.setDescription('this corresponds to the Wellfleet circuit number') wf_ds1_interval_number = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 96))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalNumber.setDescription('1..96 where 1 is the most recent 15-minute interval and 96 is the least') wf_ds1_interval_e_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalESs.setDescription('the count of errored seconds in the specified interval') wf_ds1_interval_se_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalSESs.setDescription('the count of severely errored seconds in the specified interval') wf_ds1_interval_se_fs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 5), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalSEFs.setDescription('the count of severely errored framing seconds in the specified interval') wf_ds1_interval_ua_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 6), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalUASs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalUASs.setDescription('the number of unavailable seconds in the specified interval') wf_ds1_interval_bp_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 7), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalBPVs.setDescription('the count of bipolar violations in the specified interval') wf_ds1_interval_c_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 3, 1, 8), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1IntervalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1IntervalCVs.setDescription('the count of code violation error events in the specified interval') wf_ds1_total = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4)) if mibBuilder.loadTexts: wfDs1Total.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1Total.setDescription('The DS1 Total table') wf_ds1_total_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1)).setIndexNames((0, 'Wellfleet-DS1-MIB', 'wfDs1TotalIndex')) if mibBuilder.loadTexts: wfDs1TotalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalEntry.setDescription('per circuit DS1 total objects - wfDs1TotalIndex corresponds to Wellfleet circuit number') wf_ds1_total_index = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TotalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalIndex.setDescription('this corresponds to the Wellfleet circuit number') wf_ds1_total_e_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 2), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TotalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalESs.setDescription('total count of errored seconds') wf_ds1_total_se_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TotalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalSESs.setDescription('total count of severely errored seconds') wf_ds1_total_se_fs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TotalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalSEFs.setDescription('total count of severely errored framing seconds') wf_ds1_total_ua_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 5), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TotalUASs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalUASs.setDescription('total number of unavailable seconds') wf_ds1_total_bp_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 6), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TotalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalBPVs.setDescription('total count of bipolar violations') wf_ds1_total_c_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 4, 1, 7), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1TotalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1TotalCVs.setDescription('total count of code violation error events') wf_ds1_fe_current = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5)) if mibBuilder.loadTexts: wfDs1FeCurrent.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrent.setDescription('The DS1 Far End Current table') wf_ds1_fe_current_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1)).setIndexNames((0, 'Wellfleet-DS1-MIB', 'wfDs1FeCurrentIndex')) if mibBuilder.loadTexts: wfDs1FeCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentEntry.setDescription('per circuit DS1 far end current objects wfDs1CurrentIndex corresponds to Wellfleet circuit number') wf_ds1_fe_current_index = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentIndex.setDescription('this corresponds to the Wellfleet circuit number') wf_ds1_fe_current_e_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 2), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeCurrentESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentESs.setDescription('the count of errored seconds in the current interval') wf_ds1_fe_current_se_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 3), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeCurrentSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentSESs.setDescription('the count of severely errored seconds in the current interval') wf_ds1_fe_current_se_fs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 4), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeCurrentSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentSEFs.setDescription('the count of severely errored framing seconds in the current interval') wf_ds1_fe_current_bp_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 5), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeCurrentBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentBPVs.setDescription('the count of bipolar violations in the current interval') wf_ds1_fe_current_c_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 5, 1, 6), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeCurrentCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeCurrentCVs.setDescription('the count of code violation error events in the current interval') wf_ds1_fe_interval = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6)) if mibBuilder.loadTexts: wfDs1FeInterval.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeInterval.setDescription('The DS1 Far End Interval table') wf_ds1_fe_interval_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1)).setIndexNames((0, 'Wellfleet-DS1-MIB', 'wfDs1FeIntervalIndex'), (0, 'Wellfleet-DS1-MIB', 'wfDs1FeIntervalNumber')) if mibBuilder.loadTexts: wfDs1FeIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalEntry.setDescription('per circuit DS1 far end interval objects - wfDs1FeIntervalIndex corresponds to Wellfleet circuit number, wfDs1FeIntervalNumber is the numbered previous 15-minute interval') wf_ds1_fe_interval_index = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalIndex.setDescription('this corresponds to the Wellfleet circuit number') wf_ds1_fe_interval_number = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 96))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalNumber.setDescription('1..96 where 1 is the most recent 15-minute interval and 96 is the least') wf_ds1_fe_interval_e_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeIntervalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalESs.setDescription('the count of errored seconds in the specified interval') wf_ds1_fe_interval_se_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeIntervalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalSESs.setDescription('the count of severely errored seconds in the specified interval') wf_ds1_fe_interval_se_fs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 5), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeIntervalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalSEFs.setDescription('the count of severely errored framing seconds in the specified interval') wf_ds1_fe_interval_bp_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 6), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeIntervalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalBPVs.setDescription('the count of bipolar violations in the specified interval') wf_ds1_fe_interval_c_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 6, 1, 7), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeIntervalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeIntervalCVs.setDescription('the count of code violation error events in the specified interval') wf_ds1_fe_total = mib_table((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7)) if mibBuilder.loadTexts: wfDs1FeTotal.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotal.setDescription('The DS1 Far End Total table') wf_ds1_fe_total_entry = mib_table_row((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1)).setIndexNames((0, 'Wellfleet-DS1-MIB', 'wfDs1FeTotalIndex')) if mibBuilder.loadTexts: wfDs1FeTotalEntry.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalEntry.setDescription('per circuit DS1 far end total objects - wfDs1FeTotalIndex corresponds to Wellfleet circuit number') wf_ds1_fe_total_index = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeTotalIndex.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalIndex.setDescription('this corresponds to the Wellfleet circuit number') wf_ds1_fe_total_e_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 2), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeTotalESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalESs.setDescription('total count of errored seconds') wf_ds1_fe_total_se_ss = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeTotalSESs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalSESs.setDescription('total count of severely errored seconds') wf_ds1_fe_total_se_fs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeTotalSEFs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalSEFs.setDescription('total count of severely errored framing seconds') wf_ds1_fe_total_bp_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 5), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeTotalBPVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalBPVs.setDescription('total count of bipolar violations') wf_ds1_fe_total_c_vs = mib_table_column((1, 3, 6, 1, 4, 1, 18, 3, 4, 12, 7, 1, 6), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wfDs1FeTotalCVs.setStatus('mandatory') if mibBuilder.loadTexts: wfDs1FeTotalCVs.setDescription('total count of code violation error events') mibBuilder.exportSymbols('Wellfleet-DS1-MIB', wfDs1FeIntervalNumber=wfDs1FeIntervalNumber, wfDs1Config=wfDs1Config, wfDs1CurrentIndex=wfDs1CurrentIndex, wfDs1TotalSESs=wfDs1TotalSESs, wfDs1FeIntervalIndex=wfDs1FeIntervalIndex, wfDs1IntervalUASs=wfDs1IntervalUASs, wfDs1FeTotalIndex=wfDs1FeTotalIndex, wfDs1FeTotalEntry=wfDs1FeTotalEntry, wfDs1IntervalESs=wfDs1IntervalESs, wfDs1CurrentEntry=wfDs1CurrentEntry, wfDs1CurrentCVs=wfDs1CurrentCVs, wfDs1FeTotalESs=wfDs1FeTotalESs, wfDs1LineStatus=wfDs1LineStatus, wfDs1CurrentBPVs=wfDs1CurrentBPVs, wfDs1FeIntervalSEFs=wfDs1FeIntervalSEFs, wfDs1TotalEntry=wfDs1TotalEntry, wfDs1ValidIntervals=wfDs1ValidIntervals, wfDs1IntervalCVs=wfDs1IntervalCVs, wfDs1FeCurrentEntry=wfDs1FeCurrentEntry, wfDs1IntervalNumber=wfDs1IntervalNumber, wfDs1Interval=wfDs1Interval, wfDs1TotalCVs=wfDs1TotalCVs, wfDs1FeTotal=wfDs1FeTotal, wfDs1CurrentSEFs=wfDs1CurrentSEFs, wfDs1TotalSEFs=wfDs1TotalSEFs, wfDs1CurrentESs=wfDs1CurrentESs, wfDs1LineIndex=wfDs1LineIndex, wfDs1SendCode=wfDs1SendCode, wfDs1IntervalIndex=wfDs1IntervalIndex, wfDs1ZeroCoding=wfDs1ZeroCoding, wfDs1IntervalSESs=wfDs1IntervalSESs, wfDs1CircuitIdentifier=wfDs1CircuitIdentifier, wfDs1FeTotalCVs=wfDs1FeTotalCVs, wfDs1Total=wfDs1Total, wfDs1FeCurrentESs=wfDs1FeCurrentESs, wfDs1FeInterval=wfDs1FeInterval, wfDs1FeTotalSESs=wfDs1FeTotalSESs, wfDs1FeCurrent=wfDs1FeCurrent, wfDs1FeCurrentBPVs=wfDs1FeCurrentBPVs, wfDs1FeTotalSEFs=wfDs1FeTotalSEFs, wfDs1CurrentSESs=wfDs1CurrentSESs, wfDs1IntervalBPVs=wfDs1IntervalBPVs, wfDs1FeIntervalSESs=wfDs1FeIntervalSESs, wfDs1FeIntervalBPVs=wfDs1FeIntervalBPVs, wfDs1FeIntervalCVs=wfDs1FeIntervalCVs, wfDs1FeIntervalEntry=wfDs1FeIntervalEntry, wfDs1ConfigEntry=wfDs1ConfigEntry, wfDs1TimeElapsed=wfDs1TimeElapsed, wfDs1FeTotalBPVs=wfDs1FeTotalBPVs, wfDs1FeCurrentIndex=wfDs1FeCurrentIndex, wfDs1Current=wfDs1Current, wfDs1TotalESs=wfDs1TotalESs, wfDs1CurrentUASs=wfDs1CurrentUASs, wfDs1FeIntervalESs=wfDs1FeIntervalESs, wfDs1FeCurrentSESs=wfDs1FeCurrentSESs, wfDs1LineType=wfDs1LineType, wfDs1TotalUASs=wfDs1TotalUASs, wfDs1TotalIndex=wfDs1TotalIndex, wfDs1IntervalSEFs=wfDs1IntervalSEFs, wfDs1IntervalEntry=wfDs1IntervalEntry, wfDs1FeCurrentSEFs=wfDs1FeCurrentSEFs, wfDs1FeCurrentCVs=wfDs1FeCurrentCVs, wfDs1LoopbackConfig=wfDs1LoopbackConfig, wfDs1TotalBPVs=wfDs1TotalBPVs)
#import numpy as np """ #moving avg #Parameters array of ts value #Returns moving avg """ #def moving_average(series, n): # return np.average(series[-n:])
""" #moving avg #Parameters array of ts value #Returns moving avg """
# *args - arguments - it returns tuple # **kwargs - keyword arguments - it returns dictionary def myfunc(*args): print(args) myfunc(1,2,3,4,5,6,7,8,9,0) def myfunc1(**kwargs): print(kwargs) if 'fruit' in kwargs: print('my fruit of choice is {}'.format(kwargs['fruit'])) else: print('I did not find any fruit here') myfunc1(fruit='apple',veggie='lettuce')
def myfunc(*args): print(args) myfunc(1, 2, 3, 4, 5, 6, 7, 8, 9, 0) def myfunc1(**kwargs): print(kwargs) if 'fruit' in kwargs: print('my fruit of choice is {}'.format(kwargs['fruit'])) else: print('I did not find any fruit here') myfunc1(fruit='apple', veggie='lettuce')
def test_get_topics(client): response = client.get("/topics/") contents = response.get_json() assert contents["status"] == "OK" assert type(contents["payload"]) is dict assert type(contents["payload"]["topics"]) is list assert type(contents["payload"]["subtopics"]) is dict assert response.status_code == 200
def test_get_topics(client): response = client.get('/topics/') contents = response.get_json() assert contents['status'] == 'OK' assert type(contents['payload']) is dict assert type(contents['payload']['topics']) is list assert type(contents['payload']['subtopics']) is dict assert response.status_code == 200
""" Find an efficient algorithm to find the smallest distance (measured in number of words) between any two given words in a string. For example, given words "hello", and "world" and a text content of "dog cat hello cat dog dog hello cat world", return 1 because there's only one word "cat" in between the two words. """ def find_distance(string:str, key_word_1, key_word_2): """ This works as follows: eg. key_word_1 = hello; key_word_1 = world "dog cat hello cat dog dog hello cat world" ------------------------------------------------------------------------------- count| 0 0 0 1 2 3 0 1 0 ending_key_word | None None world world world world world world hello min_count | inf inf inf inf inf inf inf inf 1 Args: string: key_word_1: key_word_2: Returns: """ min_count = float('inf') count = 0 ending_key_word = None # initially we don't know which keyword we are looking to end the count for word in string.split(): if ending_key_word is None and word == key_word_1: # check if we should start counting ending_key_word = key_word_2 # look for key_word_2 to stop count elif ending_key_word is None and word == key_word_2: ending_key_word = key_word_1 # look for key_word_1 to stop the count elif ending_key_word == word: # when the ending keyword has been found min_count = min(count, min_count) # store the min count # now we if the the ending_key_word was: # a - key_word_1 we will now set ending_key_word=key_word_2 # b - key_word_2 we will now set ending_key_word=key_word_1 ending_key_word = key_word_2 if key_word_1 == word else key_word_1 count = 0 # reset count elif word == key_word_1 or word == key_word_2: count = 0 # reset count found a word that is possibly closer elif ending_key_word: count += 1 # while we are looking for end_key_word keep counting words return min_count if __name__ == '__main__': test_string = "dog cat hello cat dog dog hello cat world" print(find_distance(test_string, 'hello', 'world')) # ans 1 test_string = "dog cat hello cat dog dog dog cat world cat world dog dog hello" print(find_distance(test_string, 'hello', 'world')) # ans 2
""" Find an efficient algorithm to find the smallest distance (measured in number of words) between any two given words in a string. For example, given words "hello", and "world" and a text content of "dog cat hello cat dog dog hello cat world", return 1 because there's only one word "cat" in between the two words. """ def find_distance(string: str, key_word_1, key_word_2): """ This works as follows: eg. key_word_1 = hello; key_word_1 = world "dog cat hello cat dog dog hello cat world" ------------------------------------------------------------------------------- count| 0 0 0 1 2 3 0 1 0 ending_key_word | None None world world world world world world hello min_count | inf inf inf inf inf inf inf inf 1 Args: string: key_word_1: key_word_2: Returns: """ min_count = float('inf') count = 0 ending_key_word = None for word in string.split(): if ending_key_word is None and word == key_word_1: ending_key_word = key_word_2 elif ending_key_word is None and word == key_word_2: ending_key_word = key_word_1 elif ending_key_word == word: min_count = min(count, min_count) ending_key_word = key_word_2 if key_word_1 == word else key_word_1 count = 0 elif word == key_word_1 or word == key_word_2: count = 0 elif ending_key_word: count += 1 return min_count if __name__ == '__main__': test_string = 'dog cat hello cat dog dog hello cat world' print(find_distance(test_string, 'hello', 'world')) test_string = 'dog cat hello cat dog dog dog cat world cat world dog dog hello' print(find_distance(test_string, 'hello', 'world'))
# https://practice.geeksforgeeks.org/problems/number-of-palindromic-paths-in-a-matrix0819/1# # at each node recursively call itself and at bottom,left cornet determine it its a palindrome class Solution: def rec(self, matrix, it, jt, ib, jb, cache): if it > ib or jt > jb: cache[(it, jt, ib, jb)] = 0 return 0 if matrix[it][jt] != matrix[ib][jb]: cache[(it, jt, ib, jb)] = 0 return 0 if abs(it - ib) + abs(jt - jb) < 2: cache[(it, jt, ib, jb)] = 1 return 1 coun1, count2, count3, count4 = 0,0,0,0 if cache.__contains__((it+1, jt, ib-1, jb)): count1 = cache[(it+1, jt, ib-1, jb)] else: count1 = self.rec(matrix, it+1, jt, ib-1, jb, cache) if cache.__contains__((it+1, jt, ib, jb-1)): count2 = cache[(it+1, jt, ib, jb-1)] else: count2 = self.rec(matrix, it+1, jt, ib, jb-1, cache) if cache.__contains__((it, jt+1, ib-1, jb)): count3 = cache[(it, jt+1, ib-1, jb)] else: count3 = self.rec(matrix, it, jt+1, ib-1, jb, cache) if cache.__contains__((it, jt+1, ib, jb-1)): count4 = cache[(it, jt+1, ib, jb-1)] else: count4 = self.rec(matrix, it, jt+1, ib, jb-1, cache) count = count1+count2+count3+count4 cache[(it, jt, ib, jb)] = count return count def countOfPalindromicPaths(self, matrix): return self.rec(matrix, 0, 0, len(matrix)-1, len(matrix[0])-1, {}) if __name__ == '__main__': T = int(input()) for i in range(T): n, m = input().split() n = int(n); m = int(m); matrix = [] for _ in range(n): cur = input() temp = [] for __ in cur: temp.append(__) matrix.append(temp) obj = Solution() ans = obj.countOfPalindromicPaths(matrix) print(ans)
class Solution: def rec(self, matrix, it, jt, ib, jb, cache): if it > ib or jt > jb: cache[it, jt, ib, jb] = 0 return 0 if matrix[it][jt] != matrix[ib][jb]: cache[it, jt, ib, jb] = 0 return 0 if abs(it - ib) + abs(jt - jb) < 2: cache[it, jt, ib, jb] = 1 return 1 (coun1, count2, count3, count4) = (0, 0, 0, 0) if cache.__contains__((it + 1, jt, ib - 1, jb)): count1 = cache[it + 1, jt, ib - 1, jb] else: count1 = self.rec(matrix, it + 1, jt, ib - 1, jb, cache) if cache.__contains__((it + 1, jt, ib, jb - 1)): count2 = cache[it + 1, jt, ib, jb - 1] else: count2 = self.rec(matrix, it + 1, jt, ib, jb - 1, cache) if cache.__contains__((it, jt + 1, ib - 1, jb)): count3 = cache[it, jt + 1, ib - 1, jb] else: count3 = self.rec(matrix, it, jt + 1, ib - 1, jb, cache) if cache.__contains__((it, jt + 1, ib, jb - 1)): count4 = cache[it, jt + 1, ib, jb - 1] else: count4 = self.rec(matrix, it, jt + 1, ib, jb - 1, cache) count = count1 + count2 + count3 + count4 cache[it, jt, ib, jb] = count return count def count_of_palindromic_paths(self, matrix): return self.rec(matrix, 0, 0, len(matrix) - 1, len(matrix[0]) - 1, {}) if __name__ == '__main__': t = int(input()) for i in range(T): (n, m) = input().split() n = int(n) m = int(m) matrix = [] for _ in range(n): cur = input() temp = [] for __ in cur: temp.append(__) matrix.append(temp) obj = solution() ans = obj.countOfPalindromicPaths(matrix) print(ans)
# Numbers 0 to 10 print(list(range(0,11))) print() # Even numbers 0 to 10 print(list(range(0,11,2))) print() # Odd numbers 0 to 10 print(list(range(1,11,2))) print() # Numbers 20 to 10 print(list(range(20,9,-1))) print() # Numbers 45 to 75 divisable by 5 print(list(range(45, 76, 5)))
print(list(range(0, 11))) print() print(list(range(0, 11, 2))) print() print(list(range(1, 11, 2))) print() print(list(range(20, 9, -1))) print() print(list(range(45, 76, 5)))
# https://leetcode.com/problems/monotonic-array/description/ # # algorithms # Medium (42.6%) # Total Accepted: 4.8k # Total Submissions: 11.2k # beats 77.52% of python submissions class Solution(object): def largestOverlap(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: int """ length = len(A) A_1_arr, B_1_arr = [], [] for i in xrange(length): for j in xrange(length): if A[i][j] == 1: A_1_arr.append((i, j)) if B[i][j] == 1: B_1_arr.append((i, j)) res = 0 for i in xrange(length): for j in xrange(length): cnt_sum_A, cnt_sum_B = 0, 0 for x, y in A_1_arr: if x + i < length and y + j < length and B[x + i][y + j] == 1: cnt_sum_A += 1 for x, y in B_1_arr: if x + i < length and y + j < length and A[x + i][y + j] == 1: cnt_sum_B += 1 res = max(res, cnt_sum_A, cnt_sum_B) return res
class Solution(object): def largest_overlap(self, A, B): """ :type A: List[List[int]] :type B: List[List[int]] :rtype: int """ length = len(A) (a_1_arr, b_1_arr) = ([], []) for i in xrange(length): for j in xrange(length): if A[i][j] == 1: A_1_arr.append((i, j)) if B[i][j] == 1: B_1_arr.append((i, j)) res = 0 for i in xrange(length): for j in xrange(length): (cnt_sum_a, cnt_sum_b) = (0, 0) for (x, y) in A_1_arr: if x + i < length and y + j < length and (B[x + i][y + j] == 1): cnt_sum_a += 1 for (x, y) in B_1_arr: if x + i < length and y + j < length and (A[x + i][y + j] == 1): cnt_sum_b += 1 res = max(res, cnt_sum_A, cnt_sum_B) return res
term_mappings = { 'Cell': 'csvw:Cell', 'Column': 'csvw:Column', 'Datatype': 'csvw:Datatype', 'Dialect': 'csvw:Dialect', 'Direction': 'csvw:Direction', 'ForeignKey': 'csvw:ForeignKey', 'JSON': 'csvw:JSON', 'NCName': 'xsd:NCName', 'NMTOKEN': 'xsd:NMTOKEN', 'Name': 'xsd:Name', 'NumericFormat': 'csvw:NumericFormat', 'QName': 'xsd:QName', 'Row': 'csvw:Row', 'Schema': 'csvw:Schema', 'Table': 'csvw:Table', 'TableGroup': 'csvw:TableGroup', 'TableReference': 'csvw:TableReference', 'Transformation': 'csvw:Transformation', 'aboutUrl': 'csvw:aboutUrl', 'any': 'xsd:anyAtomicType', 'anyAtomicType': 'xsd:anyAtomicType', 'anyURI': 'xsd:anyURI', 'as': 'https://www.w3.org/ns/activitystreams#', 'base': 'csvw:base', 'base64Binary': 'xsd:base64Binary', 'binary': 'xsd:base64Binary', 'boolean': 'xsd:boolean', 'byte': 'xsd:byte', 'cc': 'http://creativecommons.org/ns#', 'columnReference': 'csvw:columnReference', 'columns': 'csvw:column', 'commentPrefix': 'csvw:commentPrefix', 'csvw': 'http://www.w3.org/ns/csvw#', 'ctag': 'http://commontag.org/ns#', 'datatype': 'csvw:datatype', 'date': 'xsd:date', 'dateTime': 'xsd:dateTime', 'dateTimeStamp': 'xsd:dateTimeStamp', 'datetime': 'xsd:dateTime', 'dayTimeDuration': 'xsd:dayTimeDuration', 'dc': 'http://purl.org/dc/terms/', 'dc11': 'http://purl.org/dc/elements/1.1/', 'dcat': 'http://www.w3.org/ns/dcat#', 'dcterms': 'http://purl.org/dc/terms/', 'dctypes': 'http://purl.org/dc/dcmitype/', 'decimal': 'xsd:decimal', 'decimalChar': 'csvw:decimalChar', 'default': 'csvw:default', 'delimiter': 'csvw:delimiter', 'describedby': 'wrds:describedby', 'describes': 'csvw:describes', 'dialect': 'csvw:dialect', 'double': 'xsd:double', 'doubleQuote': 'csvw:doubleQuote', 'dqv': 'http://www.w3.org/ns/dqv#', 'duration': 'xsd:duration', 'duv': 'https://www.w3.org/TR/vocab-duv#', 'encoding': 'csvw:encoding', 'float': 'xsd:float', 'foaf': 'http://xmlns.com/foaf/0.1/', 'foreignKeys': 'csvw:foreignKey', 'format': 'csvw:format', 'gDay': 'xsd:gDay', 'gMonth': 'xsd:gMonth', 'gMonthDay': 'xsd:gMonthDay', 'gYear': 'xsd:gYear', 'gYearMonth': 'xsd:gYearMonth', 'gr': 'http://purl.org/goodrelations/v1#', 'grddl': 'http://www.w3.org/2003/g/data-view#', 'groupChar': 'csvw:groupChar', 'header': 'csvw:header', 'headerRowCount': 'csvw:headerRowCount', 'hexBinary': 'xsd:hexBinary', 'html': 'rdf:HTML', 'ical': 'http://www.w3.org/2002/12/cal/icaltzd#', 'int': 'xsd:int', 'integer': 'xsd:integer', 'json': 'csvw:JSON', 'lang': 'csvw:lang', 'language': 'xsd:language', 'ldp': 'http://www.w3.org/ns/ldp#', 'length': 'csvw:length', 'license': 'xhv:license', 'lineTerminators': 'csvw:lineTerminators', 'long': 'xsd:long', 'ma': 'http://www.w3.org/ns/ma-ont#', 'maxExclusive': 'csvw:maxExclusive', 'maxInclusive': 'csvw:maxInclusive', 'maxLength': 'csvw:maxLength', 'maximum': 'csvw:maxInclusive', 'minExclusive': 'csvw:minExclusive', 'minInclusive': 'csvw:minInclusive', 'minLength': 'csvw:minLength', 'minimum': 'csvw:minInclusive', 'name': 'csvw:name', 'negativeInteger': 'xsd:negativeInteger', 'nonNegativeInteger': 'xsd:nonNegativeInteger', 'nonPositiveInteger': 'xsd:nonPositiveInteger', 'normalizedString': 'xsd:normalizedString', 'notes': 'csvw:note', 'null': 'csvw:null', 'number': 'xsd:double', 'oa': 'http://www.w3.org/ns/oa#', 'og': 'http://ogp.me/ns#', 'ordered': 'csvw:ordered', 'org': 'http://www.w3.org/ns/org#', 'owl': 'http://www.w3.org/2002/07/owl#', 'pattern': 'csvw:pattern', 'positiveInteger': 'xsd:positiveInteger', 'primaryKey': 'csvw:primaryKey', 'propertyUrl': 'csvw:propertyUrl', 'prov': 'http://www.w3.org/ns/prov#', 'qb': 'http://purl.org/linked-data/cube#', 'quoteChar': 'csvw:quoteChar', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfa': 'http://www.w3.org/ns/rdfa#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'reference': 'csvw:reference', 'referencedRows': 'csvw:referencedRow', 'required': 'csvw:required', 'resource': 'csvw:resource', 'rev': 'http://purl.org/stuff/rev#', 'rif': 'http://www.w3.org/2007/rif#', 'role': 'xhv:role', 'row': 'csvw:row', 'rowTitles': 'csvw:rowTitle', 'rownum': 'csvw:rownum', 'rr': 'http://www.w3.org/ns/r2rml#', 'schema': 'http://schema.org/', 'schemaReference': 'csvw:schemaReference', 'scriptFormat': 'csvw:scriptFormat', 'sd': 'http://www.w3.org/ns/sparql-service-description#', 'separator': 'csvw:separator', 'short': 'xsd:short', 'sioc': 'http://rdfs.org/sioc/ns#', 'skipBlankRows': 'csvw:skipBlankRows', 'skipColumns': 'csvw:skipColumns', 'skipInitialSpace': 'csvw:skipInitialSpace', 'skipRows': 'csvw:skipRows', 'skos': 'http://www.w3.org/2004/02/skos/core#', 'skosxl': 'http://www.w3.org/2008/05/skos-xl#', 'source': 'csvw:source', 'string': 'xsd:string', 'suppressOutput': 'csvw:suppressOutput', 'tableDirection': 'csvw:tableDirection', 'tableSchema': 'csvw:tableSchema', 'tables': 'csvw:table', 'targetFormat': 'csvw:targetFormat', 'textDirection': 'csvw:textDirection', 'time': 'xsd:time', 'titles': 'csvw:title', 'token': 'xsd:token', 'transformations': 'csvw:transformations', 'trim': 'csvw:trim', 'unsignedByte': 'xsd:unsignedByte', 'unsignedInt': 'xsd:unsignedInt', 'unsignedLong': 'xsd:unsignedLong', 'unsignedShort': 'xsd:unsignedShort', 'uriTemplate': 'csvw:uriTemplate', 'url': 'csvw:url', 'v': 'http://rdf.data-vocabulary.org/#', 'valueUrl': 'csvw:valueUrl', 'vcard': 'http://www.w3.org/2006/vcard/ns#', 'virtual': 'csvw:virtual', 'void': 'http://rdfs.org/ns/void#', 'wdr': 'http://www.w3.org/2007/05/powder#', 'wrds': 'http://www.w3.org/2007/05/powder-s#', 'xhv': 'http://www.w3.org/1999/xhtml/vocab#', 'xml': 'rdf:XMLLiteral', 'xsd': 'http://www.w3.org/2001/XMLSchema#', 'yearMonthDuration': 'xsd:yearMonthDuration', } core_group_of_tables_annotations = ['id', 'notes', 'tables'] core_table_annotations = ['columns', 'tableDirection', 'foreignKeys', 'id', 'notes', 'rows', 'schema', 'suppressOutput', 'transformations', 'url'] core_column_annotations = ['aboutUrl', 'cells', 'datatype', 'default', 'lang', 'name', 'null', 'number', 'ordered', 'propertyUrl', 'required', 'separator', 'sourceNumber', 'suppressOutput', 'table', 'textDirection', 'titles', 'valueUrl', 'virtual'] core_row_annotations = ['cells', 'number', 'primaryKey', 'titles', 'referencedRows', 'sourceNumber', 'table'] schema_description = ['columns', 'foreignKeys', 'primaryKey', 'rowTitles', '@type', '@id'] def is_non_core_annotation(name): return name not in core_group_of_tables_annotations \ and name not in core_table_annotations \ and name not in core_column_annotations \ and name not in core_row_annotations \ and name not in schema_description CONST_STANDARD_MODE = 'standard' CONST_MINIMAL_MODE = 'minimal' core_group_of_tables_properties = ['tables', 'dialect', 'notes', 'tableDirection', 'tableSchema', 'transformations', '@id', '@type', '@context'] core_table_properties = ['url', 'dialect', 'notes', 'suppressOutput', 'tableDirection', 'tableSchema', 'transformations', '@id', '@type'] inherited_properties = ['aboutUrl', 'datatype', 'default', 'lang', 'null', 'ordered', 'propertyUrl', 'required', 'separator', 'textDirection', 'valueUrl'] array_properties = ['tables', 'transformations', '@context', 'notes', 'foreignKeys', 'columns', 'lineTerminators'] array_property_item_types = { 'columns': dict, 'foreignKeys': dict, 'lineTerminators': str, 'notes': dict, 'transformations': dict, 'tables': dict, } number_datatypes = ['decimal', 'integer', 'integer', 'long', 'int', 'short', 'byte', 'nonNegativeInteger', 'positiveInteger', 'unsignedLong', 'unsignedInt', 'unsignedShort', 'unsignedByte', 'nonPositiveInteger', 'negativeInteger', 'double', 'number', 'duration', 'dayTimeDuration', 'yearMonthDuration', 'float'] date_datatypes = ['date', 'dateTime', 'datetime', 'dateTimeStamp'] fields_properties = { 'transformations': {'url': True, 'scriptFormat': True, 'targetFormat': True, 'source': False, 'titles': False, '@id': False, '@type': True}, 'tableGroup': {'tables': True, 'dialect': False, 'notes': False, 'tableDirection': False, 'tableSchema': False, 'transformations': False, '@id': False, '@type': False, '@context': True}, 'tables': {'url': True, 'dialect': False, 'notes': False, 'suppressOutput': False, 'tableDirection': False, 'transformations': False, 'tableSchema': False, '@id': False, '@type': False}, 'columns': {'name': False, 'suppressOutput': False, 'titles': False, 'virtual': False, '@id': False, '@type': False, } }
term_mappings = {'Cell': 'csvw:Cell', 'Column': 'csvw:Column', 'Datatype': 'csvw:Datatype', 'Dialect': 'csvw:Dialect', 'Direction': 'csvw:Direction', 'ForeignKey': 'csvw:ForeignKey', 'JSON': 'csvw:JSON', 'NCName': 'xsd:NCName', 'NMTOKEN': 'xsd:NMTOKEN', 'Name': 'xsd:Name', 'NumericFormat': 'csvw:NumericFormat', 'QName': 'xsd:QName', 'Row': 'csvw:Row', 'Schema': 'csvw:Schema', 'Table': 'csvw:Table', 'TableGroup': 'csvw:TableGroup', 'TableReference': 'csvw:TableReference', 'Transformation': 'csvw:Transformation', 'aboutUrl': 'csvw:aboutUrl', 'any': 'xsd:anyAtomicType', 'anyAtomicType': 'xsd:anyAtomicType', 'anyURI': 'xsd:anyURI', 'as': 'https://www.w3.org/ns/activitystreams#', 'base': 'csvw:base', 'base64Binary': 'xsd:base64Binary', 'binary': 'xsd:base64Binary', 'boolean': 'xsd:boolean', 'byte': 'xsd:byte', 'cc': 'http://creativecommons.org/ns#', 'columnReference': 'csvw:columnReference', 'columns': 'csvw:column', 'commentPrefix': 'csvw:commentPrefix', 'csvw': 'http://www.w3.org/ns/csvw#', 'ctag': 'http://commontag.org/ns#', 'datatype': 'csvw:datatype', 'date': 'xsd:date', 'dateTime': 'xsd:dateTime', 'dateTimeStamp': 'xsd:dateTimeStamp', 'datetime': 'xsd:dateTime', 'dayTimeDuration': 'xsd:dayTimeDuration', 'dc': 'http://purl.org/dc/terms/', 'dc11': 'http://purl.org/dc/elements/1.1/', 'dcat': 'http://www.w3.org/ns/dcat#', 'dcterms': 'http://purl.org/dc/terms/', 'dctypes': 'http://purl.org/dc/dcmitype/', 'decimal': 'xsd:decimal', 'decimalChar': 'csvw:decimalChar', 'default': 'csvw:default', 'delimiter': 'csvw:delimiter', 'describedby': 'wrds:describedby', 'describes': 'csvw:describes', 'dialect': 'csvw:dialect', 'double': 'xsd:double', 'doubleQuote': 'csvw:doubleQuote', 'dqv': 'http://www.w3.org/ns/dqv#', 'duration': 'xsd:duration', 'duv': 'https://www.w3.org/TR/vocab-duv#', 'encoding': 'csvw:encoding', 'float': 'xsd:float', 'foaf': 'http://xmlns.com/foaf/0.1/', 'foreignKeys': 'csvw:foreignKey', 'format': 'csvw:format', 'gDay': 'xsd:gDay', 'gMonth': 'xsd:gMonth', 'gMonthDay': 'xsd:gMonthDay', 'gYear': 'xsd:gYear', 'gYearMonth': 'xsd:gYearMonth', 'gr': 'http://purl.org/goodrelations/v1#', 'grddl': 'http://www.w3.org/2003/g/data-view#', 'groupChar': 'csvw:groupChar', 'header': 'csvw:header', 'headerRowCount': 'csvw:headerRowCount', 'hexBinary': 'xsd:hexBinary', 'html': 'rdf:HTML', 'ical': 'http://www.w3.org/2002/12/cal/icaltzd#', 'int': 'xsd:int', 'integer': 'xsd:integer', 'json': 'csvw:JSON', 'lang': 'csvw:lang', 'language': 'xsd:language', 'ldp': 'http://www.w3.org/ns/ldp#', 'length': 'csvw:length', 'license': 'xhv:license', 'lineTerminators': 'csvw:lineTerminators', 'long': 'xsd:long', 'ma': 'http://www.w3.org/ns/ma-ont#', 'maxExclusive': 'csvw:maxExclusive', 'maxInclusive': 'csvw:maxInclusive', 'maxLength': 'csvw:maxLength', 'maximum': 'csvw:maxInclusive', 'minExclusive': 'csvw:minExclusive', 'minInclusive': 'csvw:minInclusive', 'minLength': 'csvw:minLength', 'minimum': 'csvw:minInclusive', 'name': 'csvw:name', 'negativeInteger': 'xsd:negativeInteger', 'nonNegativeInteger': 'xsd:nonNegativeInteger', 'nonPositiveInteger': 'xsd:nonPositiveInteger', 'normalizedString': 'xsd:normalizedString', 'notes': 'csvw:note', 'null': 'csvw:null', 'number': 'xsd:double', 'oa': 'http://www.w3.org/ns/oa#', 'og': 'http://ogp.me/ns#', 'ordered': 'csvw:ordered', 'org': 'http://www.w3.org/ns/org#', 'owl': 'http://www.w3.org/2002/07/owl#', 'pattern': 'csvw:pattern', 'positiveInteger': 'xsd:positiveInteger', 'primaryKey': 'csvw:primaryKey', 'propertyUrl': 'csvw:propertyUrl', 'prov': 'http://www.w3.org/ns/prov#', 'qb': 'http://purl.org/linked-data/cube#', 'quoteChar': 'csvw:quoteChar', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfa': 'http://www.w3.org/ns/rdfa#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'reference': 'csvw:reference', 'referencedRows': 'csvw:referencedRow', 'required': 'csvw:required', 'resource': 'csvw:resource', 'rev': 'http://purl.org/stuff/rev#', 'rif': 'http://www.w3.org/2007/rif#', 'role': 'xhv:role', 'row': 'csvw:row', 'rowTitles': 'csvw:rowTitle', 'rownum': 'csvw:rownum', 'rr': 'http://www.w3.org/ns/r2rml#', 'schema': 'http://schema.org/', 'schemaReference': 'csvw:schemaReference', 'scriptFormat': 'csvw:scriptFormat', 'sd': 'http://www.w3.org/ns/sparql-service-description#', 'separator': 'csvw:separator', 'short': 'xsd:short', 'sioc': 'http://rdfs.org/sioc/ns#', 'skipBlankRows': 'csvw:skipBlankRows', 'skipColumns': 'csvw:skipColumns', 'skipInitialSpace': 'csvw:skipInitialSpace', 'skipRows': 'csvw:skipRows', 'skos': 'http://www.w3.org/2004/02/skos/core#', 'skosxl': 'http://www.w3.org/2008/05/skos-xl#', 'source': 'csvw:source', 'string': 'xsd:string', 'suppressOutput': 'csvw:suppressOutput', 'tableDirection': 'csvw:tableDirection', 'tableSchema': 'csvw:tableSchema', 'tables': 'csvw:table', 'targetFormat': 'csvw:targetFormat', 'textDirection': 'csvw:textDirection', 'time': 'xsd:time', 'titles': 'csvw:title', 'token': 'xsd:token', 'transformations': 'csvw:transformations', 'trim': 'csvw:trim', 'unsignedByte': 'xsd:unsignedByte', 'unsignedInt': 'xsd:unsignedInt', 'unsignedLong': 'xsd:unsignedLong', 'unsignedShort': 'xsd:unsignedShort', 'uriTemplate': 'csvw:uriTemplate', 'url': 'csvw:url', 'v': 'http://rdf.data-vocabulary.org/#', 'valueUrl': 'csvw:valueUrl', 'vcard': 'http://www.w3.org/2006/vcard/ns#', 'virtual': 'csvw:virtual', 'void': 'http://rdfs.org/ns/void#', 'wdr': 'http://www.w3.org/2007/05/powder#', 'wrds': 'http://www.w3.org/2007/05/powder-s#', 'xhv': 'http://www.w3.org/1999/xhtml/vocab#', 'xml': 'rdf:XMLLiteral', 'xsd': 'http://www.w3.org/2001/XMLSchema#', 'yearMonthDuration': 'xsd:yearMonthDuration'} core_group_of_tables_annotations = ['id', 'notes', 'tables'] core_table_annotations = ['columns', 'tableDirection', 'foreignKeys', 'id', 'notes', 'rows', 'schema', 'suppressOutput', 'transformations', 'url'] core_column_annotations = ['aboutUrl', 'cells', 'datatype', 'default', 'lang', 'name', 'null', 'number', 'ordered', 'propertyUrl', 'required', 'separator', 'sourceNumber', 'suppressOutput', 'table', 'textDirection', 'titles', 'valueUrl', 'virtual'] core_row_annotations = ['cells', 'number', 'primaryKey', 'titles', 'referencedRows', 'sourceNumber', 'table'] schema_description = ['columns', 'foreignKeys', 'primaryKey', 'rowTitles', '@type', '@id'] def is_non_core_annotation(name): return name not in core_group_of_tables_annotations and name not in core_table_annotations and (name not in core_column_annotations) and (name not in core_row_annotations) and (name not in schema_description) const_standard_mode = 'standard' const_minimal_mode = 'minimal' core_group_of_tables_properties = ['tables', 'dialect', 'notes', 'tableDirection', 'tableSchema', 'transformations', '@id', '@type', '@context'] core_table_properties = ['url', 'dialect', 'notes', 'suppressOutput', 'tableDirection', 'tableSchema', 'transformations', '@id', '@type'] inherited_properties = ['aboutUrl', 'datatype', 'default', 'lang', 'null', 'ordered', 'propertyUrl', 'required', 'separator', 'textDirection', 'valueUrl'] array_properties = ['tables', 'transformations', '@context', 'notes', 'foreignKeys', 'columns', 'lineTerminators'] array_property_item_types = {'columns': dict, 'foreignKeys': dict, 'lineTerminators': str, 'notes': dict, 'transformations': dict, 'tables': dict} number_datatypes = ['decimal', 'integer', 'integer', 'long', 'int', 'short', 'byte', 'nonNegativeInteger', 'positiveInteger', 'unsignedLong', 'unsignedInt', 'unsignedShort', 'unsignedByte', 'nonPositiveInteger', 'negativeInteger', 'double', 'number', 'duration', 'dayTimeDuration', 'yearMonthDuration', 'float'] date_datatypes = ['date', 'dateTime', 'datetime', 'dateTimeStamp'] fields_properties = {'transformations': {'url': True, 'scriptFormat': True, 'targetFormat': True, 'source': False, 'titles': False, '@id': False, '@type': True}, 'tableGroup': {'tables': True, 'dialect': False, 'notes': False, 'tableDirection': False, 'tableSchema': False, 'transformations': False, '@id': False, '@type': False, '@context': True}, 'tables': {'url': True, 'dialect': False, 'notes': False, 'suppressOutput': False, 'tableDirection': False, 'transformations': False, 'tableSchema': False, '@id': False, '@type': False}, 'columns': {'name': False, 'suppressOutput': False, 'titles': False, 'virtual': False, '@id': False, '@type': False}}
expected_number_of_transactions = [ 2650, 2543, 1395, 2751, 2398, 2827, 2737, 3084, 1998, 2997, 976, 1929, 3268, 1904, 1772, 776, 2553, 2547, 2581, 2226, 2307, 2812, 2618, 177, 1538, 1990, 2323, 2613, 2503, 2140, 2542, 2291, 2782, 1994, 2513, 2773, 1359, 1744, 868, 896, 2228, 2300, 2349, 2440, 2562, 2123, 3150, 2564, 1590, 349, 2049, 1978, 2687, 2330, 1492, 1968, 2610, 2228, 1581, 2204, 1837, 2565, 2375, 2422, 1808, 2662, 2760, 1507, 2753, 2067, 2786, 1677, 2622, 2319, 17, 2144, 922, 2123, 2379, 2798, 2197, 2060, 2081, 2257, 2728, 2689, 2103, 2218, 960, 1397, 479, 913, 87, 1682, 2032, 2307, 2579, 229, 817, 1457, 1822, 1353, 907, 912, 1413, 2469, 2293, 2396, 1087, 970, 1363, 2305, 2319, 2192, 2320, 2804, 2936, 2627, 2242, 2068, 2630, 2366, 2494, 2191, 2598, 1933, 1236, 1380, 985, 2507, 2003, 586, 1223, 1120, 2119, 2401, 1706, 739, 1378, 960, 1751, 2553, 2312, 2392 ] expected_block_sizes = [ 1340282.0, 1171564.8, 1290236.0, 1374338.4, 1306336.8333333333, 1114189.7272727273, 1334556.3333333333, 1072760.4, 1190087.0, 1316951.0, 1258290.5, 1263454.6666666667, 1261141.25, 1350125.8, 1387607.0, 1215300.1666666667, 828290.3333333334, 1227950.5, 1287358.3333333333, 925557.1666666666, 1215318.111111111, 1523156.4444444445, 1278528.75, 1411428.0, 1315790.6666666667, 1019578.3, 990839.5 ] expected_hourly_transactions = [ 2650, 11914, 7819, 11074, 12455, 23563, 7067, 9257, 18048, 2564, 10983, 6070, 7850, 11832, 2760, 13412, 4480, 12479, 14076, 5518, 13503, 15208, 19508, 7490, 6722, 15560, 13791 ] expected_times_between_blocks = [ 1612, 93, 242, 1294, 1704, 586, 789, 1969, 403, 228, 116, 23, 2398, 850, 864, 340, 185, 24, 1802, 812, 203, 887, 677, 45, 194, 73, 366, 125, 76, 456, 1035, 236, 1450, 1123, 872, 1669, 110, 725, 186, 10, 85, 291, 252, 279, 1380, 180, 3919, 1201, 218, 102, 791, 257, 233, 1721, 773, 433, 2865, 343, 410, 2042, 285, 121, 1515, 851, 135, 977, 4108, 43, 1585, 177, 249, 759, 1361, 2200, 2, 530, 23, 496, 626, 459, 1125, 1305, 639, 45, 884, 47, 1069, 813, 158, 1963, 122, 239, 21, 443, 158, 1002, 807, 65, 66, 525, 461, 284, 170, 63, 172, 714, 1043, 815, 259, 184, 98, 521, 582, 922, 40, 430, 181, 431, 526, 1225, 829, 1015, 1220, 2161, 175, 1224, 347, 372, 253, 224, 699, 152, 388, 204, 162, 1277, 483, 178, 337, 68, 452, 75, 701 ] expected_transaction_values = [ 11383.94878785999, 17308.05367398, 3622.7728769900023, 9633.670801730033, 14826.62779696996, 7259.995884540011, 11203.150786679953, 29506.748038190017, 16576.26348286996, 13175.761536749957, 8641.552318090005, 4003.4319120199984, 25662.060170189954, 10444.260513739988, 7554.059845370009, 4268.25902016, 2472.864963509989, 4077.0395888499947, 12750.97627863001, 12355.883847110006, 2393.240527540009, 8622.960466979994, 5447.26763365, 87.38996292999992, 2605.2993410000067, 1471.356488039999, 3053.277851210003, 2625.0749443800064, 1072.1113604599975, 5041.109816149992, 9713.188765789986, 3266.108440949993, 11768.000924819953, 13569.830664560017, 7538.576938960003, 13569.767463059985, 844.6543596399998, 5331.023938179994, 848.165141919999, 967.1358015199999, 1010.1064013400085, 5567.299901390007, 1625.9675534700016, 2253.125553860004, 7658.386822249995, 8384.54668757001, 19206.147882259953, 4469.351264000007, 1315.0544174199972, 432.19316666, 6127.310503930018, 2066.3867831300004, 1872.9193954999962, 8815.472050029986, 2843.420696440003, 4687.6417044999835, 16042.92928003998, 1382.5175280100018, 8815.100493969989, 14234.330114909988, 1557.5183457699975, 685.3837385100013, 8590.53198090003, 4053.731241960002, 4720.6605097500005, 9639.943570420017, 11608.579181260073, 988.918982430001, 6871.058338240004, 989.8308203200012, 1580.3052625199962, 10245.606500710022, 5184.384621690003, 11088.598342719983, 8.966610300000001, 3152.560446030012, 194.15356827999992, 1916.1249402400003, 2332.781637169996, 1904.5502168199978, 4478.237747329994, 3766.84221378, 2647.122554909998, 1194.9242250000002, 3695.6209336000006, 1154.9818379700005, 9400.906267190016, 6496.324190000008, 1501.6140470199998, 19201.642837140032, 1197.2633540199993, 1833.1202640199983, 78.32123893999999, 1376.2240791900024, 976.7801730400008, 3321.5335948599977, 3486.9283997099947, 129.03544430000005, 1922.221544139999, 2939.189555250006, 5593.631477060008, 2429.757580759996, 2298.759065579999, 703.1883488999998, 1117.6024098399996, 5161.379796689989, 5459.422803130007, 4495.1067846999795, 4045.725931109999, 1516.9282807899995, 854.3813730699983, 1992.721841120003, 4143.047950169987, 5249.556289420004, 1518.8253502700004, 4252.785797819985, 1540.4489411699933, 3430.193032909998, 4144.407905429995, 6595.714538640011, 6396.9363644500345, 9235.605561159991, 8098.343213619993, 11370.341906110016, 1631.5964133900047, 7494.17682190998, 1991.0408088299973, 1646.4867985599997, 5561.463178049983, 1584.26847222, 4428.548573870004, 510.3291968700005, 1558.24513197, 2942.867825329997, 1391.3934453300005, 7026.66253513999, 3573.887328660006, 1833.9685547500019, 4669.513988809994, 587.4164939700005, 2331.6464144200054, 1765.9344505200047, 6876.602656040003, 11012.55110367002 ]
expected_number_of_transactions = [2650, 2543, 1395, 2751, 2398, 2827, 2737, 3084, 1998, 2997, 976, 1929, 3268, 1904, 1772, 776, 2553, 2547, 2581, 2226, 2307, 2812, 2618, 177, 1538, 1990, 2323, 2613, 2503, 2140, 2542, 2291, 2782, 1994, 2513, 2773, 1359, 1744, 868, 896, 2228, 2300, 2349, 2440, 2562, 2123, 3150, 2564, 1590, 349, 2049, 1978, 2687, 2330, 1492, 1968, 2610, 2228, 1581, 2204, 1837, 2565, 2375, 2422, 1808, 2662, 2760, 1507, 2753, 2067, 2786, 1677, 2622, 2319, 17, 2144, 922, 2123, 2379, 2798, 2197, 2060, 2081, 2257, 2728, 2689, 2103, 2218, 960, 1397, 479, 913, 87, 1682, 2032, 2307, 2579, 229, 817, 1457, 1822, 1353, 907, 912, 1413, 2469, 2293, 2396, 1087, 970, 1363, 2305, 2319, 2192, 2320, 2804, 2936, 2627, 2242, 2068, 2630, 2366, 2494, 2191, 2598, 1933, 1236, 1380, 985, 2507, 2003, 586, 1223, 1120, 2119, 2401, 1706, 739, 1378, 960, 1751, 2553, 2312, 2392] expected_block_sizes = [1340282.0, 1171564.8, 1290236.0, 1374338.4, 1306336.8333333333, 1114189.7272727273, 1334556.3333333333, 1072760.4, 1190087.0, 1316951.0, 1258290.5, 1263454.6666666667, 1261141.25, 1350125.8, 1387607.0, 1215300.1666666667, 828290.3333333334, 1227950.5, 1287358.3333333333, 925557.1666666666, 1215318.111111111, 1523156.4444444445, 1278528.75, 1411428.0, 1315790.6666666667, 1019578.3, 990839.5] expected_hourly_transactions = [2650, 11914, 7819, 11074, 12455, 23563, 7067, 9257, 18048, 2564, 10983, 6070, 7850, 11832, 2760, 13412, 4480, 12479, 14076, 5518, 13503, 15208, 19508, 7490, 6722, 15560, 13791] expected_times_between_blocks = [1612, 93, 242, 1294, 1704, 586, 789, 1969, 403, 228, 116, 23, 2398, 850, 864, 340, 185, 24, 1802, 812, 203, 887, 677, 45, 194, 73, 366, 125, 76, 456, 1035, 236, 1450, 1123, 872, 1669, 110, 725, 186, 10, 85, 291, 252, 279, 1380, 180, 3919, 1201, 218, 102, 791, 257, 233, 1721, 773, 433, 2865, 343, 410, 2042, 285, 121, 1515, 851, 135, 977, 4108, 43, 1585, 177, 249, 759, 1361, 2200, 2, 530, 23, 496, 626, 459, 1125, 1305, 639, 45, 884, 47, 1069, 813, 158, 1963, 122, 239, 21, 443, 158, 1002, 807, 65, 66, 525, 461, 284, 170, 63, 172, 714, 1043, 815, 259, 184, 98, 521, 582, 922, 40, 430, 181, 431, 526, 1225, 829, 1015, 1220, 2161, 175, 1224, 347, 372, 253, 224, 699, 152, 388, 204, 162, 1277, 483, 178, 337, 68, 452, 75, 701] expected_transaction_values = [11383.94878785999, 17308.05367398, 3622.7728769900023, 9633.670801730033, 14826.62779696996, 7259.995884540011, 11203.150786679953, 29506.748038190017, 16576.26348286996, 13175.761536749957, 8641.552318090005, 4003.4319120199984, 25662.060170189954, 10444.260513739988, 7554.059845370009, 4268.25902016, 2472.864963509989, 4077.0395888499947, 12750.97627863001, 12355.883847110006, 2393.240527540009, 8622.960466979994, 5447.26763365, 87.38996292999992, 2605.2993410000067, 1471.356488039999, 3053.277851210003, 2625.0749443800064, 1072.1113604599975, 5041.109816149992, 9713.188765789986, 3266.108440949993, 11768.000924819953, 13569.830664560017, 7538.576938960003, 13569.767463059985, 844.6543596399998, 5331.023938179994, 848.165141919999, 967.1358015199999, 1010.1064013400085, 5567.299901390007, 1625.9675534700016, 2253.125553860004, 7658.386822249995, 8384.54668757001, 19206.147882259953, 4469.351264000007, 1315.0544174199972, 432.19316666, 6127.310503930018, 2066.3867831300004, 1872.9193954999962, 8815.472050029986, 2843.420696440003, 4687.6417044999835, 16042.92928003998, 1382.5175280100018, 8815.100493969989, 14234.330114909988, 1557.5183457699975, 685.3837385100013, 8590.53198090003, 4053.731241960002, 4720.6605097500005, 9639.943570420017, 11608.579181260073, 988.918982430001, 6871.058338240004, 989.8308203200012, 1580.3052625199962, 10245.606500710022, 5184.384621690003, 11088.598342719983, 8.966610300000001, 3152.560446030012, 194.15356827999992, 1916.1249402400003, 2332.781637169996, 1904.5502168199978, 4478.237747329994, 3766.84221378, 2647.122554909998, 1194.9242250000002, 3695.6209336000006, 1154.9818379700005, 9400.906267190016, 6496.324190000008, 1501.6140470199998, 19201.642837140032, 1197.2633540199993, 1833.1202640199983, 78.32123893999999, 1376.2240791900024, 976.7801730400008, 3321.5335948599977, 3486.9283997099947, 129.03544430000005, 1922.221544139999, 2939.189555250006, 5593.631477060008, 2429.757580759996, 2298.759065579999, 703.1883488999998, 1117.6024098399996, 5161.379796689989, 5459.422803130007, 4495.1067846999795, 4045.725931109999, 1516.9282807899995, 854.3813730699983, 1992.721841120003, 4143.047950169987, 5249.556289420004, 1518.8253502700004, 4252.785797819985, 1540.4489411699933, 3430.193032909998, 4144.407905429995, 6595.714538640011, 6396.9363644500345, 9235.605561159991, 8098.343213619993, 11370.341906110016, 1631.5964133900047, 7494.17682190998, 1991.0408088299973, 1646.4867985599997, 5561.463178049983, 1584.26847222, 4428.548573870004, 510.3291968700005, 1558.24513197, 2942.867825329997, 1391.3934453300005, 7026.66253513999, 3573.887328660006, 1833.9685547500019, 4669.513988809994, 587.4164939700005, 2331.6464144200054, 1765.9344505200047, 6876.602656040003, 11012.55110367002]
files_c=[ 'C/Threads.c', ] files_cpp=[ 'CPP/7zip/UI/P7ZIP/wxP7ZIP.cpp', 'CPP/Common/IntToString.cpp', 'CPP/Common/MyString.cpp', 'CPP/Common/MyVector.cpp', 'CPP/Common/StringConvert.cpp', 'CPP/Windows/FileDir.cpp', 'CPP/Windows/FileFind.cpp', 'CPP/Windows/FileIO.cpp', 'CPP/Windows/FileName.cpp', 'CPP/Common/MyWindows.cpp', 'CPP/myWindows/wine_date_and_time.cpp', ]
files_c = ['C/Threads.c'] files_cpp = ['CPP/7zip/UI/P7ZIP/wxP7ZIP.cpp', 'CPP/Common/IntToString.cpp', 'CPP/Common/MyString.cpp', 'CPP/Common/MyVector.cpp', 'CPP/Common/StringConvert.cpp', 'CPP/Windows/FileDir.cpp', 'CPP/Windows/FileFind.cpp', 'CPP/Windows/FileIO.cpp', 'CPP/Windows/FileName.cpp', 'CPP/Common/MyWindows.cpp', 'CPP/myWindows/wine_date_and_time.cpp']
# Medium # https://leetcode.com/problems/spiral-matrix/ # Time Complexity: O(N) # Space Complexity: 0(1) class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: return Solution.spiralsol(matrix, []) @staticmethod def spiralsol(matrix, res): m = len(matrix) if m == 0: return res n = len(matrix[0]) if n == 0: return res res += matrix[0] if m > 1: res += [matrix[i][n - 1] for i in range(1, m - 1)] res += matrix[m - 1][::-1] if n > 1: res += [matrix[i][0] for i in range(m - 2, 0, -1)] matrix = matrix[1:m - 1] for index, row in enumerate(matrix): matrix[index] = row[1:n-1] Solution.spiralsol(matrix, res) return res
class Solution: def spiral_order(self, matrix: List[List[int]]) -> List[int]: return Solution.spiralsol(matrix, []) @staticmethod def spiralsol(matrix, res): m = len(matrix) if m == 0: return res n = len(matrix[0]) if n == 0: return res res += matrix[0] if m > 1: res += [matrix[i][n - 1] for i in range(1, m - 1)] res += matrix[m - 1][::-1] if n > 1: res += [matrix[i][0] for i in range(m - 2, 0, -1)] matrix = matrix[1:m - 1] for (index, row) in enumerate(matrix): matrix[index] = row[1:n - 1] Solution.spiralsol(matrix, res) return res
# https://www.reddit.com/wiki/bottiquette omit /r/suicidewatch and /r/depression # note: lowercase for case insensitive match blacklist = [ # https://www.reddit.com/r/Bottiquette/wiki/robots_txt_json "anime", "asianamerican", "askhistorians", "askscience", "askreddit", "aww", "chicagosuburbs", "cosplay", "cumberbitches", "d3gf", "deer", "depression", "depthhub", "drinkingdollars", "forwardsfromgrandma", "geckos", "giraffes", "grindsmygears", "indianfetish", "me_irl", "misc", "movies", "mixedbreeds", "news", "newtotf2", "omaha", "petstacking", "pics", "pigs", "politicaldiscussion", "politics", "programmingcirclejerk", "raerthdev", "rants", "runningcirclejerk", "salvia", "science", "seiko", "shoplifting", "sketches", "sociopath", "suicidewatch", "talesfromtechsupport", "torrent", "torrents", "trackers", "tr4shbros", "unitedkingdom", "crucibleplaybook", "cassetteculture", "italy_SS", "DimmiOuija", # no bots allowed but not on bottiquette "todayilearned", # non-english speaking "hololive", "internetbrasil", "puebla", "chile", "saintrampalji", # needs more karma "centrist", "conspiracy", # handle timestamp in youtube title "dauntless", # timestamps usually not a skip point "speedrun", ] min_karma_dict = {"superstonk": 1200}
blacklist = ['anime', 'asianamerican', 'askhistorians', 'askscience', 'askreddit', 'aww', 'chicagosuburbs', 'cosplay', 'cumberbitches', 'd3gf', 'deer', 'depression', 'depthhub', 'drinkingdollars', 'forwardsfromgrandma', 'geckos', 'giraffes', 'grindsmygears', 'indianfetish', 'me_irl', 'misc', 'movies', 'mixedbreeds', 'news', 'newtotf2', 'omaha', 'petstacking', 'pics', 'pigs', 'politicaldiscussion', 'politics', 'programmingcirclejerk', 'raerthdev', 'rants', 'runningcirclejerk', 'salvia', 'science', 'seiko', 'shoplifting', 'sketches', 'sociopath', 'suicidewatch', 'talesfromtechsupport', 'torrent', 'torrents', 'trackers', 'tr4shbros', 'unitedkingdom', 'crucibleplaybook', 'cassetteculture', 'italy_SS', 'DimmiOuija', 'todayilearned', 'hololive', 'internetbrasil', 'puebla', 'chile', 'saintrampalji', 'centrist', 'conspiracy', 'dauntless', 'speedrun'] min_karma_dict = {'superstonk': 1200}
load("//bazel/rules/cpp:object.bzl", "cpp_object") load("//bazel/rules/hcp:hcp.bzl", "hcp") load("//bazel/rules/hcp:hcp_hdrs_derive.bzl", "hcp_hdrs_derive") def string_tree_to_static_tree_parser(name): #the file names to use target_name = name + "_string_tree_parser_dat" in_file = name + ".dat" outfile = name + "_string_tree_parser.hcp" #converting hcp to hpp/cpp native.genrule( name = target_name, srcs = [in_file], outs = [outfile], tools = ["//code/programs/transcompilers/tree_hcp/string_tree_to_static_tree_parser:string_tree_to_static_tree_parser"], cmd = "$(location //code/programs/transcompilers/tree_hcp/string_tree_to_static_tree_parser:string_tree_to_static_tree_parser) -i $(SRCS) -o $@", ) #compile hcp file #unique dep (TODO: dynamically decide) static_struct_dep = "//code/utilities/code:concept_static_tree_structs" deps = [ "//code/utilities/data_structures/tree/generic:string_tree", "//code/utilities/data_structures/tree/generic:string_to_string_tree", "//code/utilities/types/strings/transformers/appending:lib", "//code/utilities/data_structures/tree/generic/tokens:tree_token", "//code/utilities/types/vectors/observers:lib", static_struct_dep, ] hcp(name + "_string_tree_parser", deps)
load('//bazel/rules/cpp:object.bzl', 'cpp_object') load('//bazel/rules/hcp:hcp.bzl', 'hcp') load('//bazel/rules/hcp:hcp_hdrs_derive.bzl', 'hcp_hdrs_derive') def string_tree_to_static_tree_parser(name): target_name = name + '_string_tree_parser_dat' in_file = name + '.dat' outfile = name + '_string_tree_parser.hcp' native.genrule(name=target_name, srcs=[in_file], outs=[outfile], tools=['//code/programs/transcompilers/tree_hcp/string_tree_to_static_tree_parser:string_tree_to_static_tree_parser'], cmd='$(location //code/programs/transcompilers/tree_hcp/string_tree_to_static_tree_parser:string_tree_to_static_tree_parser) -i $(SRCS) -o $@') static_struct_dep = '//code/utilities/code:concept_static_tree_structs' deps = ['//code/utilities/data_structures/tree/generic:string_tree', '//code/utilities/data_structures/tree/generic:string_to_string_tree', '//code/utilities/types/strings/transformers/appending:lib', '//code/utilities/data_structures/tree/generic/tokens:tree_token', '//code/utilities/types/vectors/observers:lib', static_struct_dep] hcp(name + '_string_tree_parser', deps)
class BaseServerException(Exception): def __init__(self, detail, status_code, message): super().__init__(message) self.detail = detail self.status_code = status_code class SearchFieldRequiered(BaseServerException): def __init__(self): super().__init__(detail='entity', status_code=404, message='Search field required')
class Baseserverexception(Exception): def __init__(self, detail, status_code, message): super().__init__(message) self.detail = detail self.status_code = status_code class Searchfieldrequiered(BaseServerException): def __init__(self): super().__init__(detail='entity', status_code=404, message='Search field required')
class Solution: def nextGreaterElement(self, n: int) -> int: s = list(str(n)) i = len(s) - 1 while i - 1 >= 0 and s[i - 1] >= s[i]: i -= 1 if i == 0: return -1 j = len(s) - 1 while s[j] <= s[i - 1]: j -= 1 s[i - 1], s[j] = s[j], s[i - 1] s[i:] = s[i:][::-1] res = int(''.join(s)) if res <= 2 ** 31 - 1: return res return -1
class Solution: def next_greater_element(self, n: int) -> int: s = list(str(n)) i = len(s) - 1 while i - 1 >= 0 and s[i - 1] >= s[i]: i -= 1 if i == 0: return -1 j = len(s) - 1 while s[j] <= s[i - 1]: j -= 1 (s[i - 1], s[j]) = (s[j], s[i - 1]) s[i:] = s[i:][::-1] res = int(''.join(s)) if res <= 2 ** 31 - 1: return res return -1
class MyrialCompileException(Exception): pass class MyrialUnexpectedEndOfFileException(MyrialCompileException): def __str__(self): return "Unexpected end-of-file" class MyrialParseException(MyrialCompileException): def __init__(self, token): self.token = token def __str__(self): return 'Parse error at token %s on line %d' % (self.token.value, self.token.lineno) class MyrialScanException(MyrialCompileException): def __init__(self, token): self.token = token def __str__(self): return 'Illegal token string %s on line %d' % (self.token.value, self.token.lineno) class DuplicateFunctionDefinitionException(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'Duplicate function definition for %s on line %d' % (self.funcname, # noqa self.lineno) # noqa class NoSuchFunctionException(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'No such function definition for %s on line %d' % (self.funcname, # noqa self.lineno) # noqa class ReservedTokenException(MyrialCompileException): def __init__(self, token, lineno): self.token = token self.lineno = lineno def __str__(self): return 'The token "%s" on line %d is reserved.' % (self.token, self.lineno) # noqa class InvalidArgumentList(MyrialCompileException): def __init__(self, funcname, expected_args, lineno): self.funcname = funcname self.expected_args = expected_args self.lineno = lineno def __str__(self): return "Incorrect number of arguments for %s(%s) on line %d" % ( self.funcname, ','.join(self.expected_args), self.lineno) class UndefinedVariableException(MyrialCompileException): def __init__(self, funcname, var, lineno): self.funcname = funcname self.var = var self.lineno = lineno def __str__(self): return "Undefined variable %s in function %s at line %d" % ( self.var, self.funcname, self.lineno) class DuplicateVariableException(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return "Duplicately defined in function %s at line %d" % ( self.funcname, self.lineno) class BadApplyDefinitionException(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return "Bad apply definition for in function %s at line %d" % ( self.funcname, self.lineno) class UnnamedStateVariableException(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return "Unnamed state variable in function %s at line %d" % ( self.funcname, self.lineno) class IllegalWildcardException(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return "Illegal use of wildcard in function %s at line %d" % ( self.funcname, self.lineno) class NestedTupleExpressionException(MyrialCompileException): def __init__(self, lineno): self.lineno = lineno def __str__(self): return "Illegal use of tuple expression on line %d" % self.lineno class InvalidEmitList(MyrialCompileException): def __init__(self, function, lineno): self.function = function self.lineno = lineno def __str__(self): return "Wrong number of emit arguments in %s at line %d" % ( self.function, self.lineno) class IllegalColumnNamesException(MyrialCompileException): def __init__(self, lineno): self.lineno = lineno def __str__(self): return "Invalid column names on line %d" % self.lineno class ColumnIndexOutOfBounds(Exception): pass class SchemaMismatchException(MyrialCompileException): def __init__(self, op_name): self.op_name = op_name def __str__(self): return "Incompatible input schemas for %s operation" % self.op_name class NoSuchRelationException(MyrialCompileException): def __init__(self, relname): self.relname = relname def __str__(self): return "No such relation: %s" % self.relname
class Myrialcompileexception(Exception): pass class Myrialunexpectedendoffileexception(MyrialCompileException): def __str__(self): return 'Unexpected end-of-file' class Myrialparseexception(MyrialCompileException): def __init__(self, token): self.token = token def __str__(self): return 'Parse error at token %s on line %d' % (self.token.value, self.token.lineno) class Myrialscanexception(MyrialCompileException): def __init__(self, token): self.token = token def __str__(self): return 'Illegal token string %s on line %d' % (self.token.value, self.token.lineno) class Duplicatefunctiondefinitionexception(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'Duplicate function definition for %s on line %d' % (self.funcname, self.lineno) class Nosuchfunctionexception(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'No such function definition for %s on line %d' % (self.funcname, self.lineno) class Reservedtokenexception(MyrialCompileException): def __init__(self, token, lineno): self.token = token self.lineno = lineno def __str__(self): return 'The token "%s" on line %d is reserved.' % (self.token, self.lineno) class Invalidargumentlist(MyrialCompileException): def __init__(self, funcname, expected_args, lineno): self.funcname = funcname self.expected_args = expected_args self.lineno = lineno def __str__(self): return 'Incorrect number of arguments for %s(%s) on line %d' % (self.funcname, ','.join(self.expected_args), self.lineno) class Undefinedvariableexception(MyrialCompileException): def __init__(self, funcname, var, lineno): self.funcname = funcname self.var = var self.lineno = lineno def __str__(self): return 'Undefined variable %s in function %s at line %d' % (self.var, self.funcname, self.lineno) class Duplicatevariableexception(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'Duplicately defined in function %s at line %d' % (self.funcname, self.lineno) class Badapplydefinitionexception(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'Bad apply definition for in function %s at line %d' % (self.funcname, self.lineno) class Unnamedstatevariableexception(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'Unnamed state variable in function %s at line %d' % (self.funcname, self.lineno) class Illegalwildcardexception(MyrialCompileException): def __init__(self, funcname, lineno): self.funcname = funcname self.lineno = lineno def __str__(self): return 'Illegal use of wildcard in function %s at line %d' % (self.funcname, self.lineno) class Nestedtupleexpressionexception(MyrialCompileException): def __init__(self, lineno): self.lineno = lineno def __str__(self): return 'Illegal use of tuple expression on line %d' % self.lineno class Invalidemitlist(MyrialCompileException): def __init__(self, function, lineno): self.function = function self.lineno = lineno def __str__(self): return 'Wrong number of emit arguments in %s at line %d' % (self.function, self.lineno) class Illegalcolumnnamesexception(MyrialCompileException): def __init__(self, lineno): self.lineno = lineno def __str__(self): return 'Invalid column names on line %d' % self.lineno class Columnindexoutofbounds(Exception): pass class Schemamismatchexception(MyrialCompileException): def __init__(self, op_name): self.op_name = op_name def __str__(self): return 'Incompatible input schemas for %s operation' % self.op_name class Nosuchrelationexception(MyrialCompileException): def __init__(self, relname): self.relname = relname def __str__(self): return 'No such relation: %s' % self.relname