content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
PACKAGE = "python-ptrace" VERSION = "0.9" WEBSITE = "http://python-ptrace.readthedocs.org/" LICENSE = "GNU GPL v2"
package = 'python-ptrace' version = '0.9' website = 'http://python-ptrace.readthedocs.org/' license = 'GNU GPL v2'
def findmax(items): if len(items) == 0: return None m = items[0] i = 1 while i < len(items): if m < items[i]: m = items[i] i = i + 1 return m
def findmax(items): if len(items) == 0: return None m = items[0] i = 1 while i < len(items): if m < items[i]: m = items[i] i = i + 1 return m
# -*- coding: utf-8 -*- """ Model Map refurbishment_level table :author: Sergio Aparicio Vegas :version: 0.2 :date: 29 Nov 2017 """ __docformat__ = "restructuredtext" class RefurbishmentLevel(): """ Refurbishment level options """ def __init__(self): self.__id = 0 self.__level = "" def __str__(self): return "id:" + str(self.__id) + " level:" + self.__level @property def id(self): return self.__id @id.setter def id(self, val): self.__id = val @property def level(self): return self.__level @level.setter def level(self, val): self.__level = val
""" Model Map refurbishment_level table :author: Sergio Aparicio Vegas :version: 0.2 :date: 29 Nov 2017 """ __docformat__ = 'restructuredtext' class Refurbishmentlevel: """ Refurbishment level options """ def __init__(self): self.__id = 0 self.__level = '' def __str__(self): return 'id:' + str(self.__id) + ' level:' + self.__level @property def id(self): return self.__id @id.setter def id(self, val): self.__id = val @property def level(self): return self.__level @level.setter def level(self, val): self.__level = val
#!/usr/bin/python patch_size = [25, 31, 35] scale_factor = [1.15, 1.2, 1.3] num_levels = [4, 8, 10] max_dist = [35, 40, 45, 50] fp_runscript = open("/home/kivan/source/cv-stereo/scripts/egomotion_kitti_eval/run_validation_orb2.sh", 'w') fp_runscript.write("#!/bin/bash\n\n") cnt = 0 for i in range(len(patch_size)): for j in range(len(num_levels)): for k in range(len(scale_factor)): for l in range(len(max_dist)): cnt += 1 filepath = "/home/kivan/source/cv-stereo/config_files/experiments/kitti/validation/orb/validation_orb2_" + str(cnt) + ".txt" print(filepath) fp = open(filepath, 'w') fp.write("egomotion_method = EgomotionRansac\n") fp.write("ransac_iters = 1000\n") fp.write("ransac_threshold = 1.5\n") fp.write("loss_function_type = Squared\n") fp.write("use_weighting = false\n") fp.write("use_deformation_field = false\n") fp.write("tracker = StereoTrackerORB\n") fp.write("max_features = 5000\n") fp.write("max_xdiff = 100\n") fp.write("max_disparity = 160\n") fp.write("orb_patch_size = " + str(patch_size[i]) + "\n") fp.write("orb_num_levels = " + str(num_levels[j]) + "\n") fp.write("orb_scale_factor = " + str(scale_factor[k]) + "\n") fp.write("orb_max_dist_stereo = " + str(max_dist[l]) + "\n") fp.write("orb_max_dist_mono = " + str(max_dist[l]) + "\n") fp.write("use_bundle_adjustment = true\n") fp.write("bundle_adjuster = BundleAdjuster\n") fp.write("ba_num_frames = 6\n") fp.close() fp_runscript.write('./run_evaluation_i7.sh "' + filepath + '"\n') fp_runscript.close()
patch_size = [25, 31, 35] scale_factor = [1.15, 1.2, 1.3] num_levels = [4, 8, 10] max_dist = [35, 40, 45, 50] fp_runscript = open('/home/kivan/source/cv-stereo/scripts/egomotion_kitti_eval/run_validation_orb2.sh', 'w') fp_runscript.write('#!/bin/bash\n\n') cnt = 0 for i in range(len(patch_size)): for j in range(len(num_levels)): for k in range(len(scale_factor)): for l in range(len(max_dist)): cnt += 1 filepath = '/home/kivan/source/cv-stereo/config_files/experiments/kitti/validation/orb/validation_orb2_' + str(cnt) + '.txt' print(filepath) fp = open(filepath, 'w') fp.write('egomotion_method = EgomotionRansac\n') fp.write('ransac_iters = 1000\n') fp.write('ransac_threshold = 1.5\n') fp.write('loss_function_type = Squared\n') fp.write('use_weighting = false\n') fp.write('use_deformation_field = false\n') fp.write('tracker = StereoTrackerORB\n') fp.write('max_features = 5000\n') fp.write('max_xdiff = 100\n') fp.write('max_disparity = 160\n') fp.write('orb_patch_size = ' + str(patch_size[i]) + '\n') fp.write('orb_num_levels = ' + str(num_levels[j]) + '\n') fp.write('orb_scale_factor = ' + str(scale_factor[k]) + '\n') fp.write('orb_max_dist_stereo = ' + str(max_dist[l]) + '\n') fp.write('orb_max_dist_mono = ' + str(max_dist[l]) + '\n') fp.write('use_bundle_adjustment = true\n') fp.write('bundle_adjuster = BundleAdjuster\n') fp.write('ba_num_frames = 6\n') fp.close() fp_runscript.write('./run_evaluation_i7.sh "' + filepath + '"\n') fp_runscript.close()
"""Automatically generated by oppfest. To update, run python3 -m script.oppfest """ # fmt: off MQTT = { "tasmota": [ "tasmota/discovery/#" ] }
"""Automatically generated by oppfest. To update, run python3 -m script.oppfest """ mqtt = {'tasmota': ['tasmota/discovery/#']}
class Queue: def __init__(self, size): if size <= 0: raise "Size must be 1 or greater." self.start = 0 self.end = 0 self.count = 0 self.size = size self.items = [None] * size def enqueue(self, data): if self.count >= self.size: raise "Queue is full." self.items[self.end] = data newEnd = self.end + 1 if newEnd >= self.size - 1: newEnd -= self.size self.end = newEnd self.count += 1 def dequeue(self): if self.count == 0: raise "Queue is empty." data = self.items[self.start] self.items[self.start] = None self.start += 1 self.count -= 1 if self.start >= self.size: self.start -= self.size return data def printQueue(self): for i in range(self.count): index = self.start + i if index >= self.size - 1: index -= self.size print(self.items[index], end="; ") print() queue = Queue(10) while True: print("1. Enqueue") print("2. Dequeue") print("3. Print queue") print("4. Exit") choice = int(input("Enter your choice: ")) if choice == 1: data = input("Enter data: ") queue.enqueue(data) elif choice == 2: print(queue.dequeue()) elif choice == 3: queue.printQueue() elif choice == 4: break else: print("Invalid choice.")
class Queue: def __init__(self, size): if size <= 0: raise 'Size must be 1 or greater.' self.start = 0 self.end = 0 self.count = 0 self.size = size self.items = [None] * size def enqueue(self, data): if self.count >= self.size: raise 'Queue is full.' self.items[self.end] = data new_end = self.end + 1 if newEnd >= self.size - 1: new_end -= self.size self.end = newEnd self.count += 1 def dequeue(self): if self.count == 0: raise 'Queue is empty.' data = self.items[self.start] self.items[self.start] = None self.start += 1 self.count -= 1 if self.start >= self.size: self.start -= self.size return data def print_queue(self): for i in range(self.count): index = self.start + i if index >= self.size - 1: index -= self.size print(self.items[index], end='; ') print() queue = queue(10) while True: print('1. Enqueue') print('2. Dequeue') print('3. Print queue') print('4. Exit') choice = int(input('Enter your choice: ')) if choice == 1: data = input('Enter data: ') queue.enqueue(data) elif choice == 2: print(queue.dequeue()) elif choice == 3: queue.printQueue() elif choice == 4: break else: print('Invalid choice.')
""" Zachary Cook Class representing a lab user. """ """ Class for a user. """ class User(): """ Constructor for the user. """ def __init__(self,id,maxSessionTime,accessType="UNAUTHORIZED"): self.id = id self.accessType = accessType self.maxSessionTime = maxSessionTime """ Returns the user's id. """ def getId(self): return self.id """ Returns the access type of the user. """ def getAccessType(self): return self.accessType """ Returns the max session time. """ def getSessionTime(self): return self.maxSessionTime
""" Zachary Cook Class representing a lab user. """ '\nClass for a user.\n' class User: """ Constructor for the user. """ def __init__(self, id, maxSessionTime, accessType='UNAUTHORIZED'): self.id = id self.accessType = accessType self.maxSessionTime = maxSessionTime "\n\tReturns the user's id.\n\t" def get_id(self): return self.id '\n\tReturns the access type of the user.\n\t' def get_access_type(self): return self.accessType '\n\tReturns the max session time.\n\t' def get_session_time(self): return self.maxSessionTime
def dist_whittaker(datamtx, strict=True): """ returns whittaker distance (manhattan distance with sample normalization) btw rows. This script interfaces with Cogent for adding the extra metric in QIIME in beta_diversity.py dist(a,b) = 0.5*manhattan distance(ai/A, bi/B) where ai is each element of a, and A is the sum of all ai. 1 indicates complete similarity, 0 indicates complete dissimilarity. see for example: D9 p. 198 Legendre and Legendre Developments in Environmental Modeling Vol. 3 1983 this code added jzl 3/17/11 * comparisons are between rows (samples) * input: 2D numpy array. Limited support for non-2D arrays if strict==False * output: numpy 2D array float ('d') type. shape (inputrows, inputrows) for sane input data * two rows of all zeros returns 0 distance between them * if strict==True, raises ValueError if any of the input data is negative, not finite, or if the input data is not a rank 2 array (a matrix). * if strict==False, assumes input data is a matrix with nonnegative entries. If rank of input data is < 2, returns an empty 2d array (shape: (0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array. """ if strict: if not all(isfinite(datamtx)): raise ValueError("non finite number in input matrix") if any(datamtx<0.0): raise ValueError("negative value in input matrix") if rank(datamtx) != 2: raise ValueError("input matrix not 2D") numrows, numcols = shape(datamtx) else: try: numrows, numcols = shape(datamtx) except ValueError: return zeros((0,0),'d') if numrows == 0 or numcols == 0: return zeros((0,0),'d') dists = zeros((numrows,numrows),'d') for i in range(numrows): r1 = array(datamtx[i,:],'d') r1sum = sum(r1) for j in range(i): r2 = array(datamtx[j,:], 'd') r2sum = sum(r2) cur_d = 0.0 if r1sum > 0 and r2sum > 0: cur_d = 0.5*float(sum(abs(r1/r1sum - r2/r2sum))) dists[i][j] = dists[j][i] = cur_d return dists
def dist_whittaker(datamtx, strict=True): """ returns whittaker distance (manhattan distance with sample normalization) btw rows. This script interfaces with Cogent for adding the extra metric in QIIME in beta_diversity.py dist(a,b) = 0.5*manhattan distance(ai/A, bi/B) where ai is each element of a, and A is the sum of all ai. 1 indicates complete similarity, 0 indicates complete dissimilarity. see for example: D9 p. 198 Legendre and Legendre Developments in Environmental Modeling Vol. 3 1983 this code added jzl 3/17/11 * comparisons are between rows (samples) * input: 2D numpy array. Limited support for non-2D arrays if strict==False * output: numpy 2D array float ('d') type. shape (inputrows, inputrows) for sane input data * two rows of all zeros returns 0 distance between them * if strict==True, raises ValueError if any of the input data is negative, not finite, or if the input data is not a rank 2 array (a matrix). * if strict==False, assumes input data is a matrix with nonnegative entries. If rank of input data is < 2, returns an empty 2d array (shape: (0, 0) ). If 0 rows or 0 colunms, also returns an empty 2d array. """ if strict: if not all(isfinite(datamtx)): raise value_error('non finite number in input matrix') if any(datamtx < 0.0): raise value_error('negative value in input matrix') if rank(datamtx) != 2: raise value_error('input matrix not 2D') (numrows, numcols) = shape(datamtx) else: try: (numrows, numcols) = shape(datamtx) except ValueError: return zeros((0, 0), 'd') if numrows == 0 or numcols == 0: return zeros((0, 0), 'd') dists = zeros((numrows, numrows), 'd') for i in range(numrows): r1 = array(datamtx[i, :], 'd') r1sum = sum(r1) for j in range(i): r2 = array(datamtx[j, :], 'd') r2sum = sum(r2) cur_d = 0.0 if r1sum > 0 and r2sum > 0: cur_d = 0.5 * float(sum(abs(r1 / r1sum - r2 / r2sum))) dists[i][j] = dists[j][i] = cur_d return dists
# ----------------------------------------------------------------------------- # Staff Assistance Flow # ----------------------------------------------------------------------------- staff_assistance_customer_email_inputtext = "xpath=//*[@id='emailInput']" staff_assistance_company_input = "//*[@id='customerInput']" staff_assistance_company_dropdown = "xpath=//*[@id='customerInput']/div/div[2]/div" staff_assistance_company_select_button = "xpath=//button[contains(text(),'Done')]" staff_assistance_company_dropdown_option_01 = "xpath=//div[contains(@class,' css-1n7v3ny-option')]" staff_assistance_changed_company_dropdown_option_01 = "xpath=//div[contains(@class,' css-yt9ioa-option')]" staff_assistance_changed_company_dropdown_option_02 = "xpath=//div[contains(@class,' css-1n7v3ny-option')]" staff_assistance_header_banner_change_link = "xpath=//a[contains(text(),'Change')]" staff_assistance_email_address_label = "xpath=//*[contains(@data-testid,'currentAccountEmail')]" staff_assistance_currently_access_label = "xpath=//*[@id='gatsby-focus-wrapper']/div[4]/div/div/span" staff_assistance_company_email_label = "xpath=//*[contains(@data-testid,'companyEmail')]" staff_assistance_company_name_label = "xpath=//*[contains(@data-testid,'companyName')]" staff_assistance_header_text_label = "You are currently acting on behalf of" staff_assistance_customer_email_address_01 = "kumindu777+yellowms@gmail.com" staff_assistance_header_company_name_label_0101 = "Yellow NZ Advertising MS" staff_assistance_customer_email_address_02 = "kumindu777+yellowsa@gmail.com" staff_assistance_header_company_name_label_0201 = "Test Business Search Ads Go Live" staff_assistance_header_company_link = "xpath=//a[contains(@href, '/my-yellow/choose-customer')]" staff_assistance_customer_email_address_03 = "kumindu777+fingoo@gmail.com" staff_assistance_header_company_name_label_0301 = "Ian Charle Langdon" staff_assistance_header_company_name_label_0302 = "Sriwis Foods" staff_assistance_select_button = "//a[contains(text(),'Select')]"
staff_assistance_customer_email_inputtext = "xpath=//*[@id='emailInput']" staff_assistance_company_input = "//*[@id='customerInput']" staff_assistance_company_dropdown = "xpath=//*[@id='customerInput']/div/div[2]/div" staff_assistance_company_select_button = "xpath=//button[contains(text(),'Done')]" staff_assistance_company_dropdown_option_01 = "xpath=//div[contains(@class,' css-1n7v3ny-option')]" staff_assistance_changed_company_dropdown_option_01 = "xpath=//div[contains(@class,' css-yt9ioa-option')]" staff_assistance_changed_company_dropdown_option_02 = "xpath=//div[contains(@class,' css-1n7v3ny-option')]" staff_assistance_header_banner_change_link = "xpath=//a[contains(text(),'Change')]" staff_assistance_email_address_label = "xpath=//*[contains(@data-testid,'currentAccountEmail')]" staff_assistance_currently_access_label = "xpath=//*[@id='gatsby-focus-wrapper']/div[4]/div/div/span" staff_assistance_company_email_label = "xpath=//*[contains(@data-testid,'companyEmail')]" staff_assistance_company_name_label = "xpath=//*[contains(@data-testid,'companyName')]" staff_assistance_header_text_label = 'You are currently acting on behalf of' staff_assistance_customer_email_address_01 = 'kumindu777+yellowms@gmail.com' staff_assistance_header_company_name_label_0101 = 'Yellow NZ Advertising MS' staff_assistance_customer_email_address_02 = 'kumindu777+yellowsa@gmail.com' staff_assistance_header_company_name_label_0201 = 'Test Business Search Ads Go Live' staff_assistance_header_company_link = "xpath=//a[contains(@href, '/my-yellow/choose-customer')]" staff_assistance_customer_email_address_03 = 'kumindu777+fingoo@gmail.com' staff_assistance_header_company_name_label_0301 = 'Ian Charle Langdon' staff_assistance_header_company_name_label_0302 = 'Sriwis Foods' staff_assistance_select_button = "//a[contains(text(),'Select')]"
# ------------------------------ # 187. Repeated DNA Sequences # # Description: # You are given two non-empty linked lists representing two non-negative integers. The most significant digit # comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. # # You may assume the two numbers do not contain any leading zero, except the number 0 itself. # Follow up: # What if you cannot modify the input lists? In other words, reversing the lists is not allowed. # # Example: # # Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4) # Output: 7 -> 8 -> 0 -> 7 # # Version: 1.0 # 10/06/17 by Jianfa # ------------------------------ class Solution(object): def findRepeatedDnaSequences(self, s): """ :type s: str :rtype: List[str] """ s_len = len(s) s_dict = {} res = set() for i in range(s_len - 9): if s[i:i+10] in s_dict: res.add(s[i:i+10]) else: s_dict[s[i:i+10]] = 1 return list(set(res)) # Used for test if __name__ == "__main__": test = Solution() s = "AAAAAAAAAAA" res = test.addTwoNumbers(a4, b3) print(test.findRepeatedDnaSequences(s)) # ------------------------------ # Summary: # O(n) solution with O(n) space. # Key idea is to use set/dict to detect whether the string appears has appeared. # Another idea for saving space is to use int in replace of string. e.g. Let A for 1, C for 2, G for 3, T for 4. # Then a ten-unit string can be converted to a 10-digit integer and save the space. May use a large array to # imitate a hash map.
class Solution(object): def find_repeated_dna_sequences(self, s): """ :type s: str :rtype: List[str] """ s_len = len(s) s_dict = {} res = set() for i in range(s_len - 9): if s[i:i + 10] in s_dict: res.add(s[i:i + 10]) else: s_dict[s[i:i + 10]] = 1 return list(set(res)) if __name__ == '__main__': test = solution() s = 'AAAAAAAAAAA' res = test.addTwoNumbers(a4, b3) print(test.findRepeatedDnaSequences(s))
# Python Program To Copy An Image Into Another Files ''' Function Name : Copy An Image Into Another Files Function Date : 24 Sep 2020 Function Author : Prasad Dangare Input : -- Output : -- ''' # Open The File In Binary Modes f1 = open('new.jpg.png', 'rb') f2 = open('neww.jpg.jpg', 'wb') # Read Bytes From f1 And Write Into f2 bytes = f1.read() f2.write(bytes) # Close The File f1.close() f2.close()
""" Function Name : Copy An Image Into Another Files Function Date : 24 Sep 2020 Function Author : Prasad Dangare Input : -- Output : -- """ f1 = open('new.jpg.png', 'rb') f2 = open('neww.jpg.jpg', 'wb') bytes = f1.read() f2.write(bytes) f1.close() f2.close()
# Oefening: Vraag de geboortedatum van de gebruiker en zeg de leeftijd. huidig_jaar = 2017 huidige_maand = 10 huidige_dag = 24 jaar = int(input("In welk jaar ben je geboren? ")) maand = int(input("En in welke maand? (getal) ")) # De dag moeten we pas weten als de geboortemaand deze maand is! # Je kan het hier natuurlijk ook al vragen als je wilt. leeftijd = huidig_jaar - jaar if (maand > huidige_maand): # De gebruiker is nog niet verjaard leeftijd -= 1 # hetzelfde als "leeftijd = leeftijd - 1" elif (maand == huidige_maand): dag = int(input("En welke dag? (getal) ")) if (dag > huidige_dag): leeftijd -= 1 elif (dag == huidige_dag): # leeftijd = leeftijd # Dat doet helemaal niets natuurlijk print("Gelukkige verjaardag!") # else: # Enkel (dag < huidige_dag) kan nog => # # De gebruiker is al verjaard deze maand! # leeftijd = leeftijd # Maar er hoeft niets veranderd te worden. # else: # De gebruiker is zeker al verjaard, # # want enkel maand < huidige_maand kan nog! # leeftijd = leeftijd # Maar we moeten niets aanpassen! print("Dan ben je " + str(leeftijd) + " jaar oud.") ## Oefeningen zonder oplossing (mail bij vragen!). # # Oefening: start met leeftijd = huidig_jaar - jaar - 1 en verhoog die # waarde wanneer nodig. Vergelijk de voorwaarden daar met die hier. # Wat is het verschil in de tekens? # # Nog een oefening: kijk de waarden die de gebruiker ingeeft na. # Zorg ervoor je geen dag kan invoeren die later komt dan vandaag. # Probeer dat zo onafhankelijk mogelijk te doen van de bovenstaande code. # # Nadenkoefening: kan je bovenstaande 2 voorwaarden in de vorige opdracht uitvoeren # zonder in de herhaling te vallen? (dat is geen uitdaging, maar een vraag!). # Als je toch iets mag aanpassen aan bovenstaande code, kan het dan? # Wat denk je dat de beste optie is?
huidig_jaar = 2017 huidige_maand = 10 huidige_dag = 24 jaar = int(input('In welk jaar ben je geboren? ')) maand = int(input('En in welke maand? (getal) ')) leeftijd = huidig_jaar - jaar if maand > huidige_maand: leeftijd -= 1 elif maand == huidige_maand: dag = int(input('En welke dag? (getal) ')) if dag > huidige_dag: leeftijd -= 1 elif dag == huidige_dag: print('Gelukkige verjaardag!') print('Dan ben je ' + str(leeftijd) + ' jaar oud.')
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class NetworkApiMixin(object): def peer_list(self): """ GET /network/peers Use the Network APIs to retrieve information about the network of peer nodes comprising the blockchain network. ```golang message PeersMessage { repeated PeerEndpoint peers = 1; } message PeerEndpoint { PeerID ID = 1; string address = 2; enum Type { UNDEFINED = 0; VALIDATOR = 1; NON_VALIDATOR = 2; } Type type = 3; bytes pkiID = 4; } message PeerID { string name = 1; } ``` :return: json body of the network peers info """ res = self._get(self._url("/network/peers")) return self._result(res, True)
class Networkapimixin(object): def peer_list(self): """ GET /network/peers Use the Network APIs to retrieve information about the network of peer nodes comprising the blockchain network. ```golang message PeersMessage { repeated PeerEndpoint peers = 1; } message PeerEndpoint { PeerID ID = 1; string address = 2; enum Type { UNDEFINED = 0; VALIDATOR = 1; NON_VALIDATOR = 2; } Type type = 3; bytes pkiID = 4; } message PeerID { string name = 1; } ``` :return: json body of the network peers info """ res = self._get(self._url('/network/peers')) return self._result(res, True)
# Problem for Prof Charnesky's mid term review sheet at: # https://canvas.umd.umich.edu/courses/522665/pages/midterm-practice?module_item_id=9243802 # 1 Classes and Unit Test question # Given the following UML, write the class # Pizza # toppings : [] # slices : int # base_cost : float # price_per_topping : int # get_total_price() : int # Write a unit test for get_total_price() class Pizza: def __init__(self, toppings, slices, base_cost=2.5, price_per_topping=1): self._toppings = toppings self._slices = slices self._base_cost = base_cost self._price_per_topping = price_per_topping def get_total_price(self): return (self._base_cost + self._price_per_topping * (len(self._toppings))) * self._slices if __name__ == "__main__": nice = Pizza(['pineapple', 'ham', 'mushrooms'], 3) print(nice.get_total_price())
class Pizza: def __init__(self, toppings, slices, base_cost=2.5, price_per_topping=1): self._toppings = toppings self._slices = slices self._base_cost = base_cost self._price_per_topping = price_per_topping def get_total_price(self): return (self._base_cost + self._price_per_topping * len(self._toppings)) * self._slices if __name__ == '__main__': nice = pizza(['pineapple', 'ham', 'mushrooms'], 3) print(nice.get_total_price())
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): if self.value: if value < self.value: if self.left: self.left.insert(value) else: self.left = Node(value) else: if self.right: self.right.insert(value) else: self.right = Node(value) else: self.value = value def preorder(self): result = [] if not self: return result result.append(self.value) if self.left: result += self.left.preorder() if self.right: result += self.right.preorder() return result def inorder(self): result = [] if not self: return result if self.left: result += self.left.inorder() result.append(self.value) if self.right: result += self.right.inorder() return result def postorder(self): result = [] if not self: return result if self.left: result += self.left.postorder() if self.right: result += self.right.postorder() result.append(self.value) return result def create_bst(lst): root = Node(lst[0]) for i in lst[1:]: root.insert(i) return root
class Node: def __init__(self, value): self.value = value self.left = None self.right = None def insert(self, value): if self.value: if value < self.value: if self.left: self.left.insert(value) else: self.left = node(value) elif self.right: self.right.insert(value) else: self.right = node(value) else: self.value = value def preorder(self): result = [] if not self: return result result.append(self.value) if self.left: result += self.left.preorder() if self.right: result += self.right.preorder() return result def inorder(self): result = [] if not self: return result if self.left: result += self.left.inorder() result.append(self.value) if self.right: result += self.right.inorder() return result def postorder(self): result = [] if not self: return result if self.left: result += self.left.postorder() if self.right: result += self.right.postorder() result.append(self.value) return result def create_bst(lst): root = node(lst[0]) for i in lst[1:]: root.insert(i) return root
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- ACR_RESOURCE_PROVIDER = 'Microsoft.ContainerRegistry' ACR_RESOURCE_TYPE = ACR_RESOURCE_PROVIDER + '/registries' STORAGE_RESOURCE_TYPE = 'Microsoft.Storage/storageAccounts' WEBHOOK_RESOURCE_TYPE = ACR_RESOURCE_TYPE + '/webhooks' WEBHOOK_API_VERSION = '2017-06-01-preview' MANAGED_REGISTRY_API_VERSION = '2017-06-01-preview' MANAGED_REGISTRY_SKU = ['Managed_Basic', 'Managed_Standard', 'Managed_Premium']
acr_resource_provider = 'Microsoft.ContainerRegistry' acr_resource_type = ACR_RESOURCE_PROVIDER + '/registries' storage_resource_type = 'Microsoft.Storage/storageAccounts' webhook_resource_type = ACR_RESOURCE_TYPE + '/webhooks' webhook_api_version = '2017-06-01-preview' managed_registry_api_version = '2017-06-01-preview' managed_registry_sku = ['Managed_Basic', 'Managed_Standard', 'Managed_Premium']
class Settings: """ All Game Settings """ def __init__(self): self.screen_width = 1000 self.screen_height = 600 self.bg_color = (180, 255, 255) self.ship_speed = 1.25 self.ship_limit = 3 self.bullet_speed = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullet_allowed = 4 self.virus_speed = 0.50 self.fleet_drop_speed = 5 self.speed_upscale = 1.20 self.score_upscale = 1.25 self.initialize_dynamic_settings() self.fleet_direction = 1 def initialize_dynamic_settings(self): self.ship_speed = 1.25 self.bullet_speed = 1 self.virus_speed = 0.50 self.fleet_direction = 1 self.virus_points = 50 def increase_speed(self): #self.ship_speed *= self.speed_upscale self.bullet_speed *= self.speed_upscale self.virus_speed *= self.speed_upscale self.virus_points = int(self.virus_points * self.score_upscale)
class Settings: """ All Game Settings """ def __init__(self): self.screen_width = 1000 self.screen_height = 600 self.bg_color = (180, 255, 255) self.ship_speed = 1.25 self.ship_limit = 3 self.bullet_speed = 1 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullet_allowed = 4 self.virus_speed = 0.5 self.fleet_drop_speed = 5 self.speed_upscale = 1.2 self.score_upscale = 1.25 self.initialize_dynamic_settings() self.fleet_direction = 1 def initialize_dynamic_settings(self): self.ship_speed = 1.25 self.bullet_speed = 1 self.virus_speed = 0.5 self.fleet_direction = 1 self.virus_points = 50 def increase_speed(self): self.bullet_speed *= self.speed_upscale self.virus_speed *= self.speed_upscale self.virus_points = int(self.virus_points * self.score_upscale)
total = 0 for num in range(101): total = total + num print (total)
total = 0 for num in range(101): total = total + num print(total)
def totalFruit(self, tree): count = {} i = res = 0 for j, v in enumerate(tree): count[v] = count.get(v, 0) + 1 while len(count) > 2: count[tree[i]] -= 1 if count[tree[i]] == 0: del count[tree[i]] i += 1 res = max(res, j - i + 1) return res
def total_fruit(self, tree): count = {} i = res = 0 for (j, v) in enumerate(tree): count[v] = count.get(v, 0) + 1 while len(count) > 2: count[tree[i]] -= 1 if count[tree[i]] == 0: del count[tree[i]] i += 1 res = max(res, j - i + 1) return res
a, b = input().split() st = '' num_a = int(a) num_b = int(b) if num_a % 2 == 0 : answer = -num_a st += str(-num_a) else : answer = num_a st += str(num_a) if a == b : if int(a) % 2 == 0 : print("-", a, "=-", a, sep='') else : print(a, "=+", a, sep='') exit() while num_a != num_b : num_a += 1 if(num_a %2 == 0) : st += '-' + str(num_a) answer -= num_a else : st += '+' + str(num_a) answer += num_a st += '=' if (num_b - 1) % 2 == 0 : st += '+' + str(answer) else : st += str(answer) print(st)
(a, b) = input().split() st = '' num_a = int(a) num_b = int(b) if num_a % 2 == 0: answer = -num_a st += str(-num_a) else: answer = num_a st += str(num_a) if a == b: if int(a) % 2 == 0: print('-', a, '=-', a, sep='') else: print(a, '=+', a, sep='') exit() while num_a != num_b: num_a += 1 if num_a % 2 == 0: st += '-' + str(num_a) answer -= num_a else: st += '+' + str(num_a) answer += num_a st += '=' if (num_b - 1) % 2 == 0: st += '+' + str(answer) else: st += str(answer) print(st)
result =1 i=1 while i<=100: result=result*i i=i+1 pass print("the factorial is {}".format(result))
result = 1 i = 1 while i <= 100: result = result * i i = i + 1 pass print('the factorial is {}'.format(result))
class TOS(QTextEdit): tos_signal = pyqtSignal() error_signal = pyqtSignal(object) class Plugin(TrustedCoinPlugin): def __init__(self, parent, config, name): super().__init__(parent, config, name) @hook def on_new_window(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if wallet.can_sign_without_server(): msg = " ".join([_("This wallet was restored from seed, and it contains two master private keys."), _("Therefore, two-factor authentication is disabled.")]) action = lambda: window.show_message(msg) else: action = partial(self.settings_dialog, window) button = StatusBarButton(QIcon(":icons/trustedcoin-status.png"), _("TrustedCoin"), action) window.statusBar().addPermanentWidget(button) self.start_request_thread(window.wallet) def auth_dialog(self, window): d = WindowModalDialog(window, _("Authorization")) vbox = QVBoxLayout(d) pw = AmountEdit(None, is_int=True) msg = _("Please enter your Google Authenticator code") vbox.addWidget(QLabel(msg)) grid = QGridLayout() grid.setSpacing(8) grid.addWidget(QLabel(_("Code")), 1, 0) grid.addWidget(pw, 1, 1) vbox.addLayout(grid) msg = _("If you have lost your second factor, you need to restore your wallet from seed in order to request a new code.") label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addLayout(Buttons(CancelButton(d), OkButton(d))) if not d.exec_(): return return pw.get_amount() @hook def sign_tx(self, window, tx): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if not wallet.can_sign_without_server(): self.print_error("twofactor:sign_tx") auth_code = None if wallet.keystores["x3/"].get_tx_derivations(tx): auth_code = self.auth_dialog(window) else: self.print_error("twofactor: xpub3 not needed") window.wallet.auth_code = auth_code def waiting_dialog(self, window, on_finished=None): task = partial(self.request_billing_info, window.wallet) return WaitingDialog(window, "Getting billing information...", task, on_finished) @hook def abort_send(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if wallet.can_sign_without_server(): return if wallet.billing_info is None: return True return False def settings_dialog(self, window): self.waiting_dialog(window, partial(self.show_settings_dialog, window)) def show_settings_dialog(self, window, success): if not success: window.show_message(_("Server not reachable.")) return wallet = window.wallet d = WindowModalDialog(window, _("TrustedCoin Information")) d.setMinimumSize(500, 200) vbox = QVBoxLayout(d) hbox = QHBoxLayout() logo = QLabel() logo.setPixmap(QPixmap(":icons/trustedcoin-status.png")) msg = _("This wallet is protected by TrustedCoin's two-factor authentication.") + "<br/>" + _("For more information, visit") + ' <a href="https://api.trustedcoin.com/#/electrum-help">https://api.trustedcoin.com/#/electrum-help</a>' label = QLabel(msg) label.setOpenExternalLinks(1) hbox.addStretch(10) hbox.addWidget(logo) hbox.addStretch(10) hbox.addWidget(label) hbox.addStretch(10) vbox.addLayout(hbox) vbox.addStretch(10) msg = _("TrustedCoin charges a small fee to co-sign transactions. The fee depends on how many prepaid transactions you buy. An extra output is added to your transaction everytime you run out of prepaid transactions.") + "<br/>" label = QLabel(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addStretch(10) grid = QGridLayout() vbox.addLayout(grid) price_per_tx = wallet.price_per_tx n_prepay = wallet.num_prepay(self.config) i = 0 for k, v in sorted(price_per_tx.items()): if k == 1: continue grid.addWidget(QLabel("Pay every %d transactions:" % k), i, 0) grid.addWidget(QLabel(window.format_amount(v / k) + " " + window.base_unit() + "/tx"), i, 1) b = QRadioButton() b.setChecked(k == n_prepay) b.clicked.connect(lambda b, k=k: self.config.set_key("trustedcoin_prepay", k, True)) grid.addWidget(b, i, 2) i += 1 n = wallet.billing_info.get("tx_remaining", 0) grid.addWidget(QLabel(_("Your wallet has {} prepaid transactions.").format(n)), i, 0) vbox.addLayout(Buttons(CloseButton(d))) d.exec_() def on_buy(self, window, k, v, d): d.close() if window.pluginsdialog: window.pluginsdialog.close() wallet = window.wallet uri = "bitcoin:" + wallet.billing_info["billing_address"] + "?message=TrustedCoin %d Prepaid Transactions&amount=" % k + str(Decimal(v) / 100000000) wallet.is_billing = True window.pay_to_URI(uri) window.payto_e.setFrozen(True) window.message_e.setFrozen(True) window.amount_e.setFrozen(True) def accept_terms_of_use(self, window): vbox = QVBoxLayout() vbox.addWidget(QLabel(_("Terms of Service"))) tos_e = TOS() tos_e.setReadOnly(True) vbox.addWidget(tos_e) tos_received = False vbox.addWidget(QLabel(_("Please enter your e-mail address"))) email_e = QLineEdit() vbox.addWidget(email_e) next_button = window.next_button prior_button_text = next_button.text() next_button.setText(_("Accept")) def request_TOS(): try: tos = server.get_terms_of_service() except Exception as e: traceback.print_exc(file=sys.stderr) tos_e.error_signal.emit(_("Could not retrieve Terms of Service:") + "\n" + str(e)) return self.TOS = tos tos_e.tos_signal.emit() def on_result(): tos_e.setText(self.TOS) nonlocal tos_received tos_received = True set_enabled() def on_error(msg): window.show_error(str(msg)) window.terminate() def set_enabled(): valid_email = re.match(regexp, email_e.text()) is not None next_button.setEnabled(tos_received and valid_email) tos_e.tos_signal.connect(on_result) tos_e.error_signal.connect(on_error) t = Thread(target=request_TOS) t.setDaemon(True) t.start() regexp = r"[^@]+@[^@]+\.[^@]+" email_e.textChanged.connect(set_enabled) email_e.setFocus(True) window.exec_layout(vbox, next_enabled=False) next_button.setText(prior_button_text) return str(email_e.text()) def request_otp_dialog(self, window, _id, otp_secret): vbox = QVBoxLayout() if otp_secret is not None: uri = "otpauth://totp/%s?secret=%s" % ("trustedcoin.com", otp_secret) l = QLabel("Please scan the following QR code in Google Authenticator. You may as well use the following key: %s" % otp_secret) l.setWordWrap(True) vbox.addWidget(l) qrw = QRCodeWidget(uri) vbox.addWidget(qrw, 1) msg = _("Then, enter your Google Authenticator code:") else: label = QLabel("This wallet is already registered with Trustedcoin. " "To finalize wallet creation, please enter your Google Authenticator Code. ") label.setWordWrap(1) vbox.addWidget(label) msg = _("Google Authenticator code:") hbox = QHBoxLayout() hbox.addWidget(WWLabel(msg)) pw = AmountEdit(None, is_int=True) pw.setFocus(True) pw.setMaximumWidth(50) hbox.addWidget(pw) vbox.addLayout(hbox) cb_lost = QCheckBox(_("I have lost my Google Authenticator account")) cb_lost.setToolTip(_("Check this box to request a new secret. You will need to retype your seed.")) vbox.addWidget(cb_lost) cb_lost.setVisible(otp_secret is None) def set_enabled(): b = True if cb_lost.isChecked() else len(pw.text()) == 6 window.next_button.setEnabled(b) pw.textChanged.connect(set_enabled) cb_lost.toggled.connect(set_enabled) window.exec_layout(vbox, next_enabled=False, raise_on_cancel=False) return pw.get_amount(), cb_lost.isChecked()
class Tos(QTextEdit): tos_signal = pyqt_signal() error_signal = pyqt_signal(object) class Plugin(TrustedCoinPlugin): def __init__(self, parent, config, name): super().__init__(parent, config, name) @hook def on_new_window(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if wallet.can_sign_without_server(): msg = ' '.join([_('This wallet was restored from seed, and it contains two master private keys.'), _('Therefore, two-factor authentication is disabled.')]) action = lambda : window.show_message(msg) else: action = partial(self.settings_dialog, window) button = status_bar_button(q_icon(':icons/trustedcoin-status.png'), _('TrustedCoin'), action) window.statusBar().addPermanentWidget(button) self.start_request_thread(window.wallet) def auth_dialog(self, window): d = window_modal_dialog(window, _('Authorization')) vbox = qv_box_layout(d) pw = amount_edit(None, is_int=True) msg = _('Please enter your Google Authenticator code') vbox.addWidget(q_label(msg)) grid = q_grid_layout() grid.setSpacing(8) grid.addWidget(q_label(_('Code')), 1, 0) grid.addWidget(pw, 1, 1) vbox.addLayout(grid) msg = _('If you have lost your second factor, you need to restore your wallet from seed in order to request a new code.') label = q_label(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addLayout(buttons(cancel_button(d), ok_button(d))) if not d.exec_(): return return pw.get_amount() @hook def sign_tx(self, window, tx): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if not wallet.can_sign_without_server(): self.print_error('twofactor:sign_tx') auth_code = None if wallet.keystores['x3/'].get_tx_derivations(tx): auth_code = self.auth_dialog(window) else: self.print_error('twofactor: xpub3 not needed') window.wallet.auth_code = auth_code def waiting_dialog(self, window, on_finished=None): task = partial(self.request_billing_info, window.wallet) return waiting_dialog(window, 'Getting billing information...', task, on_finished) @hook def abort_send(self, window): wallet = window.wallet if not isinstance(wallet, self.wallet_class): return if wallet.can_sign_without_server(): return if wallet.billing_info is None: return True return False def settings_dialog(self, window): self.waiting_dialog(window, partial(self.show_settings_dialog, window)) def show_settings_dialog(self, window, success): if not success: window.show_message(_('Server not reachable.')) return wallet = window.wallet d = window_modal_dialog(window, _('TrustedCoin Information')) d.setMinimumSize(500, 200) vbox = qv_box_layout(d) hbox = qh_box_layout() logo = q_label() logo.setPixmap(q_pixmap(':icons/trustedcoin-status.png')) msg = _("This wallet is protected by TrustedCoin's two-factor authentication.") + '<br/>' + _('For more information, visit') + ' <a href="https://api.trustedcoin.com/#/electrum-help">https://api.trustedcoin.com/#/electrum-help</a>' label = q_label(msg) label.setOpenExternalLinks(1) hbox.addStretch(10) hbox.addWidget(logo) hbox.addStretch(10) hbox.addWidget(label) hbox.addStretch(10) vbox.addLayout(hbox) vbox.addStretch(10) msg = _('TrustedCoin charges a small fee to co-sign transactions. The fee depends on how many prepaid transactions you buy. An extra output is added to your transaction everytime you run out of prepaid transactions.') + '<br/>' label = q_label(msg) label.setWordWrap(1) vbox.addWidget(label) vbox.addStretch(10) grid = q_grid_layout() vbox.addLayout(grid) price_per_tx = wallet.price_per_tx n_prepay = wallet.num_prepay(self.config) i = 0 for (k, v) in sorted(price_per_tx.items()): if k == 1: continue grid.addWidget(q_label('Pay every %d transactions:' % k), i, 0) grid.addWidget(q_label(window.format_amount(v / k) + ' ' + window.base_unit() + '/tx'), i, 1) b = q_radio_button() b.setChecked(k == n_prepay) b.clicked.connect(lambda b, k=k: self.config.set_key('trustedcoin_prepay', k, True)) grid.addWidget(b, i, 2) i += 1 n = wallet.billing_info.get('tx_remaining', 0) grid.addWidget(q_label(_('Your wallet has {} prepaid transactions.').format(n)), i, 0) vbox.addLayout(buttons(close_button(d))) d.exec_() def on_buy(self, window, k, v, d): d.close() if window.pluginsdialog: window.pluginsdialog.close() wallet = window.wallet uri = 'bitcoin:' + wallet.billing_info['billing_address'] + '?message=TrustedCoin %d Prepaid Transactions&amount=' % k + str(decimal(v) / 100000000) wallet.is_billing = True window.pay_to_URI(uri) window.payto_e.setFrozen(True) window.message_e.setFrozen(True) window.amount_e.setFrozen(True) def accept_terms_of_use(self, window): vbox = qv_box_layout() vbox.addWidget(q_label(_('Terms of Service'))) tos_e = tos() tos_e.setReadOnly(True) vbox.addWidget(tos_e) tos_received = False vbox.addWidget(q_label(_('Please enter your e-mail address'))) email_e = q_line_edit() vbox.addWidget(email_e) next_button = window.next_button prior_button_text = next_button.text() next_button.setText(_('Accept')) def request_tos(): try: tos = server.get_terms_of_service() except Exception as e: traceback.print_exc(file=sys.stderr) tos_e.error_signal.emit(_('Could not retrieve Terms of Service:') + '\n' + str(e)) return self.TOS = tos tos_e.tos_signal.emit() def on_result(): tos_e.setText(self.TOS) nonlocal tos_received tos_received = True set_enabled() def on_error(msg): window.show_error(str(msg)) window.terminate() def set_enabled(): valid_email = re.match(regexp, email_e.text()) is not None next_button.setEnabled(tos_received and valid_email) tos_e.tos_signal.connect(on_result) tos_e.error_signal.connect(on_error) t = thread(target=request_TOS) t.setDaemon(True) t.start() regexp = '[^@]+@[^@]+\\.[^@]+' email_e.textChanged.connect(set_enabled) email_e.setFocus(True) window.exec_layout(vbox, next_enabled=False) next_button.setText(prior_button_text) return str(email_e.text()) def request_otp_dialog(self, window, _id, otp_secret): vbox = qv_box_layout() if otp_secret is not None: uri = 'otpauth://totp/%s?secret=%s' % ('trustedcoin.com', otp_secret) l = q_label('Please scan the following QR code in Google Authenticator. You may as well use the following key: %s' % otp_secret) l.setWordWrap(True) vbox.addWidget(l) qrw = qr_code_widget(uri) vbox.addWidget(qrw, 1) msg = _('Then, enter your Google Authenticator code:') else: label = q_label('This wallet is already registered with Trustedcoin. To finalize wallet creation, please enter your Google Authenticator Code. ') label.setWordWrap(1) vbox.addWidget(label) msg = _('Google Authenticator code:') hbox = qh_box_layout() hbox.addWidget(ww_label(msg)) pw = amount_edit(None, is_int=True) pw.setFocus(True) pw.setMaximumWidth(50) hbox.addWidget(pw) vbox.addLayout(hbox) cb_lost = q_check_box(_('I have lost my Google Authenticator account')) cb_lost.setToolTip(_('Check this box to request a new secret. You will need to retype your seed.')) vbox.addWidget(cb_lost) cb_lost.setVisible(otp_secret is None) def set_enabled(): b = True if cb_lost.isChecked() else len(pw.text()) == 6 window.next_button.setEnabled(b) pw.textChanged.connect(set_enabled) cb_lost.toggled.connect(set_enabled) window.exec_layout(vbox, next_enabled=False, raise_on_cancel=False) return (pw.get_amount(), cb_lost.isChecked())
# # PySNMP MIB module ZHONE-PHY-SONET-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZHONE-PHY-SONET-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:47:49 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, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, Bits, Counter32, Gauge32, MibIdentifier, ObjectIdentity, Counter64, NotificationType, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, IpAddress, ModuleIdentity, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Bits", "Counter32", "Gauge32", "MibIdentifier", "ObjectIdentity", "Counter64", "NotificationType", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "IpAddress", "ModuleIdentity", "TimeTicks") TextualConvention, TruthValue, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "TruthValue", "DisplayString") sonetMediumEntry, sonetPathCurrentStatus, sonetSectionCurrentStatus, sonetLineCurrentStatus = mibBuilder.importSymbols("SONET-MIB", "sonetMediumEntry", "sonetPathCurrentStatus", "sonetSectionCurrentStatus", "sonetLineCurrentStatus") zhoneModules, zhoneSonet = mibBuilder.importSymbols("Zhone", "zhoneModules", "zhoneSonet") phySonet = ModuleIdentity((1, 3, 6, 1, 4, 1, 5504, 6, 16)) phySonet.setRevisions(('2004-08-18 11:47', '2003-07-10 13:30', '2002-03-26 14:30', '2001-09-12 15:08', '2001-07-19 18:00', '2001-02-22 11:35', '2000-12-19 15:23', '2000-12-18 16:20',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: phySonet.setRevisionsDescriptions(('1.03.04 - Add zhoneSonetErrorStatsTable.', '1.03.02 Add sonetPathStatusChange trap.', '1.03.01 Add sonetSectionStatusChange trap and sonetLineStatusChange trap.', 'V01.03.00 Changed names for valid values for sonetClockTransmitSource', 'V01.02.00 Add Sonet clock source change trap.', 'V01.01.00 - Add Sonet Medium Extension Table.', 'V01.00.01 - Add Zhone keywords.', 'V01.00.00 - Initial Release',)) if mibBuilder.loadTexts: phySonet.setLastUpdated('200408181330Z') if mibBuilder.loadTexts: phySonet.setOrganization('Zhone Technologies, Inc.') if mibBuilder.loadTexts: phySonet.setContactInfo(' Postal: Zhone Technologies, Inc. @ Zhone Way 7001 Oakport Street Oakland, CA 94621 USA Toll-Free: +1 877-ZHONE20 (+1 877-946-6320) Tel: +1-510-777-7000 Fax: +1-510-777-7001 E-mail: support@zhone.com') if mibBuilder.loadTexts: phySonet.setDescription('SONET physical MIB to configure and monitor SONET physical attributes. ') sonetClockTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1), ) if mibBuilder.loadTexts: sonetClockTable.setStatus('current') if mibBuilder.loadTexts: sonetClockTable.setDescription('MIB table for clock related configuration for SONET interfaces.') sonetClockEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1, 1), ) sonetMediumEntry.registerAugmentions(("ZHONE-PHY-SONET-MIB", "sonetClockEntry")) sonetClockEntry.setIndexNames(*sonetMediumEntry.getIndexNames()) if mibBuilder.loadTexts: sonetClockEntry.setStatus('current') if mibBuilder.loadTexts: sonetClockEntry.setDescription('An entry of the sonetClockEntry. sonetClockEntry is augmented to sonetMediumEntry defined in rfc2558.mib. Whenever a row is instantiated in the sonetMediumTable, a corresponding row will be instantiated in the sonetClockTable.') sonetClockExternalRecovery = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sonetClockExternalRecovery.setStatus('current') if mibBuilder.loadTexts: sonetClockExternalRecovery.setDescription("This variable indicates if external clock recovery is enabled for this SONET interface. The default value is 'enabled'.") sonetClockTransmitSource = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("loopTiming", 1), ("throughTiming", 2), ("localTiming", 3), ("external155MHz", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: sonetClockTransmitSource.setStatus('current') if mibBuilder.loadTexts: sonetClockTransmitSource.setDescription("This variable describes the SONET transmit clock source. Valid values are: loopTiming - transmit clock synthesized from the recovered receive clock. throughTiming - transmit clock is derived from the recovered receive clock of another SONET interface. localTiming - transmit clock synthesized from a local clock source or that an external clock is attached to the box containing the interface. external155MHz - transmit clock synthesized from an external 155.52 MHz source. The default value is 'loopTiming'. 'external155MHz' option is not valid for Sechtor 100.") sonetMediumExtTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2), ) if mibBuilder.loadTexts: sonetMediumExtTable.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtTable.setDescription('This is an extenion of the standard Sonet MIB (RFC 2558).') sonetMediumExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2, 1), ) sonetMediumEntry.registerAugmentions(("ZHONE-PHY-SONET-MIB", "sonetMediumExtEntry")) sonetMediumExtEntry.setIndexNames(*sonetMediumEntry.getIndexNames()) if mibBuilder.loadTexts: sonetMediumExtEntry.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtEntry.setDescription('Each row is an extension to the sonetMediumTable for Zhone specific fields. This row is created when the augmented sonetMediumEntry is created.') sonetMediumExtScrambleEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2, 1, 1), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: sonetMediumExtScrambleEnabled.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtScrambleEnabled.setDescription('This field describes the enabled status of the Sonet Scramble mode. If this field is true(1) then Scramble mode is enabled, if this field is false(2) scramble mode is disable.') sonetMediumExtLineScrmEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2, 1, 2), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: sonetMediumExtLineScrmEnabled.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtLineScrmEnabled.setDescription('This field describes the enabled status of the Line level Sonet Scramble mode. If this field is true(1), then Scramble mode is enabled. If this field is false(2), scramble mode is disable.') sonetTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3)) if mibBuilder.loadTexts: sonetTraps.setStatus('current') if mibBuilder.loadTexts: sonetTraps.setDescription('All Zhone Sonet traps will be defined under this object identity.') sonetV2Traps = ObjectIdentity((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0)) if mibBuilder.loadTexts: sonetV2Traps.setStatus('current') if mibBuilder.loadTexts: sonetV2Traps.setDescription('This object identity adds a zero(0) for the next to last sub-identifier which should be used for new SNMPv2 Traps.') sonetClockTransmitSourceChange = NotificationType((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 1)).setObjects(("ZHONE-PHY-SONET-MIB", "sonetClockExternalRecovery"), ("ZHONE-PHY-SONET-MIB", "sonetClockTransmitSource")) if mibBuilder.loadTexts: sonetClockTransmitSourceChange.setStatus('current') if mibBuilder.loadTexts: sonetClockTransmitSourceChange.setDescription('A notification trap is sent when either sonetClockExternalRecovery or sonetClockTransmitSource is changed. The trap object is identified by the OID instance of sonetClockTransmitSource described in the OBJECTS clause.') sonetSectionStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 2)).setObjects(("SONET-MIB", "sonetSectionCurrentStatus")) if mibBuilder.loadTexts: sonetSectionStatusChange.setStatus('current') if mibBuilder.loadTexts: sonetSectionStatusChange.setDescription('A notification trap is sent when there is a change in the sonet SECTION status. Currenly the following are supported: NO-DEFECT = 1 LOS = 2 LOF = 4 The trap object is identified by the OID instance of sonetSectionCurrentStatus described in the OBJECTS clause.') sonetLineStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 3)).setObjects(("SONET-MIB", "sonetLineCurrentStatus")) if mibBuilder.loadTexts: sonetLineStatusChange.setStatus('current') if mibBuilder.loadTexts: sonetLineStatusChange.setDescription('A notification trap is sent when there is a change in the sonet LINE status. Currenly the following are supported: NO-DEFECT = 1 AIS = 2 RDI = 4 The trap object is identified by the OID instance of sonetLineCurrentStatus described in the OBJECTS clause.') sonetPathStatusChange = NotificationType((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 4)).setObjects(("SONET-MIB", "sonetPathCurrentStatus")) if mibBuilder.loadTexts: sonetPathStatusChange.setStatus('current') if mibBuilder.loadTexts: sonetPathStatusChange.setDescription('A notification trap is sent when there is a change in the sonetPathCurrentStatus. Currenly the following are supported: 1 sonetPathNoDefect 2 sonetPathSTSLOP 4 sonetPathSTSAIS 8 sonetPathSTSRDI 16 sonetPathUnequipped 32 sonetPathSignalLabelMismatch The trap object is identified by the OID instance of sonetPathCurrentStatus described in the OBJECTS clause.') zhoneSonetErrorStatsTable = MibTable((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6), ) if mibBuilder.loadTexts: zhoneSonetErrorStatsTable.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsTable.setDescription('Description.') zhoneSonetErrorStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1), ).setIndexNames((0, "ZHONE-PHY-SONET-MIB", "zhoneSonetErrorStatsIndex")) if mibBuilder.loadTexts: zhoneSonetErrorStatsEntry.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsEntry.setDescription('Description.') zhoneSonetErrorStatsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: zhoneSonetErrorStatsIndex.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsIndex.setDescription('Description.') zhoneSonetErrorStatsLineFebeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsLineFebeCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsLineFebeCount.setDescription('Number of RLOP far-end block errors (FEBE).') zhoneSonetErrorStatsPathFebeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsPathFebeCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsPathFebeCount.setDescription('Number of RPOP far-end block errors (FEBE).') zhoneSonetErrorStatsLineBipCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsLineBipCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsLineBipCount.setDescription('Number of Receive Line Overhead Processor (RLOP) BIP-8 errors. The RLOP is responsible for line-level alarms and for monitoring performance.') zhoneSonetErrorStatsSectionBipCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsSectionBipCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsSectionBipCount.setDescription('Number of Receive Section Overhead Processor (RSOP) bit-interleaved parity (BIP)-8 errors. The RSOP synchronizes and descrambles frames and provides section-level alarms and performance monitoring.') zhoneSonetErrorStatsPathBipCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsPathBipCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsPathBipCount.setDescription('Number of Receive Path Overhead Processor (RPOP) BIP-8 errors. The RSOP interprets pointers and extracts path overhead and the synchronous payload envelope. It is also responsible for path-level alarms and for monitoring performance.') zhoneSonetErrorStatsOofCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsOofCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsOofCount.setDescription('Near end is out of frame. False indicates that the line is up and in frame.') zhoneSonetErrorStatsRxCellCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsRxCellCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsRxCellCount.setDescription('Receive ATM Cell Processor (RACP) receive cell count.') zhoneSonetErrorStatsTxCellCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsTxCellCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsTxCellCount.setDescription('Transmit ATM Cell Processor (TACP) transmit cell count.') zhoneSonetErrorStatsHecCorrectedCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsHecCorrectedCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsHecCorrectedCount.setDescription('Number of corrected HEC cells.') zhoneSonetErrorStatsHecUncorrectedCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsHecUncorrectedCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsHecUncorrectedCount.setDescription('Number of uncorrected dropped HEC cells.') zhoneSonetErrorStatsCellFifoOverflowCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsCellFifoOverflowCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsCellFifoOverflowCount.setDescription('Number of cells dropped because of first in, first out (FIFO) overflow.') zhoneSonetErrorStatsLocdCount = MibTableColumn((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zhoneSonetErrorStatsLocdCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsLocdCount.setDescription('Loss of cell delineation.') mibBuilder.exportSymbols("ZHONE-PHY-SONET-MIB", sonetLineStatusChange=sonetLineStatusChange, zhoneSonetErrorStatsPathBipCount=zhoneSonetErrorStatsPathBipCount, zhoneSonetErrorStatsSectionBipCount=zhoneSonetErrorStatsSectionBipCount, sonetTraps=sonetTraps, zhoneSonetErrorStatsPathFebeCount=zhoneSonetErrorStatsPathFebeCount, zhoneSonetErrorStatsRxCellCount=zhoneSonetErrorStatsRxCellCount, sonetMediumExtEntry=sonetMediumExtEntry, sonetMediumExtTable=sonetMediumExtTable, sonetClockEntry=sonetClockEntry, sonetSectionStatusChange=sonetSectionStatusChange, sonetClockExternalRecovery=sonetClockExternalRecovery, sonetClockTransmitSource=sonetClockTransmitSource, sonetMediumExtLineScrmEnabled=sonetMediumExtLineScrmEnabled, zhoneSonetErrorStatsHecCorrectedCount=zhoneSonetErrorStatsHecCorrectedCount, zhoneSonetErrorStatsTable=zhoneSonetErrorStatsTable, zhoneSonetErrorStatsIndex=zhoneSonetErrorStatsIndex, zhoneSonetErrorStatsLineFebeCount=zhoneSonetErrorStatsLineFebeCount, phySonet=phySonet, sonetV2Traps=sonetV2Traps, sonetMediumExtScrambleEnabled=sonetMediumExtScrambleEnabled, zhoneSonetErrorStatsEntry=zhoneSonetErrorStatsEntry, zhoneSonetErrorStatsLineBipCount=zhoneSonetErrorStatsLineBipCount, PYSNMP_MODULE_ID=phySonet, zhoneSonetErrorStatsHecUncorrectedCount=zhoneSonetErrorStatsHecUncorrectedCount, sonetPathStatusChange=sonetPathStatusChange, sonetClockTransmitSourceChange=sonetClockTransmitSourceChange, sonetClockTable=sonetClockTable, zhoneSonetErrorStatsCellFifoOverflowCount=zhoneSonetErrorStatsCellFifoOverflowCount, zhoneSonetErrorStatsOofCount=zhoneSonetErrorStatsOofCount, zhoneSonetErrorStatsLocdCount=zhoneSonetErrorStatsLocdCount, zhoneSonetErrorStatsTxCellCount=zhoneSonetErrorStatsTxCellCount)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint') (interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (unsigned32, bits, counter32, gauge32, mib_identifier, object_identity, counter64, notification_type, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, ip_address, module_identity, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'Bits', 'Counter32', 'Gauge32', 'MibIdentifier', 'ObjectIdentity', 'Counter64', 'NotificationType', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'IpAddress', 'ModuleIdentity', 'TimeTicks') (textual_convention, truth_value, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'TruthValue', 'DisplayString') (sonet_medium_entry, sonet_path_current_status, sonet_section_current_status, sonet_line_current_status) = mibBuilder.importSymbols('SONET-MIB', 'sonetMediumEntry', 'sonetPathCurrentStatus', 'sonetSectionCurrentStatus', 'sonetLineCurrentStatus') (zhone_modules, zhone_sonet) = mibBuilder.importSymbols('Zhone', 'zhoneModules', 'zhoneSonet') phy_sonet = module_identity((1, 3, 6, 1, 4, 1, 5504, 6, 16)) phySonet.setRevisions(('2004-08-18 11:47', '2003-07-10 13:30', '2002-03-26 14:30', '2001-09-12 15:08', '2001-07-19 18:00', '2001-02-22 11:35', '2000-12-19 15:23', '2000-12-18 16:20')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: phySonet.setRevisionsDescriptions(('1.03.04 - Add zhoneSonetErrorStatsTable.', '1.03.02 Add sonetPathStatusChange trap.', '1.03.01 Add sonetSectionStatusChange trap and sonetLineStatusChange trap.', 'V01.03.00 Changed names for valid values for sonetClockTransmitSource', 'V01.02.00 Add Sonet clock source change trap.', 'V01.01.00 - Add Sonet Medium Extension Table.', 'V01.00.01 - Add Zhone keywords.', 'V01.00.00 - Initial Release')) if mibBuilder.loadTexts: phySonet.setLastUpdated('200408181330Z') if mibBuilder.loadTexts: phySonet.setOrganization('Zhone Technologies, Inc.') if mibBuilder.loadTexts: phySonet.setContactInfo(' Postal: Zhone Technologies, Inc. @ Zhone Way 7001 Oakport Street Oakland, CA 94621 USA Toll-Free: +1 877-ZHONE20 (+1 877-946-6320) Tel: +1-510-777-7000 Fax: +1-510-777-7001 E-mail: support@zhone.com') if mibBuilder.loadTexts: phySonet.setDescription('SONET physical MIB to configure and monitor SONET physical attributes. ') sonet_clock_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1)) if mibBuilder.loadTexts: sonetClockTable.setStatus('current') if mibBuilder.loadTexts: sonetClockTable.setDescription('MIB table for clock related configuration for SONET interfaces.') sonet_clock_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1, 1)) sonetMediumEntry.registerAugmentions(('ZHONE-PHY-SONET-MIB', 'sonetClockEntry')) sonetClockEntry.setIndexNames(*sonetMediumEntry.getIndexNames()) if mibBuilder.loadTexts: sonetClockEntry.setStatus('current') if mibBuilder.loadTexts: sonetClockEntry.setDescription('An entry of the sonetClockEntry. sonetClockEntry is augmented to sonetMediumEntry defined in rfc2558.mib. Whenever a row is instantiated in the sonetMediumTable, a corresponding row will be instantiated in the sonetClockTable.') sonet_clock_external_recovery = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: sonetClockExternalRecovery.setStatus('current') if mibBuilder.loadTexts: sonetClockExternalRecovery.setDescription("This variable indicates if external clock recovery is enabled for this SONET interface. The default value is 'enabled'.") sonet_clock_transmit_source = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('loopTiming', 1), ('throughTiming', 2), ('localTiming', 3), ('external155MHz', 4)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: sonetClockTransmitSource.setStatus('current') if mibBuilder.loadTexts: sonetClockTransmitSource.setDescription("This variable describes the SONET transmit clock source. Valid values are: loopTiming - transmit clock synthesized from the recovered receive clock. throughTiming - transmit clock is derived from the recovered receive clock of another SONET interface. localTiming - transmit clock synthesized from a local clock source or that an external clock is attached to the box containing the interface. external155MHz - transmit clock synthesized from an external 155.52 MHz source. The default value is 'loopTiming'. 'external155MHz' option is not valid for Sechtor 100.") sonet_medium_ext_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2)) if mibBuilder.loadTexts: sonetMediumExtTable.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtTable.setDescription('This is an extenion of the standard Sonet MIB (RFC 2558).') sonet_medium_ext_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2, 1)) sonetMediumEntry.registerAugmentions(('ZHONE-PHY-SONET-MIB', 'sonetMediumExtEntry')) sonetMediumExtEntry.setIndexNames(*sonetMediumEntry.getIndexNames()) if mibBuilder.loadTexts: sonetMediumExtEntry.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtEntry.setDescription('Each row is an extension to the sonetMediumTable for Zhone specific fields. This row is created when the augmented sonetMediumEntry is created.') sonet_medium_ext_scramble_enabled = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2, 1, 1), truth_value().clone('true')).setMaxAccess('readwrite') if mibBuilder.loadTexts: sonetMediumExtScrambleEnabled.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtScrambleEnabled.setDescription('This field describes the enabled status of the Sonet Scramble mode. If this field is true(1) then Scramble mode is enabled, if this field is false(2) scramble mode is disable.') sonet_medium_ext_line_scrm_enabled = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 2, 1, 2), truth_value().clone('true')).setMaxAccess('readwrite') if mibBuilder.loadTexts: sonetMediumExtLineScrmEnabled.setStatus('current') if mibBuilder.loadTexts: sonetMediumExtLineScrmEnabled.setDescription('This field describes the enabled status of the Line level Sonet Scramble mode. If this field is true(1), then Scramble mode is enabled. If this field is false(2), scramble mode is disable.') sonet_traps = object_identity((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3)) if mibBuilder.loadTexts: sonetTraps.setStatus('current') if mibBuilder.loadTexts: sonetTraps.setDescription('All Zhone Sonet traps will be defined under this object identity.') sonet_v2_traps = object_identity((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0)) if mibBuilder.loadTexts: sonetV2Traps.setStatus('current') if mibBuilder.loadTexts: sonetV2Traps.setDescription('This object identity adds a zero(0) for the next to last sub-identifier which should be used for new SNMPv2 Traps.') sonet_clock_transmit_source_change = notification_type((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 1)).setObjects(('ZHONE-PHY-SONET-MIB', 'sonetClockExternalRecovery'), ('ZHONE-PHY-SONET-MIB', 'sonetClockTransmitSource')) if mibBuilder.loadTexts: sonetClockTransmitSourceChange.setStatus('current') if mibBuilder.loadTexts: sonetClockTransmitSourceChange.setDescription('A notification trap is sent when either sonetClockExternalRecovery or sonetClockTransmitSource is changed. The trap object is identified by the OID instance of sonetClockTransmitSource described in the OBJECTS clause.') sonet_section_status_change = notification_type((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 2)).setObjects(('SONET-MIB', 'sonetSectionCurrentStatus')) if mibBuilder.loadTexts: sonetSectionStatusChange.setStatus('current') if mibBuilder.loadTexts: sonetSectionStatusChange.setDescription('A notification trap is sent when there is a change in the sonet SECTION status. Currenly the following are supported: NO-DEFECT = 1 LOS = 2 LOF = 4 The trap object is identified by the OID instance of sonetSectionCurrentStatus described in the OBJECTS clause.') sonet_line_status_change = notification_type((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 3)).setObjects(('SONET-MIB', 'sonetLineCurrentStatus')) if mibBuilder.loadTexts: sonetLineStatusChange.setStatus('current') if mibBuilder.loadTexts: sonetLineStatusChange.setDescription('A notification trap is sent when there is a change in the sonet LINE status. Currenly the following are supported: NO-DEFECT = 1 AIS = 2 RDI = 4 The trap object is identified by the OID instance of sonetLineCurrentStatus described in the OBJECTS clause.') sonet_path_status_change = notification_type((1, 3, 6, 1, 4, 1, 5504, 5, 9, 3, 0, 4)).setObjects(('SONET-MIB', 'sonetPathCurrentStatus')) if mibBuilder.loadTexts: sonetPathStatusChange.setStatus('current') if mibBuilder.loadTexts: sonetPathStatusChange.setDescription('A notification trap is sent when there is a change in the sonetPathCurrentStatus. Currenly the following are supported: 1 sonetPathNoDefect 2 sonetPathSTSLOP 4 sonetPathSTSAIS 8 sonetPathSTSRDI 16 sonetPathUnequipped 32 sonetPathSignalLabelMismatch The trap object is identified by the OID instance of sonetPathCurrentStatus described in the OBJECTS clause.') zhone_sonet_error_stats_table = mib_table((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6)) if mibBuilder.loadTexts: zhoneSonetErrorStatsTable.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsTable.setDescription('Description.') zhone_sonet_error_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1)).setIndexNames((0, 'ZHONE-PHY-SONET-MIB', 'zhoneSonetErrorStatsIndex')) if mibBuilder.loadTexts: zhoneSonetErrorStatsEntry.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsEntry.setDescription('Description.') zhone_sonet_error_stats_index = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 1), interface_index()) if mibBuilder.loadTexts: zhoneSonetErrorStatsIndex.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsIndex.setDescription('Description.') zhone_sonet_error_stats_line_febe_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsLineFebeCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsLineFebeCount.setDescription('Number of RLOP far-end block errors (FEBE).') zhone_sonet_error_stats_path_febe_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsPathFebeCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsPathFebeCount.setDescription('Number of RPOP far-end block errors (FEBE).') zhone_sonet_error_stats_line_bip_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsLineBipCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsLineBipCount.setDescription('Number of Receive Line Overhead Processor (RLOP) BIP-8 errors. The RLOP is responsible for line-level alarms and for monitoring performance.') zhone_sonet_error_stats_section_bip_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsSectionBipCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsSectionBipCount.setDescription('Number of Receive Section Overhead Processor (RSOP) bit-interleaved parity (BIP)-8 errors. The RSOP synchronizes and descrambles frames and provides section-level alarms and performance monitoring.') zhone_sonet_error_stats_path_bip_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsPathBipCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsPathBipCount.setDescription('Number of Receive Path Overhead Processor (RPOP) BIP-8 errors. The RSOP interprets pointers and extracts path overhead and the synchronous payload envelope. It is also responsible for path-level alarms and for monitoring performance.') zhone_sonet_error_stats_oof_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsOofCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsOofCount.setDescription('Near end is out of frame. False indicates that the line is up and in frame.') zhone_sonet_error_stats_rx_cell_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 8), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsRxCellCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsRxCellCount.setDescription('Receive ATM Cell Processor (RACP) receive cell count.') zhone_sonet_error_stats_tx_cell_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 9), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsTxCellCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsTxCellCount.setDescription('Transmit ATM Cell Processor (TACP) transmit cell count.') zhone_sonet_error_stats_hec_corrected_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 10), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsHecCorrectedCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsHecCorrectedCount.setDescription('Number of corrected HEC cells.') zhone_sonet_error_stats_hec_uncorrected_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 11), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsHecUncorrectedCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsHecUncorrectedCount.setDescription('Number of uncorrected dropped HEC cells.') zhone_sonet_error_stats_cell_fifo_overflow_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 12), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsCellFifoOverflowCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsCellFifoOverflowCount.setDescription('Number of cells dropped because of first in, first out (FIFO) overflow.') zhone_sonet_error_stats_locd_count = mib_table_column((1, 3, 6, 1, 4, 1, 5504, 5, 9, 6, 1, 13), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: zhoneSonetErrorStatsLocdCount.setStatus('current') if mibBuilder.loadTexts: zhoneSonetErrorStatsLocdCount.setDescription('Loss of cell delineation.') mibBuilder.exportSymbols('ZHONE-PHY-SONET-MIB', sonetLineStatusChange=sonetLineStatusChange, zhoneSonetErrorStatsPathBipCount=zhoneSonetErrorStatsPathBipCount, zhoneSonetErrorStatsSectionBipCount=zhoneSonetErrorStatsSectionBipCount, sonetTraps=sonetTraps, zhoneSonetErrorStatsPathFebeCount=zhoneSonetErrorStatsPathFebeCount, zhoneSonetErrorStatsRxCellCount=zhoneSonetErrorStatsRxCellCount, sonetMediumExtEntry=sonetMediumExtEntry, sonetMediumExtTable=sonetMediumExtTable, sonetClockEntry=sonetClockEntry, sonetSectionStatusChange=sonetSectionStatusChange, sonetClockExternalRecovery=sonetClockExternalRecovery, sonetClockTransmitSource=sonetClockTransmitSource, sonetMediumExtLineScrmEnabled=sonetMediumExtLineScrmEnabled, zhoneSonetErrorStatsHecCorrectedCount=zhoneSonetErrorStatsHecCorrectedCount, zhoneSonetErrorStatsTable=zhoneSonetErrorStatsTable, zhoneSonetErrorStatsIndex=zhoneSonetErrorStatsIndex, zhoneSonetErrorStatsLineFebeCount=zhoneSonetErrorStatsLineFebeCount, phySonet=phySonet, sonetV2Traps=sonetV2Traps, sonetMediumExtScrambleEnabled=sonetMediumExtScrambleEnabled, zhoneSonetErrorStatsEntry=zhoneSonetErrorStatsEntry, zhoneSonetErrorStatsLineBipCount=zhoneSonetErrorStatsLineBipCount, PYSNMP_MODULE_ID=phySonet, zhoneSonetErrorStatsHecUncorrectedCount=zhoneSonetErrorStatsHecUncorrectedCount, sonetPathStatusChange=sonetPathStatusChange, sonetClockTransmitSourceChange=sonetClockTransmitSourceChange, sonetClockTable=sonetClockTable, zhoneSonetErrorStatsCellFifoOverflowCount=zhoneSonetErrorStatsCellFifoOverflowCount, zhoneSonetErrorStatsOofCount=zhoneSonetErrorStatsOofCount, zhoneSonetErrorStatsLocdCount=zhoneSonetErrorStatsLocdCount, zhoneSonetErrorStatsTxCellCount=zhoneSonetErrorStatsTxCellCount)
### SATISFACTORY RESPONSE ## Not found code OK = 200 OK_NOCONTENT = 204 ### CLIENT ERROR ## Not found code NOT_FOUND = 404 UNAUTHORIZED = 401 ### SERVER ERROR ## Internal server error INTERNAL_ERROR = 500
ok = 200 ok_nocontent = 204 not_found = 404 unauthorized = 401 internal_error = 500
""" Time complexity O(n) """ # Search for maximum number l = [2, 4, 5, 1, 80, 5, 99] maximum = l[0] for item in l: if item > maximum: maximum = item print(maximum)
""" Time complexity O(n) """ l = [2, 4, 5, 1, 80, 5, 99] maximum = l[0] for item in l: if item > maximum: maximum = item print(maximum)
# DESCRIPTION # Return the root node of a binary search tree that matches the given preorder traversal. # It's guaranteed that for the given test cases there is always possible to find a # binary search tree with the given requirements. # EXAMPLE # Input: [8,5,1,7,10,12] # Output: [8,5,10,1,7,null,12] # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: ''' Time: O(N), Must iterate over every element of the list Space: O(N), max space needed for recursive stack ''' self.index = 0 return self.bst_build(preorder, float('inf')) def bst_build(self, preorder, limit): # if we have run out of numbers in list # or the curr val is larger than the limit if self.index >= len(preorder) or preorder[self.index] > limit: return None root = TreeNode(preorder[self.index]) # inc to move with the list self.index += 1 # must not be larger than the parent value root.left = self.bst_build(preorder, root.val) # must not be larger than the parents limit root.right = self.bst_build(preorder, limit) return root
class Solution: def bst_from_preorder(self, preorder: List[int]) -> TreeNode: """ Time: O(N), Must iterate over every element of the list Space: O(N), max space needed for recursive stack """ self.index = 0 return self.bst_build(preorder, float('inf')) def bst_build(self, preorder, limit): if self.index >= len(preorder) or preorder[self.index] > limit: return None root = tree_node(preorder[self.index]) self.index += 1 root.left = self.bst_build(preorder, root.val) root.right = self.bst_build(preorder, limit) return root
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None ## mergesort class Solution(object): def sortList(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head p,s,f = None, head, head while f and f.next: p,s,f = s,s.next,f.next.next p.next=None return self.merge(self.sortList(head), self.sortList(s)) def merge(self, h1, h2): res=res0=ListNode(0) while h1 or h2: if h1 and h2: if h1.val<=h2.val: res.next = h1 res = res.next h1 = h1.next res.next = None else: res.next = h2 res = res.next h2 = h2.next res.next = None elif h1: res.next = h1 h1 = None else: res.next = h2 h2 = None return res0.next
class Solution(object): def sort_list(self, head): """ :type head: ListNode :rtype: ListNode """ if not head or not head.next: return head (p, s, f) = (None, head, head) while f and f.next: (p, s, f) = (s, s.next, f.next.next) p.next = None return self.merge(self.sortList(head), self.sortList(s)) def merge(self, h1, h2): res = res0 = list_node(0) while h1 or h2: if h1 and h2: if h1.val <= h2.val: res.next = h1 res = res.next h1 = h1.next res.next = None else: res.next = h2 res = res.next h2 = h2.next res.next = None elif h1: res.next = h1 h1 = None else: res.next = h2 h2 = None return res0.next
def find_floor(brackets: str) -> int: return sum(1 if c == '(' else -1 for c in brackets) def find_basement_entry(brackets: str) -> int: return [n + 1 for n in range(len(brackets)) if find_floor(brackets[:n + 1]) == -1][0] if __name__ == '__main__': with open('input') as f: bracket_text = f.read() print(f'Part 1: {find_floor(bracket_text)}') print(f'Part 2: {find_basement_entry(bracket_text)}')
def find_floor(brackets: str) -> int: return sum((1 if c == '(' else -1 for c in brackets)) def find_basement_entry(brackets: str) -> int: return [n + 1 for n in range(len(brackets)) if find_floor(brackets[:n + 1]) == -1][0] if __name__ == '__main__': with open('input') as f: bracket_text = f.read() print(f'Part 1: {find_floor(bracket_text)}') print(f'Part 2: {find_basement_entry(bracket_text)}')
result = [ None, 6, ['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}], {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}, {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}, ['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}], None, 6 ] def is_equal(a, b, message): comparable_a = [ a[0], a[1], [a[2][0], a[2][1], a[2][2], {'uu': a[2][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], {'uu': a[3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, {'uu': a[4]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, [a[5][0], a[5][1], a[5][2], {'uu': a[5][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], a[6], a[7] ] comparable_b = [ b[0], b[1], [b[2][0], b[2][1], b[2][2], {'uu': b[2][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], {'uu': b[3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, {'uu': b[4]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, [b[5][0], b[5][1], b[5][2], {'uu': b[5][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], b[6], b[7] ] if len(a) != len(b): raise AssertionError(message + ': Array length differs') non_recursive_a = [a[0], a[1], a[-2], a[-1]] non_recursive_b = [b[0], b[1], b[-2], b[-1]] if non_recursive_a != non_recursive_b: raise AssertionError(message + ': non-recursive part differs') if comparable_a != comparable_b: raise AssertionError(message + ': recursive part differs')
result = [None, 6, ['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}], {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}, {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}, ['a', 'b', 'c', {'uu': 5.6, 'oo': [Ellipsis], 'ii': {Ellipsis}}], None, 6] def is_equal(a, b, message): comparable_a = [a[0], a[1], [a[2][0], a[2][1], a[2][2], {'uu': a[2][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], {'uu': a[3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, {'uu': a[4]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, [a[5][0], a[5][1], a[5][2], {'uu': a[5][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], a[6], a[7]] comparable_b = [b[0], b[1], [b[2][0], b[2][1], b[2][2], {'uu': b[2][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], {'uu': b[3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, {'uu': b[4]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}, [b[5][0], b[5][1], b[5][2], {'uu': b[5][3]['uu'], 'oo': [Ellipsis], 'ii': [Ellipsis]}], b[6], b[7]] if len(a) != len(b): raise assertion_error(message + ': Array length differs') non_recursive_a = [a[0], a[1], a[-2], a[-1]] non_recursive_b = [b[0], b[1], b[-2], b[-1]] if non_recursive_a != non_recursive_b: raise assertion_error(message + ': non-recursive part differs') if comparable_a != comparable_b: raise assertion_error(message + ': recursive part differs')
p1, p2 = map(int, input().split()) m = (p1 + p2) / 2 if m >= 7: print(f'{m} - Aprovado', end='') elif m < 5: print(f'{m} - Reprovado', end='') else: print(f'{m} - De Recuperacao', end='')
(p1, p2) = map(int, input().split()) m = (p1 + p2) / 2 if m >= 7: print(f'{m} - Aprovado', end='') elif m < 5: print(f'{m} - Reprovado', end='') else: print(f'{m} - De Recuperacao', end='')
"""680. Valid Palindrome II https://leetcode.com/problems/valid-palindrome-ii/ """ class Solution: def validPalindrome(self, s: str) -> bool: def helper(i: int, j: int, flag: bool) -> bool: while i < j: if s[i] == s[j]: i += 1 j -= 1 elif not flag: return False else: return helper(i + 1, j, False) or helper(i, j - 1, False) return True return helper(0, len(s) - 1, True)
"""680. Valid Palindrome II https://leetcode.com/problems/valid-palindrome-ii/ """ class Solution: def valid_palindrome(self, s: str) -> bool: def helper(i: int, j: int, flag: bool) -> bool: while i < j: if s[i] == s[j]: i += 1 j -= 1 elif not flag: return False else: return helper(i + 1, j, False) or helper(i, j - 1, False) return True return helper(0, len(s) - 1, True)
# # PySNMP MIB module RADIUS-ACCOUNTING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/RADIUS-ACCOUNTING-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:44:47 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) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection") dlink_common_mgmt, = mibBuilder.importSymbols("DLINK-ID-REC-MIB", "dlink-common-mgmt") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, Gauge32, Counter32, iso, ObjectIdentity, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Integer32, ModuleIdentity, Bits, NotificationType, Counter64, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Gauge32", "Counter32", "iso", "ObjectIdentity", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Integer32", "ModuleIdentity", "Bits", "NotificationType", "Counter64", "Unsigned32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") swRadiusAccountMGMTMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 171, 12, 55)) if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setLastUpdated('0712200000Z') if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setOrganization('D-Link Corp.') if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setContactInfo('http://support.dlink.com') if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setDescription('The structure of RADIUS accounting for the proprietary enterprise.') radiusAccountCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 171, 12, 55, 1)) accountingShellState = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 55, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: accountingShellState.setStatus('current') if mibBuilder.loadTexts: accountingShellState.setDescription('Specifies the status of the RADIUS accounting service for shell events.') accountingSystemState = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 55, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: accountingSystemState.setStatus('current') if mibBuilder.loadTexts: accountingSystemState.setDescription('Specifies the status of the RADIUS accounting service for system events.') accountingNetworkState = MibScalar((1, 3, 6, 1, 4, 1, 171, 12, 55, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite") if mibBuilder.loadTexts: accountingNetworkState.setStatus('current') if mibBuilder.loadTexts: accountingNetworkState.setDescription('Specifies the status of the RADIUS accounting service for 802.1x port access control.') mibBuilder.exportSymbols("RADIUS-ACCOUNTING-MIB", accountingShellState=accountingShellState, accountingSystemState=accountingSystemState, PYSNMP_MODULE_ID=swRadiusAccountMGMTMIB, radiusAccountCtrl=radiusAccountCtrl, swRadiusAccountMGMTMIB=swRadiusAccountMGMTMIB, accountingNetworkState=accountingNetworkState)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection') (dlink_common_mgmt,) = mibBuilder.importSymbols('DLINK-ID-REC-MIB', 'dlink-common-mgmt') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (ip_address, gauge32, counter32, iso, object_identity, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, integer32, module_identity, bits, notification_type, counter64, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Gauge32', 'Counter32', 'iso', 'ObjectIdentity', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'Integer32', 'ModuleIdentity', 'Bits', 'NotificationType', 'Counter64', 'Unsigned32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') sw_radius_account_mgmtmib = module_identity((1, 3, 6, 1, 4, 1, 171, 12, 55)) if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setLastUpdated('0712200000Z') if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setOrganization('D-Link Corp.') if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setContactInfo('http://support.dlink.com') if mibBuilder.loadTexts: swRadiusAccountMGMTMIB.setDescription('The structure of RADIUS accounting for the proprietary enterprise.') radius_account_ctrl = mib_identifier((1, 3, 6, 1, 4, 1, 171, 12, 55, 1)) accounting_shell_state = mib_scalar((1, 3, 6, 1, 4, 1, 171, 12, 55, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: accountingShellState.setStatus('current') if mibBuilder.loadTexts: accountingShellState.setDescription('Specifies the status of the RADIUS accounting service for shell events.') accounting_system_state = mib_scalar((1, 3, 6, 1, 4, 1, 171, 12, 55, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: accountingSystemState.setStatus('current') if mibBuilder.loadTexts: accountingSystemState.setDescription('Specifies the status of the RADIUS accounting service for system events.') accounting_network_state = mib_scalar((1, 3, 6, 1, 4, 1, 171, 12, 55, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readwrite') if mibBuilder.loadTexts: accountingNetworkState.setStatus('current') if mibBuilder.loadTexts: accountingNetworkState.setDescription('Specifies the status of the RADIUS accounting service for 802.1x port access control.') mibBuilder.exportSymbols('RADIUS-ACCOUNTING-MIB', accountingShellState=accountingShellState, accountingSystemState=accountingSystemState, PYSNMP_MODULE_ID=swRadiusAccountMGMTMIB, radiusAccountCtrl=radiusAccountCtrl, swRadiusAccountMGMTMIB=swRadiusAccountMGMTMIB, accountingNetworkState=accountingNetworkState)
#Prints the number in matrix form def print_numbers(number): for i in range(1,number+1): for j in range(1, number+1): print(i,end=" ") print() number=int(input("please enter a number: ")) if number%2==0: print_numbers(number+1) else: print_numbers(number-1)
def print_numbers(number): for i in range(1, number + 1): for j in range(1, number + 1): print(i, end=' ') print() number = int(input('please enter a number: ')) if number % 2 == 0: print_numbers(number + 1) else: print_numbers(number - 1)
class Blackjack(): def __init__(self, cards): self.cards = cards def hand(self): """makes a list of your card values Returns: list: e.g. [1, 12] """ deck = { 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 'j': 10, 'q': 10, 'k': 10, 'a': 11 } result = [] for i in self.cards: result.append(deck[i]) return result def hand_value(self): """returns the sum of hand values Returns: int: simple hand value """ hand = self.hand() result = sum(hand) if 'a' in self.cards and result > 21: result -= 10 return result
class Blackjack: def __init__(self, cards): self.cards = cards def hand(self): """makes a list of your card values Returns: list: e.g. [1, 12] """ deck = {1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, 10: 10, 'j': 10, 'q': 10, 'k': 10, 'a': 11} result = [] for i in self.cards: result.append(deck[i]) return result def hand_value(self): """returns the sum of hand values Returns: int: simple hand value """ hand = self.hand() result = sum(hand) if 'a' in self.cards and result > 21: result -= 10 return result
def bar_spec(data): return { "config": { "view": {"continuousWidth": 400, "continuousHeight": 300}, "mark": {"opacity": 0.75} }, "layer": [ { "mark": {"type": "bar", "color": "red"}, "encoding": { "x": {"type": "nominal", "field": "subject"}, "y": { "type": "quantitative", "field": "percentage of input passed filter" } } }, { "mark": {"type": "bar", "color": "yellow"}, "encoding": { "x": {"type": "nominal", "field": "subject"}, "y": { "type": "quantitative", "field": "percentage of input non-chimeric" } } } ], "data": { "values": data }, "height": 600, "title": "% passed the filter and % non-chimeric for sample ID's", "width": 800, "$schema": "https://vega.github.io/schema/vega-lite/v4.8.1.json" }
def bar_spec(data): return {'config': {'view': {'continuousWidth': 400, 'continuousHeight': 300}, 'mark': {'opacity': 0.75}}, 'layer': [{'mark': {'type': 'bar', 'color': 'red'}, 'encoding': {'x': {'type': 'nominal', 'field': 'subject'}, 'y': {'type': 'quantitative', 'field': 'percentage of input passed filter'}}}, {'mark': {'type': 'bar', 'color': 'yellow'}, 'encoding': {'x': {'type': 'nominal', 'field': 'subject'}, 'y': {'type': 'quantitative', 'field': 'percentage of input non-chimeric'}}}], 'data': {'values': data}, 'height': 600, 'title': "% passed the filter and % non-chimeric for sample ID's", 'width': 800, '$schema': 'https://vega.github.io/schema/vega-lite/v4.8.1.json'}
#!/usr/bin/env python # # Copyright (C) 2017 ShadowMan # class FatalError(Exception): pass class FrameHeaderParseError(Exception): pass class ConnectClosed(Exception): pass class RequestError(Exception): pass class LoggerWarning(RuntimeWarning): pass class DeamonError(Exception): pass class SendDataPackError(Exception): pass class InvalidResponse(Exception): pass class ParameterError(Exception): pass def raise_parameter_error(name, except_type, got_val): if not isinstance(got_val, except_type): raise ParameterError( '{name} except {except_type}, got {got_type}'.format( name=name, except_type=except_type.__name__, got_type=type(got_val).__name__)) class ExitWrite(Exception): pass class BroadcastError(Exception): pass class HttpVerifierError(Exception): pass class FrameVerifierError(Exception): pass class WSSCertificateFileNotFound(Exception): pass
class Fatalerror(Exception): pass class Frameheaderparseerror(Exception): pass class Connectclosed(Exception): pass class Requesterror(Exception): pass class Loggerwarning(RuntimeWarning): pass class Deamonerror(Exception): pass class Senddatapackerror(Exception): pass class Invalidresponse(Exception): pass class Parametererror(Exception): pass def raise_parameter_error(name, except_type, got_val): if not isinstance(got_val, except_type): raise parameter_error('{name} except {except_type}, got {got_type}'.format(name=name, except_type=except_type.__name__, got_type=type(got_val).__name__)) class Exitwrite(Exception): pass class Broadcasterror(Exception): pass class Httpverifiererror(Exception): pass class Frameverifiererror(Exception): pass class Wsscertificatefilenotfound(Exception): pass
#!/usr/bin/env python #coding: utf-8 # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # @return a ListNode def addTwoNumbers(self, l1, l2): h = ch = ListNode(-1) n1, n2, c = l1, l2, 0 while n1 or n2: a = n1.val if n1 else 0 b = n2.val if n2 else 0 s = a + b + c ch.next = ListNode(s % 10) c = s / 10 ch = ch.next if n1: n1 = n1.next if n2: n2 = n2.next if c: ch.next = ListNode(c) return h.next def printL(x): for i in x: print(i.val), print('') if __name__ == '__main__': t0 = [ListNode(i) for i in (2,4,3)] t0[0].next = t0[1] t0[1].next == t0[2] t1 = [ListNode(i) for i in (5,6,4)] t1[0].next = t1[1] t1[1].next == t1[2] t2 = [ListNode(i) for i in (7,0,8)] t2[0].next = t2[1] t2[1].next == t2[2] printL(t0), printL(t1), printL(t2) s = Solution() assert t2[0].val == s.addTwoNumbers(t0[0], t1[0]).val
class Listnode: def __init__(self, x): self.val = x self.next = None class Solution: def add_two_numbers(self, l1, l2): h = ch = list_node(-1) (n1, n2, c) = (l1, l2, 0) while n1 or n2: a = n1.val if n1 else 0 b = n2.val if n2 else 0 s = a + b + c ch.next = list_node(s % 10) c = s / 10 ch = ch.next if n1: n1 = n1.next if n2: n2 = n2.next if c: ch.next = list_node(c) return h.next def print_l(x): for i in x: (print(i.val),) print('') if __name__ == '__main__': t0 = [list_node(i) for i in (2, 4, 3)] t0[0].next = t0[1] t0[1].next == t0[2] t1 = [list_node(i) for i in (5, 6, 4)] t1[0].next = t1[1] t1[1].next == t1[2] t2 = [list_node(i) for i in (7, 0, 8)] t2[0].next = t2[1] t2[1].next == t2[2] (print_l(t0), print_l(t1), print_l(t2)) s = solution() assert t2[0].val == s.addTwoNumbers(t0[0], t1[0]).val
def is_uppercase(letter: str): return True if 65 <= ord(letter) <= 90 else False def is_lowercase(letter: str): return True if 97 <= ord(letter) <= 122 else False def check_same_case(first: str, second: str) -> bool: if is_uppercase(first) and is_uppercase(second): return True if is_lowercase(first) and is_lowercase(second): return True return False def main(): same_case = check_same_case('?', '?') print(same_case) if __name__ == '__main__': main()
def is_uppercase(letter: str): return True if 65 <= ord(letter) <= 90 else False def is_lowercase(letter: str): return True if 97 <= ord(letter) <= 122 else False def check_same_case(first: str, second: str) -> bool: if is_uppercase(first) and is_uppercase(second): return True if is_lowercase(first) and is_lowercase(second): return True return False def main(): same_case = check_same_case('?', '?') print(same_case) if __name__ == '__main__': main()
# ========================= VMWriter CLASS class VMEncoder(object): """ VM encoder for the CompilationEngine of the Jack compiler. """ def encodePush(self, segment, index): """ Creates VM push command based on the input. args: segment: (str) segment to operate on index: (int) index of the desired segment ret: string containing VM push command """ if segment == 'const': return 'push constant '+ str(index) +'\n' elif segment == 'arg': return 'push argument '+ str(index) +'\n' elif segment == 'local': return 'push local '+ str(index) +'\n' elif segment == 'static': return 'push static '+ str(index) +'\n' elif segment == 'this': return 'push this '+ str(index) +'\n' elif segment == 'that': return 'push that '+ str(index) +'\n' elif segment == 'pointer': return 'push pointer '+ str(index) +'\n' elif segment == 'temp': return 'push temp '+ str(index) +'\n' else: raise TypeError("Invalid segment type for writePush operation. Segment type: '{}'" .format(segment)) def encodePop(self, segment, index): """ Creates VM pop command based on the input. args: segment: (str) segment to operate on index: (int) index of the desired segment ret: string containing VM push command """ if segment == 'arg': return 'pop argument '+ str(index) +'\n' elif segment == 'local': return 'pop local '+ str(index) +'\n' elif segment == 'static': return 'pop static '+ str(index) +'\n' elif segment == 'this': return 'pop this '+ str(index) +'\n' elif segment == 'that': return 'pop that '+ str(index) +'\n' elif segment == 'pointer': return 'pop pointer '+ str(index) +'\n' elif segment == 'temp': return 'pop temp '+ str(index) +'\n' else: raise TypeError("Invalid segment type for writePop operation. Segment type: '{}'" .format(segment)) def encodeArithmetic(self, command): """ Creates VM arithmetic commands based on the input. args: command: (str) command to be encoded ret: string containing VM arithmetic command """ if command in ['+', 'add']: return 'add'+'\n' elif command in ['-', 'sub']: return 'sub'+'\n' elif command == '*': return 'call Math.multiply 2'+'\n' elif command == '/': return 'call Math.divide 2'+'\n' elif command == '&amp;': return 'and'+'\n' elif command == '|': return 'or'+'\n' elif command == '&lt;': return 'lt'+'\n' elif command == '&gt;': return 'gt'+'\n' elif command == '=': return 'eq'+'\n' elif command == 'not': return 'not'+'\n' elif command == 'neg': return 'neg'+'\n' else: raise TypeError("Invalid command for writeArithmetic operation. Command given: '{}'" .format(command)) def encodeLabel(self, label): """ Creates VM label command based on the input. args: label: (str) label to encode ret: string containing VM label command """ return 'label '+ label +'\n' def encodeGoto(self, label): """ Creates VM goto command based on the input. args: label: (str) label to go to ret: string containing VM goto command """ return 'goto '+ label +'\n' def encodeIfgoto(self, label): """ Creates VM if-goto command based on the input. args: label: (str) label to go to if latest stack entry is true ret: string containing VM if-goto command """ return 'if-goto '+ label +'\n' def encodeCall(self, name, nArgs): """ Creates VM function call command based on the input. args: name: (str) name of the function to be called nArgs: (int) number of arguments the function should expect ret: string containing VM function call command """ return 'call '+ name +' '+ str(nArgs) +'\n' def encodeFunction(self, name, nVars): """ Creates VM function declaration command based on the input. args: name: (str) name of the function to be declared nVars: (int) number of local variables the function has ret: string containing VM function declaration command """ return 'function '+ name +' '+ str(nVars) +'\n' def encodeReturn(self): """ Creates VM return command. """ return 'return'+'\n'
class Vmencoder(object): """ VM encoder for the CompilationEngine of the Jack compiler. """ def encode_push(self, segment, index): """ Creates VM push command based on the input. args: segment: (str) segment to operate on index: (int) index of the desired segment ret: string containing VM push command """ if segment == 'const': return 'push constant ' + str(index) + '\n' elif segment == 'arg': return 'push argument ' + str(index) + '\n' elif segment == 'local': return 'push local ' + str(index) + '\n' elif segment == 'static': return 'push static ' + str(index) + '\n' elif segment == 'this': return 'push this ' + str(index) + '\n' elif segment == 'that': return 'push that ' + str(index) + '\n' elif segment == 'pointer': return 'push pointer ' + str(index) + '\n' elif segment == 'temp': return 'push temp ' + str(index) + '\n' else: raise type_error("Invalid segment type for writePush operation. Segment type: '{}'".format(segment)) def encode_pop(self, segment, index): """ Creates VM pop command based on the input. args: segment: (str) segment to operate on index: (int) index of the desired segment ret: string containing VM push command """ if segment == 'arg': return 'pop argument ' + str(index) + '\n' elif segment == 'local': return 'pop local ' + str(index) + '\n' elif segment == 'static': return 'pop static ' + str(index) + '\n' elif segment == 'this': return 'pop this ' + str(index) + '\n' elif segment == 'that': return 'pop that ' + str(index) + '\n' elif segment == 'pointer': return 'pop pointer ' + str(index) + '\n' elif segment == 'temp': return 'pop temp ' + str(index) + '\n' else: raise type_error("Invalid segment type for writePop operation. Segment type: '{}'".format(segment)) def encode_arithmetic(self, command): """ Creates VM arithmetic commands based on the input. args: command: (str) command to be encoded ret: string containing VM arithmetic command """ if command in ['+', 'add']: return 'add' + '\n' elif command in ['-', 'sub']: return 'sub' + '\n' elif command == '*': return 'call Math.multiply 2' + '\n' elif command == '/': return 'call Math.divide 2' + '\n' elif command == '&amp;': return 'and' + '\n' elif command == '|': return 'or' + '\n' elif command == '&lt;': return 'lt' + '\n' elif command == '&gt;': return 'gt' + '\n' elif command == '=': return 'eq' + '\n' elif command == 'not': return 'not' + '\n' elif command == 'neg': return 'neg' + '\n' else: raise type_error("Invalid command for writeArithmetic operation. Command given: '{}'".format(command)) def encode_label(self, label): """ Creates VM label command based on the input. args: label: (str) label to encode ret: string containing VM label command """ return 'label ' + label + '\n' def encode_goto(self, label): """ Creates VM goto command based on the input. args: label: (str) label to go to ret: string containing VM goto command """ return 'goto ' + label + '\n' def encode_ifgoto(self, label): """ Creates VM if-goto command based on the input. args: label: (str) label to go to if latest stack entry is true ret: string containing VM if-goto command """ return 'if-goto ' + label + '\n' def encode_call(self, name, nArgs): """ Creates VM function call command based on the input. args: name: (str) name of the function to be called nArgs: (int) number of arguments the function should expect ret: string containing VM function call command """ return 'call ' + name + ' ' + str(nArgs) + '\n' def encode_function(self, name, nVars): """ Creates VM function declaration command based on the input. args: name: (str) name of the function to be declared nVars: (int) number of local variables the function has ret: string containing VM function declaration command """ return 'function ' + name + ' ' + str(nVars) + '\n' def encode_return(self): """ Creates VM return command. """ return 'return' + '\n'
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ listL1, listL2 = "", "" while l1 != None: if l1: listL1 += str(l1.val) l1 = l1.next while l2 != None: if l2: listL2 += str(l2.val) l2 = l2.next sum = (str(int(listL1[::-1]) + int(listL2[::-1])))[::-1] sumNode = None currentNode = None for number in sum: node = ListNode(int(number)) if not sumNode: sumNode = node currentNode = node else: currentNode.next = node currentNode = node return sumNode
class Listnode(object): def __init__(self, x): self.val = x self.next = None class Solution(object): def add_two_numbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ (list_l1, list_l2) = ('', '') while l1 != None: if l1: list_l1 += str(l1.val) l1 = l1.next while l2 != None: if l2: list_l2 += str(l2.val) l2 = l2.next sum = str(int(listL1[::-1]) + int(listL2[::-1]))[::-1] sum_node = None current_node = None for number in sum: node = list_node(int(number)) if not sumNode: sum_node = node current_node = node else: currentNode.next = node current_node = node return sumNode
""" z-matrix writers """ def write(syms, key_mat, name_mat, val_dct, mat_delim=' ', setval_sign='='): """ write a z-matrix to a string """ mat_str = matrix_block(syms=syms, key_mat=key_mat, name_mat=name_mat, delim=mat_delim) setval_str = setval_block(val_dct=val_dct, setval_sign=setval_sign) zma_str = '\n\n'.join((mat_str, setval_str)) return zma_str def matrix_block(syms, key_mat, name_mat, delim=' '): """ write the .zmat matrix block to a string """ def _line_string(row_idx): line_str = '{:<2s} '.format(syms[row_idx]) keys = key_mat[row_idx] names = name_mat[row_idx] line_str += delim.join([ '{:>d}{}{:>5s} '.format(keys[col_idx], delim, names[col_idx]) for col_idx in range(min(row_idx, 3))]) return line_str natms = len(syms) mat_str = '\n'.join([_line_string(row_idx) for row_idx in range(natms)]) return mat_str def setval_block(val_dct, setval_sign='='): """ write the .zmat setval block to a string """ setval_str = '\n'.join([ '{:<5s}{}{:>11.6f}'.format(name, setval_sign, val) for name, val in val_dct.items()]) return setval_str
""" z-matrix writers """ def write(syms, key_mat, name_mat, val_dct, mat_delim=' ', setval_sign='='): """ write a z-matrix to a string """ mat_str = matrix_block(syms=syms, key_mat=key_mat, name_mat=name_mat, delim=mat_delim) setval_str = setval_block(val_dct=val_dct, setval_sign=setval_sign) zma_str = '\n\n'.join((mat_str, setval_str)) return zma_str def matrix_block(syms, key_mat, name_mat, delim=' '): """ write the .zmat matrix block to a string """ def _line_string(row_idx): line_str = '{:<2s} '.format(syms[row_idx]) keys = key_mat[row_idx] names = name_mat[row_idx] line_str += delim.join(['{:>d}{}{:>5s} '.format(keys[col_idx], delim, names[col_idx]) for col_idx in range(min(row_idx, 3))]) return line_str natms = len(syms) mat_str = '\n'.join([_line_string(row_idx) for row_idx in range(natms)]) return mat_str def setval_block(val_dct, setval_sign='='): """ write the .zmat setval block to a string """ setval_str = '\n'.join(['{:<5s}{}{:>11.6f}'.format(name, setval_sign, val) for (name, val) in val_dct.items()]) return setval_str
n=int(input("enter a number")) m=int(input("enter a number")) if n%m==0: print(n,"is dividible by",m) else: print(n,"is not divisible by",m) if n%2==0: print(n,"is even") else: print(n,"is odd")
n = int(input('enter a number')) m = int(input('enter a number')) if n % m == 0: print(n, 'is dividible by', m) else: print(n, 'is not divisible by', m) if n % 2 == 0: print(n, 'is even') else: print(n, 'is odd')
"""Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. """ class Solution(object): def addDigits(self, num): while num >= 10: num = sum([int(str(num)[i]) for i in range(len(str(num)))]) return num
"""Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. For example: Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it. """ class Solution(object): def add_digits(self, num): while num >= 10: num = sum([int(str(num)[i]) for i in range(len(str(num)))]) return num
file_extractors = {} def file_extractor(extension): """ This decorator registers functions to be used as extractors. Only functions decorated with this are considered metadata extractors, and will be called when the file extension matches the configured one. :param extension: the extension to match """ def deco(f): assert extension not in file_extractors, f"extension {extension} already registered" file_extractors[extension] = f return f return deco
file_extractors = {} def file_extractor(extension): """ This decorator registers functions to be used as extractors. Only functions decorated with this are considered metadata extractors, and will be called when the file extension matches the configured one. :param extension: the extension to match """ def deco(f): assert extension not in file_extractors, f'extension {extension} already registered' file_extractors[extension] = f return f return deco
MAX = 'x' MIN = 'o' def get_player(s): return MAX if len([1 for i in s if i == ' ']) % 2 == 1 else MIN def next_player(p): return MAX if p == MIN else MIN def get_actions(s): return [i for i in range(9) if s[i] == ' '] def result(s, a): player = get_player(s) s2 = list(s) s2[a] = player return s2 def is_winning_state(s, player): aux = [player] * 3 if s[0:3] == aux or \ s[3:6] == aux or \ s[6:9] == aux or \ s[0:9:3] == aux or \ s[1:9:3] == aux or \ s[2:9:3] == aux or \ s[2:8:2] == aux or \ s[0:9:4] == aux: return True else: return False def terminal(s): if is_winning_state(s, MAX) or is_winning_state(s, MIN): return True if ' ' not in s: return True return False def utility(s): if is_winning_state(s, MAX): return 1 if is_winning_state(s, MIN): return -1 return 0 def maxval(s): if terminal(s): return None, utility(s) best_utility = float("-Inf") best_action = None actions = get_actions(s) for action in actions: s2 = result(s, action) _, current_utility = minval(s2) if current_utility >= best_utility: best_utility = current_utility best_action = action if best_utility == 1: # Maximum utility break return best_action, best_utility def minval(s): if terminal(s): return None, utility(s) best_utility = float("Inf") best_action = None actions = get_actions(s) for action in actions: s2 = result(s, action) _, current_utility = maxval(s2) if current_utility <= best_utility: best_utility = current_utility best_action = action if best_utility == -1: # Minimum utility break return best_action, best_utility def minmax(s): p = get_player(s) if p == MAX: return maxval(s) if p == MIN: return minval(s) def print_s(s): print(" {} | {} | {} \n" " 0 | 1 | 2 \n" "-----------\n" " {} | {} | {} \n" " 3 | 4 | 5 \n" "-----------\n" " {} | {} | {} \n" " 6 | 7 | 8 \n".format(*s)) def ai_play(s): a, _ = minmax(s) return a def user_play(s): a = int(input()) return a if __name__ == "__main__": s = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] print_s(s) players = [ ("USER", user_play), ("AI", ai_play) ] while not terminal(s): for name, method in players: print("{} -> ".format(name)) a = method(s) s = result(s, a) print_s(s) if terminal(s): break if is_winning_state(s, MAX): print("PLAYER '{}' WON!".format(MAX)) elif is_winning_state(s, MIN): print("PLAYER '{}' WON!".format(MIN)) else: print("TIE!")
max = 'x' min = 'o' def get_player(s): return MAX if len([1 for i in s if i == ' ']) % 2 == 1 else MIN def next_player(p): return MAX if p == MIN else MIN def get_actions(s): return [i for i in range(9) if s[i] == ' '] def result(s, a): player = get_player(s) s2 = list(s) s2[a] = player return s2 def is_winning_state(s, player): aux = [player] * 3 if s[0:3] == aux or s[3:6] == aux or s[6:9] == aux or (s[0:9:3] == aux) or (s[1:9:3] == aux) or (s[2:9:3] == aux) or (s[2:8:2] == aux) or (s[0:9:4] == aux): return True else: return False def terminal(s): if is_winning_state(s, MAX) or is_winning_state(s, MIN): return True if ' ' not in s: return True return False def utility(s): if is_winning_state(s, MAX): return 1 if is_winning_state(s, MIN): return -1 return 0 def maxval(s): if terminal(s): return (None, utility(s)) best_utility = float('-Inf') best_action = None actions = get_actions(s) for action in actions: s2 = result(s, action) (_, current_utility) = minval(s2) if current_utility >= best_utility: best_utility = current_utility best_action = action if best_utility == 1: break return (best_action, best_utility) def minval(s): if terminal(s): return (None, utility(s)) best_utility = float('Inf') best_action = None actions = get_actions(s) for action in actions: s2 = result(s, action) (_, current_utility) = maxval(s2) if current_utility <= best_utility: best_utility = current_utility best_action = action if best_utility == -1: break return (best_action, best_utility) def minmax(s): p = get_player(s) if p == MAX: return maxval(s) if p == MIN: return minval(s) def print_s(s): print(' {} | {} | {} \n 0 | 1 | 2 \n-----------\n {} | {} | {} \n 3 | 4 | 5 \n-----------\n {} | {} | {} \n 6 | 7 | 8 \n'.format(*s)) def ai_play(s): (a, _) = minmax(s) return a def user_play(s): a = int(input()) return a if __name__ == '__main__': s = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] print_s(s) players = [('USER', user_play), ('AI', ai_play)] while not terminal(s): for (name, method) in players: print('{} -> '.format(name)) a = method(s) s = result(s, a) print_s(s) if terminal(s): break if is_winning_state(s, MAX): print("PLAYER '{}' WON!".format(MAX)) elif is_winning_state(s, MIN): print("PLAYER '{}' WON!".format(MIN)) else: print('TIE!')
# What are the factors of 18? # factor: an integer which when multiplied with another integer, results in the product 18. # Hence when 18 is divided by this number, the dividend is an integer and there are no remainders. num = 18 for i in range(1, num+1): if num % i == 0: print(i, end=' ')
num = 18 for i in range(1, num + 1): if num % i == 0: print(i, end=' ')
def main(): for _ in range(int(input())): n = int(input()) arr = list(map(int, input().strip().split())) if n == 1: print(arr[0]) else: n += 1 arr.append(1001) left, right = 0, 1 res = '' while left <= right and right < n and left < n: #print(left,right) if arr[right]-arr[left] == right-left: right += 1 else: if right-left >= 3: res += str(arr[left])+'...'+str(arr[right-1])+',' else: for i in range(left, right): res += str(arr[i])+',' left = right print(res.strip(',')) main()
def main(): for _ in range(int(input())): n = int(input()) arr = list(map(int, input().strip().split())) if n == 1: print(arr[0]) else: n += 1 arr.append(1001) (left, right) = (0, 1) res = '' while left <= right and right < n and (left < n): if arr[right] - arr[left] == right - left: right += 1 else: if right - left >= 3: res += str(arr[left]) + '...' + str(arr[right - 1]) + ',' else: for i in range(left, right): res += str(arr[i]) + ',' left = right print(res.strip(',')) main()
######################################################################################### # IMPORTANT: This file should be copied to setting.py and then completed before use # ######################################################################################### # Rocky Version VERSION = '0.3.5' # Path to json file containing hostnames, ip addresses and credentials for monitoring HOSTS = 'file.json' # Path to where ports files will be saved PORTS_PATH = 'path/ports/' # DNS Name Servers - List of stringed DNS IPs ROUTER_NAME_SERVERS = ['8.8.8.8', '1.1.1.1'] # Public Keys # These keys allow Rocky and Robot to log in to the SRX Router(s) to update the network configuration # Rocky RSA ROCKY_RSA = '' # Robot RSA ROBOT_RSA = '' # Administrator encrypted password (sha256) ADMINISTRATOR_ENCRYP_PASS = '' # api-server user with limited access API_USER_PASS = '' # Radius server RADIUS_SERVER_ADDRESS = '' # hashed password RADIUS_SERVER_SECRET = '' # Network Device Repository Path DEVICE_CONFIG_PATH = 'path/repo/' # Managed Cloud Infrastructure # One instance of Rocky can manage multiple clouds and each cloud will consist of one or more regions. # This configuration describes the cloud infrastructure managed by this instance of Rocky. # Monitoring and Provisioning servers needs access to the cloud infrastructure. # Inbound Access list # The management network of this SRXPod is firewalled to block all inbound traffic. # Access is allowed to the management network from this list of external Public IPs. MAP_ACCESS_LIST = [ { 'source_address': '', # 'any' for all ips 'destination_address': '', # 'any' for all ips 'port': '', # valid values 1 , 0-655 'protocol': '', # 'tcp'/'udp'/'any' 'description': '', }, ] clouds = [ # First Cloud ... { 'name': 'First Cloud', 'id': '', # python-cloudcix api settings 'CLOUDCIX_API_URL': '', 'CLOUDCIX_API_USERNAME': '', 'CLOUDCIX_API_PASSWORD': '', 'CLOUDCIX_API_KEY': '', 'CLOUDCIX_API_VERSION': 2, 'CLOUDCIX_API_V2_URL': '', # COP inbound access list # The management network of this SRXPod is firewalled to block all inbound traffic. # Access is allowed to the management network from this list of external Public IPs. 'COP_ACCESS_LIST': [ { 'source_address': '', 'destination_address': '', 'port': '', 'protocol': '', 'description': '', }, ], # Pod settings 'pods': [ { 'name': 'name of the cop', 'id': '', 'type': 'cop', # Network schema 'IPv4_link_subnet': [ # this is optional, you can leave them as it is. { 'address_range': '', 'gateway': '', }, ], 'IPv4_pod_subnets': [ { 'address_range': '', 'gateway': '', }, { 'address_range': '', 'gateway': '', }, ], 'IPv6_link_subnet': [ { 'address_range': '', 'gateway': '', }, ], 'IPv6_pod_subnets': [ { 'address_range': '', }, ], 'IPv4_RFC1918_subnets': [ { 'address_range': '', 'gateway': '', }, ], # VPN Tunnel from Support Center to the SRXPOD for management. 'vpns': [], }, # first region { 'name': 'region name', 'id': '', 'type': 'region', # Network schema 'IPv4_link_subnet': [ # this is optional, you can leave them as it is. { 'address_range': '', 'gateway': '', }, ], 'IPv4_pod_subnets': [ { 'address_range': '', 'gateway': '', }, { 'address_range': '', 'gateway': '', }, ], 'IPv6_link_subnet': [ { 'address_range': '', 'gateway': '', }, ], 'IPv6_pod_subnets': [ { 'address_range': '', }, ], 'IPv4_RFC1918_subnets': [ { 'address_range': '', 'gateway': '', }, ], # VPN Tunnel from Support Center to the SRXPOD for management. 'vpns': [], }, # Second region { 'name': 'Second Region', }, ], }, # second cloud {}, ]
version = '0.3.5' hosts = 'file.json' ports_path = 'path/ports/' router_name_servers = ['8.8.8.8', '1.1.1.1'] rocky_rsa = '' robot_rsa = '' administrator_encryp_pass = '' api_user_pass = '' radius_server_address = '' radius_server_secret = '' device_config_path = 'path/repo/' map_access_list = [{'source_address': '', 'destination_address': '', 'port': '', 'protocol': '', 'description': ''}] clouds = [{'name': 'First Cloud', 'id': '', 'CLOUDCIX_API_URL': '', 'CLOUDCIX_API_USERNAME': '', 'CLOUDCIX_API_PASSWORD': '', 'CLOUDCIX_API_KEY': '', 'CLOUDCIX_API_VERSION': 2, 'CLOUDCIX_API_V2_URL': '', 'COP_ACCESS_LIST': [{'source_address': '', 'destination_address': '', 'port': '', 'protocol': '', 'description': ''}], 'pods': [{'name': 'name of the cop', 'id': '', 'type': 'cop', 'IPv4_link_subnet': [{'address_range': '', 'gateway': ''}], 'IPv4_pod_subnets': [{'address_range': '', 'gateway': ''}, {'address_range': '', 'gateway': ''}], 'IPv6_link_subnet': [{'address_range': '', 'gateway': ''}], 'IPv6_pod_subnets': [{'address_range': ''}], 'IPv4_RFC1918_subnets': [{'address_range': '', 'gateway': ''}], 'vpns': []}, {'name': 'region name', 'id': '', 'type': 'region', 'IPv4_link_subnet': [{'address_range': '', 'gateway': ''}], 'IPv4_pod_subnets': [{'address_range': '', 'gateway': ''}, {'address_range': '', 'gateway': ''}], 'IPv6_link_subnet': [{'address_range': '', 'gateway': ''}], 'IPv6_pod_subnets': [{'address_range': ''}], 'IPv4_RFC1918_subnets': [{'address_range': '', 'gateway': ''}], 'vpns': []}, {'name': 'Second Region'}]}, {}]
########################################################### # # # Solving factorial problem with recursive function # # # ########################################################### def factorial(n): if n == 2: return 2 return n * factorial(n - 1) print(factorial(int(input())))
def factorial(n): if n == 2: return 2 return n * factorial(n - 1) print(factorial(int(input())))
"""Enter n, use the recursion method (for example, derive the latter term from the relationship between the preceding items, it is a one-loop question) and caculate the sum of 1+2!+3!+...+n! and output the result.""" n = int(input('Give me a integer: ')) s = term = 1 for i in range(2, n+1): term *= i s += term print(s)
"""Enter n, use the recursion method (for example, derive the latter term from the relationship between the preceding items, it is a one-loop question) and caculate the sum of 1+2!+3!+...+n! and output the result.""" n = int(input('Give me a integer: ')) s = term = 1 for i in range(2, n + 1): term *= i s += term print(s)
# -*- coding: utf-8 -*- """ 1417. Reformat The String Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string. Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters and/or digits. """ class Solution: def reformat(self, s: str) -> str: num_set = set(str(i) for i in range(10)) digit_cache = "" letter_chace = "" for char in s: if char in num_set: digit_cache += char else: letter_chace += char res = "" digit_length = len(digit_cache) letter_length = len(letter_chace) if digit_length == letter_length: for ind in range(letter_length): res += digit_cache[ind] res += letter_chace[ind] elif digit_length == letter_length + 1: for ind in range(letter_length): res += digit_cache[ind] res += letter_chace[ind] res += digit_cache[-1] elif digit_length + 1 == letter_length: for ind in range(digit_length): res += letter_chace[ind] res += digit_cache[ind] res += letter_chace[-1] return res
""" 1417. Reformat The String Given alphanumeric string s. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the string. Constraints: 1 <= s.length <= 500 s consists of only lowercase English letters and/or digits. """ class Solution: def reformat(self, s: str) -> str: num_set = set((str(i) for i in range(10))) digit_cache = '' letter_chace = '' for char in s: if char in num_set: digit_cache += char else: letter_chace += char res = '' digit_length = len(digit_cache) letter_length = len(letter_chace) if digit_length == letter_length: for ind in range(letter_length): res += digit_cache[ind] res += letter_chace[ind] elif digit_length == letter_length + 1: for ind in range(letter_length): res += digit_cache[ind] res += letter_chace[ind] res += digit_cache[-1] elif digit_length + 1 == letter_length: for ind in range(digit_length): res += letter_chace[ind] res += digit_cache[ind] res += letter_chace[-1] return res
# # University of Luxembourg # Laboratory of Algorithmics, Cryptology and Security (LACS) # # FigureOfMerit (FOM) # # Copyright (C) 2015 University of Luxembourg # # Written in 2015 by Daniel Dinu <dumitru-daniel.dinu@uni.lu> # # This file is part of FigureOfMerit. # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, see <http://www.gnu.org/licenses/>. # __author__ = 'daniel.dinu'
__author__ = 'daniel.dinu'
__all__ = ( 'ESputnikException', 'InvalidAuthDataError', 'IncorrectDataError' ) class ESputnikException(AttributeError): pass class InvalidAuthDataError(ESputnikException): def __init__(self, code, message): self.code = code self.message = message class IncorrectDataError(InvalidAuthDataError): pass
__all__ = ('ESputnikException', 'InvalidAuthDataError', 'IncorrectDataError') class Esputnikexception(AttributeError): pass class Invalidauthdataerror(ESputnikException): def __init__(self, code, message): self.code = code self.message = message class Incorrectdataerror(InvalidAuthDataError): pass
class TextFieldFsm: def __init__(self, title, position, need_hide=False, initial_text=""): self.title = title self.position = position self.need_hide = need_hide self.initial_text = initial_text
class Textfieldfsm: def __init__(self, title, position, need_hide=False, initial_text=''): self.title = title self.position = position self.need_hide = need_hide self.initial_text = initial_text
BINDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/bin' DATADIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share' DATAROOTDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share' DESTDIR = '/' DOCDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' DVIDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' EPREFIX = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6' HTMLDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' INCLUDEDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/include' INFODIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/info' LIBDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/lib' LIBEXECDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/libexec' LOCALEDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/locale' LOCALSTATEDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/var' MANDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/man' PDFDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' PKGDATADIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/bento' PKGNAME = 'bento' PREFIX = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6' PSDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' PY_VERSION_SHORT = '3.6' SBINDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/sbin' SHAREDSTATEDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/com' SITEDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages' SYSCONFDIR = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/etc'
bindir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/bin' datadir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share' datarootdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share' destdir = '/' docdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' dvidir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' eprefix = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6' htmldir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' includedir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/include' infodir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/info' libdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/lib' libexecdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/libexec' localedir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/locale' localstatedir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/var' mandir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/man' pdfdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' pkgdatadir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/bento' pkgname = 'bento' prefix = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6' psdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/share/doc/bento' py_version_short = '3.6' sbindir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/sbin' sharedstatedir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/com' sitedir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages' sysconfdir = '/usr/local/Cellar/python3/3.6.2_1/Frameworks/Python.framework/Versions/3.6/etc'
wanted_profit = float(input()) is_wanted_profit_gained = False total_amount = 0 cocktail = input() while cocktail != 'Party!': number_of_cocktails = int(input()) cocktail_price = len(cocktail) order_price = cocktail_price * number_of_cocktails if order_price % 2 != 0: order_price = order_price - order_price * 0.25 total_amount += order_price if total_amount >= wanted_profit: is_wanted_profit_gained = True break cocktail = input() difference = abs(wanted_profit - total_amount) if is_wanted_profit_gained: print ('Target acquired.') print (f'Club income - {total_amount:.2f} leva.') else: print (f'We need {difference:.2f} leva more.') print (f'Club income - {total_amount:.2f} leva.')
wanted_profit = float(input()) is_wanted_profit_gained = False total_amount = 0 cocktail = input() while cocktail != 'Party!': number_of_cocktails = int(input()) cocktail_price = len(cocktail) order_price = cocktail_price * number_of_cocktails if order_price % 2 != 0: order_price = order_price - order_price * 0.25 total_amount += order_price if total_amount >= wanted_profit: is_wanted_profit_gained = True break cocktail = input() difference = abs(wanted_profit - total_amount) if is_wanted_profit_gained: print('Target acquired.') print(f'Club income - {total_amount:.2f} leva.') else: print(f'We need {difference:.2f} leva more.') print(f'Club income - {total_amount:.2f} leva.')
# Define a class to receive the characteristics of each line detection class Line(): def __init__(self): # was the line detected in the last iteration? self.detected = False # x values of the last n fits of the line self.recent_xfitted = [] #average x values of the fitted line over the last n iterations self.bestx = None #polynomial coefficients averaged over the last n iterations self.best_fit = None #polynomial coefficients for the most recent fit self.current_fit = [np.array([False])] #radius of curvature of the line in some units self.radius_of_curvature = None #distance in meters of vehicle center from the line self.line_base_pos = None #difference in fit coefficients between last and new fits self.diffs = np.array([0,0,0], dtype='float') #x values for detected line pixels self.allx = None #y values for detected line pixels self.ally = None def pipeline(img, s_thresh=(170, 255), sx_thresh=(30, 100)): img = np.copy(img) # Convert to HLS color space and separate the V channel hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) L_channel = lab[:,:,0] l_channel = hls[:,:,1] s_channel = hls[:,:,2] # Sobel x sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) # Take the derivative in x abs_sobelx = np.absolute(sobelx) # Absolute x derivative to accentuate lines away from horizontal scaled_sobel = np.uint8(255*abs_sobelx/np.max(abs_sobelx)) #Threshold LAB labbinary = np.zeros_like(L_channel) labbinary[(L_channel >= 100) & (L_channel <= 255)] = 1 # Threshold x gradient sxbinary = np.zeros_like(scaled_sobel) sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1 # Threshold color channel s_binary = np.zeros_like(s_channel) s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1 img_bwa = cv2.bitwise_and(labbinary,s_binary) t_binary = np.zeros(img.shape[:2], dtype=np.uint8) t_binary[(L_channel >= 100) & (s_binary <= s_thresh[1])] = 1 # Stack each channel color_binary = np.dstack(( np.zeros_like(sxbinary), np.zeros_like(sxbinary), img_bwa + sxbinary)) * 255 return color_binary def find_lane_pixels(binary_warped): # Take a histogram of the bottom half of the image histogram = np.sum(binary_warped[binary_warped.shape[0]//2:,:], axis=0) # Create an output image to draw on and visualize the result out_img = np.dstack((binary_warped, binary_warped, binary_warped)) # Find the peak of the left and right halves of the histogram # These will be the starting point for the left and right lines midpoint = np.int(histogram.shape[0]//2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint # HYPERPARAMETERS # Choose the number of sliding windows nwindows = 15 # Set the width of the windows +/- margin margin = 100 # Set minimum number of pixels found to recenter window minpix = 50 # Set height of windows - based on nwindows above and image shape window_height = np.int(binary_warped.shape[0]//nwindows) # Identify the x and y positions of all nonzero (i.e. activated) pixels in the image nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) # Current positions to be updated later for each window in nwindows leftx_current = leftx_base rightx_current = rightx_base # Create empty lists to receive left and right lane pixel indices left_lane_inds = [] right_lane_inds = [] for window in range(nwindows): # Identify window boundaries in x and y (and right and left) win_y_low = binary_warped.shape[0] - (window+1)*window_height win_y_high = binary_warped.shape[0] - window*window_height ### TO-DO: Find the four below boundaries of the window ### win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin # Draw the windows on the visualization image cv2.rectangle(out_img,(win_xleft_low,win_y_low), (win_xleft_high,win_y_high),(0,255,0), 2) cv2.rectangle(out_img,(win_xright_low,win_y_low), (win_xright_high,win_y_high),(0,255,0), 2) ### TO-DO: Identify the nonzero pixels in x and y within the window ### good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] # Append these indices to the lists left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) ### TO-DO: If you found > minpix pixels, recenter next window ### if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) # Concatenate the arrays of indices (previously was a list of lists of pixels) try: left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) except ValueError: # Avoids an error if the above is not implemented fully pass # Extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] return leftx, lefty, rightx, righty, out_img def fit_polynomial(binary_warped): # Find our lane pixels first leftx, lefty, rightx, righty, out_img = find_lane_pixels(binary_warped) ### TO-DO: Fit a second order polynomial to each using `np.polyfit` ### left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) # Generate x and y values for plotting ploty = np.linspace(0, binary_warped.shape[0]-1, binary_warped.shape[0] ) try: left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2] right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2] except TypeError: # Avoids an error if `left` and `right_fit` are still none or incorrect print('The function failed to fit a line!') left_fitx = 1*ploty**2 + 1*ploty right_fitx = 1*ploty**2 + 1*ploty ## Visualization ## # Colors in the left and right lane regions out_img[lefty, leftx] = [255, 0, 0] out_img[righty, rightx] = [0, 0, 255] # Plots the left and right polynomials on the lane lines #plt.plot(left_fitx, ploty, color='yellow') #plt.plot(right_fitx, ploty, color='yellow') return out_img, left_fit, right_fit def fit_poly(img_shape, leftx, lefty, rightx, righty): ### TO-DO: Fit a second order polynomial to each with np.polyfit() ### left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) # Generate x and y values for plotting ploty = np.linspace(0, img_shape[0]-1, img_shape[0]) ### TO-DO: Calc both polynomials using ploty, left_fit and right_fit ### left_fitx = left_fit[0]*ploty**2 + left_fit[1]*ploty + left_fit[2] right_fitx = right_fit[0]*ploty**2 + right_fit[1]*ploty + right_fit[2] return left_fitx, right_fitx, ploty def compute_lane_curvature(leftx, rightx, ploty): """ Returns the triple (left_curvature, right_curvature, lane_center_offset), which are all in meters """ # Define conversions in x and y from pixels space to meters y_eval = np.max(ploty) # Fit new polynomials: find x for y in real-world space left_fit_cr = np.polyfit(ploty * ym_per_px, leftx * xm_per_px, 2) right_fit_cr = np.polyfit(ploty * ym_per_px, rightx * xm_per_px, 2) # Now calculate the radii of the curvature left_curverad = ((1 + (2 * left_fit_cr[0] * y_eval * ym_per_px + left_fit_cr[1])**2)**1.5) / np.absolute(2 * left_fit_cr[0]) right_curverad = ((1 + (2 *right_fit_cr[0] * y_eval * ym_per_px + right_fit_cr[1])**2)**1.5) / np.absolute(2 * right_fit_cr[0]) # Now our radius of curvature is in meters return left_curverad, right_curverad def search_around_poly(binary_warped, Minv, left_fit, right_fit, undist): # HYPERPARAMETER # Choose the width of the margin around the previous polynomial to search # The quiz grader expects 100 here, but feel free to tune on your own! margin = 100 # Grab activated pixels nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) ### TO-DO: Set the area of search based on activated x-values ### ### within the +/- margin of our polynomial function ### ### Hint: consider the window areas for the similarly named variables ### ### in the previous quiz, but change the windows to our new search area ### left_lane_inds = ((nonzerox > (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] - margin)) & (nonzerox < (left_fit[0]*(nonzeroy**2) + left_fit[1]*nonzeroy + left_fit[2] + margin))) right_lane_inds = ((nonzerox > (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] - margin)) & (nonzerox < (right_fit[0]*(nonzeroy**2) + right_fit[1]*nonzeroy + right_fit[2] + margin))) # Again, extract left and right line pixel positions leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] # Fit new polynomials left_fitx, right_fitx, ploty = fit_poly(binary_warped.shape, leftx, lefty, rightx, righty) ## Visualization ## # Create an image to draw on and an image to show the selection window out_img = np.dstack((binary_warped, binary_warped, binary_warped))*255 window_img = np.zeros_like(out_img) # Color in left and right line pixels out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0] out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255] # Generate a polygon to illustrate the search window area # And recast the x and y points into usable format for cv2.fillPoly() left_line_window1 = np.array([np.transpose(np.vstack([left_fitx-margin, ploty]))]) left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx+margin, ploty])))]) left_line_pts = np.hstack((left_line_window1, left_line_window2)) right_line_window1 = np.array([np.transpose(np.vstack([right_fitx-margin, ploty]))]) right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx+margin, ploty])))]) right_line_pts = np.hstack((right_line_window1, right_line_window2)) # Draw the lane onto the warped blank image #cv2.fillPoly(window_img, np.int_([left_line_pts]), (0,255, 0)) #cv2.fillPoly(window_img, np.int_([right_line_pts]), (0,255, 0)) #result = cv2.addWeighted(out_img, 1, window_img, 0.3, 0) # Plot the polynomial lines onto the image #plt.plot(left_fitx, ploty, color='yellow') #plt.plot(right_fitx, ploty, color='yellow') ## End visualization steps ## left_curverad, right_curverad = compute_lane_curvature(left_fitx, right_fitx, ploty) print(left_curverad, right_curverad) # Create an image to draw the lines on warp_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) # Recast the x and y points into usable format for cv2.fillPoly() pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))]) pts = np.hstack((pts_left, pts_right)) # Draw the lane onto the warped blank image cv2.fillPoly(color_warp, np.int_([pts]), (0,255, 0)) # Warp the blank back to original image space using inverse perspective matrix (Minv) newwarp = cv2.warpPerspective(color_warp, Minv, (undist.shape[1], undist.shape[0])) # Combine the result with the original image result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) return result
class Line: def __init__(self): self.detected = False self.recent_xfitted = [] self.bestx = None self.best_fit = None self.current_fit = [np.array([False])] self.radius_of_curvature = None self.line_base_pos = None self.diffs = np.array([0, 0, 0], dtype='float') self.allx = None self.ally = None def pipeline(img, s_thresh=(170, 255), sx_thresh=(30, 100)): img = np.copy(img) hls = cv2.cvtColor(img, cv2.COLOR_BGR2HLS) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB) l_channel = lab[:, :, 0] l_channel = hls[:, :, 1] s_channel = hls[:, :, 2] sobelx = cv2.Sobel(l_channel, cv2.CV_64F, 1, 0) abs_sobelx = np.absolute(sobelx) scaled_sobel = np.uint8(255 * abs_sobelx / np.max(abs_sobelx)) labbinary = np.zeros_like(L_channel) labbinary[(L_channel >= 100) & (L_channel <= 255)] = 1 sxbinary = np.zeros_like(scaled_sobel) sxbinary[(scaled_sobel >= sx_thresh[0]) & (scaled_sobel <= sx_thresh[1])] = 1 s_binary = np.zeros_like(s_channel) s_binary[(s_channel >= s_thresh[0]) & (s_channel <= s_thresh[1])] = 1 img_bwa = cv2.bitwise_and(labbinary, s_binary) t_binary = np.zeros(img.shape[:2], dtype=np.uint8) t_binary[(L_channel >= 100) & (s_binary <= s_thresh[1])] = 1 color_binary = np.dstack((np.zeros_like(sxbinary), np.zeros_like(sxbinary), img_bwa + sxbinary)) * 255 return color_binary def find_lane_pixels(binary_warped): histogram = np.sum(binary_warped[binary_warped.shape[0] // 2:, :], axis=0) out_img = np.dstack((binary_warped, binary_warped, binary_warped)) midpoint = np.int(histogram.shape[0] // 2) leftx_base = np.argmax(histogram[:midpoint]) rightx_base = np.argmax(histogram[midpoint:]) + midpoint nwindows = 15 margin = 100 minpix = 50 window_height = np.int(binary_warped.shape[0] // nwindows) nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) leftx_current = leftx_base rightx_current = rightx_base left_lane_inds = [] right_lane_inds = [] for window in range(nwindows): win_y_low = binary_warped.shape[0] - (window + 1) * window_height win_y_high = binary_warped.shape[0] - window * window_height win_xleft_low = leftx_current - margin win_xleft_high = leftx_current + margin win_xright_low = rightx_current - margin win_xright_high = rightx_current + margin cv2.rectangle(out_img, (win_xleft_low, win_y_low), (win_xleft_high, win_y_high), (0, 255, 0), 2) cv2.rectangle(out_img, (win_xright_low, win_y_low), (win_xright_high, win_y_high), (0, 255, 0), 2) good_left_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xleft_low) & (nonzerox < win_xleft_high)).nonzero()[0] good_right_inds = ((nonzeroy >= win_y_low) & (nonzeroy < win_y_high) & (nonzerox >= win_xright_low) & (nonzerox < win_xright_high)).nonzero()[0] left_lane_inds.append(good_left_inds) right_lane_inds.append(good_right_inds) if len(good_left_inds) > minpix: leftx_current = np.int(np.mean(nonzerox[good_left_inds])) if len(good_right_inds) > minpix: rightx_current = np.int(np.mean(nonzerox[good_right_inds])) try: left_lane_inds = np.concatenate(left_lane_inds) right_lane_inds = np.concatenate(right_lane_inds) except ValueError: pass leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] return (leftx, lefty, rightx, righty, out_img) def fit_polynomial(binary_warped): (leftx, lefty, rightx, righty, out_img) = find_lane_pixels(binary_warped) left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) ploty = np.linspace(0, binary_warped.shape[0] - 1, binary_warped.shape[0]) try: left_fitx = left_fit[0] * ploty ** 2 + left_fit[1] * ploty + left_fit[2] right_fitx = right_fit[0] * ploty ** 2 + right_fit[1] * ploty + right_fit[2] except TypeError: print('The function failed to fit a line!') left_fitx = 1 * ploty ** 2 + 1 * ploty right_fitx = 1 * ploty ** 2 + 1 * ploty out_img[lefty, leftx] = [255, 0, 0] out_img[righty, rightx] = [0, 0, 255] return (out_img, left_fit, right_fit) def fit_poly(img_shape, leftx, lefty, rightx, righty): left_fit = np.polyfit(lefty, leftx, 2) right_fit = np.polyfit(righty, rightx, 2) ploty = np.linspace(0, img_shape[0] - 1, img_shape[0]) left_fitx = left_fit[0] * ploty ** 2 + left_fit[1] * ploty + left_fit[2] right_fitx = right_fit[0] * ploty ** 2 + right_fit[1] * ploty + right_fit[2] return (left_fitx, right_fitx, ploty) def compute_lane_curvature(leftx, rightx, ploty): """ Returns the triple (left_curvature, right_curvature, lane_center_offset), which are all in meters """ y_eval = np.max(ploty) left_fit_cr = np.polyfit(ploty * ym_per_px, leftx * xm_per_px, 2) right_fit_cr = np.polyfit(ploty * ym_per_px, rightx * xm_per_px, 2) left_curverad = (1 + (2 * left_fit_cr[0] * y_eval * ym_per_px + left_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * left_fit_cr[0]) right_curverad = (1 + (2 * right_fit_cr[0] * y_eval * ym_per_px + right_fit_cr[1]) ** 2) ** 1.5 / np.absolute(2 * right_fit_cr[0]) return (left_curverad, right_curverad) def search_around_poly(binary_warped, Minv, left_fit, right_fit, undist): margin = 100 nonzero = binary_warped.nonzero() nonzeroy = np.array(nonzero[0]) nonzerox = np.array(nonzero[1]) left_lane_inds = (nonzerox > left_fit[0] * nonzeroy ** 2 + left_fit[1] * nonzeroy + left_fit[2] - margin) & (nonzerox < left_fit[0] * nonzeroy ** 2 + left_fit[1] * nonzeroy + left_fit[2] + margin) right_lane_inds = (nonzerox > right_fit[0] * nonzeroy ** 2 + right_fit[1] * nonzeroy + right_fit[2] - margin) & (nonzerox < right_fit[0] * nonzeroy ** 2 + right_fit[1] * nonzeroy + right_fit[2] + margin) leftx = nonzerox[left_lane_inds] lefty = nonzeroy[left_lane_inds] rightx = nonzerox[right_lane_inds] righty = nonzeroy[right_lane_inds] (left_fitx, right_fitx, ploty) = fit_poly(binary_warped.shape, leftx, lefty, rightx, righty) out_img = np.dstack((binary_warped, binary_warped, binary_warped)) * 255 window_img = np.zeros_like(out_img) out_img[nonzeroy[left_lane_inds], nonzerox[left_lane_inds]] = [255, 0, 0] out_img[nonzeroy[right_lane_inds], nonzerox[right_lane_inds]] = [0, 0, 255] left_line_window1 = np.array([np.transpose(np.vstack([left_fitx - margin, ploty]))]) left_line_window2 = np.array([np.flipud(np.transpose(np.vstack([left_fitx + margin, ploty])))]) left_line_pts = np.hstack((left_line_window1, left_line_window2)) right_line_window1 = np.array([np.transpose(np.vstack([right_fitx - margin, ploty]))]) right_line_window2 = np.array([np.flipud(np.transpose(np.vstack([right_fitx + margin, ploty])))]) right_line_pts = np.hstack((right_line_window1, right_line_window2)) (left_curverad, right_curverad) = compute_lane_curvature(left_fitx, right_fitx, ploty) print(left_curverad, right_curverad) warp_zero = np.zeros_like(binary_warped).astype(np.uint8) color_warp = np.dstack((warp_zero, warp_zero, warp_zero)) pts_left = np.array([np.transpose(np.vstack([left_fitx, ploty]))]) pts_right = np.array([np.flipud(np.transpose(np.vstack([right_fitx, ploty])))]) pts = np.hstack((pts_left, pts_right)) cv2.fillPoly(color_warp, np.int_([pts]), (0, 255, 0)) newwarp = cv2.warpPerspective(color_warp, Minv, (undist.shape[1], undist.shape[0])) result = cv2.addWeighted(undist, 1, newwarp, 0.3, 0) return result
load("@io_bazel_rules_dotnet//dotnet:defs.bzl", "core_library", "core_nunit3_test", "core_resource") COMMON_DEFINES = [ "NETSTANDARD2_0", "NETCOREAPP2_0", "SERIALIZATION", "ASYNC", #"PLATFORM_DETECTION", "PARALLEL", "TASK_PARALLEL_LIBRARY_API", ] core_library( name = "nunit.framework.dll", srcs = glob([ "src/NUnitFramework/framework/**/*.cs", ]) + [ "src/NUnitFramework/FrameworkVersion.cs", "src/CommonAssemblyInfo.cs", ], data = glob(["src/NUnitFramework/framework/Schemas/*.xsd"]), defines = COMMON_DEFINES, keyfile = "src/nunit.snk", visibility = ["//visibility:public"], deps = [ "@core_sdk_stdlib//:libraryset", ], ) core_library( name = "nunitlite.dll", srcs = glob(["src/NUnitFramework/nunitlite/**/*.cs"]) + ["src/CommonAssemblyInfo.cs"], data = glob(["src/NUnitFramework/framework/Schemas/*.xsd"]) + glob(["src/NUnitFramework/nunitlite/Schemas/*.xsd"]), defines = COMMON_DEFINES, keyfile = "src/nunit.snk", visibility = ["//visibility:public"], deps = [ ":nunit.framework.dll", ], ) core_library( name = "mock-assembly.dll", srcs = glob(["src/NUnitFramework/mock-assembly/**/*.cs"]) + ["src/CommonAssemblyInfo.cs"], defines = COMMON_DEFINES, keyfile = "src/nunit.snk", visibility = ["//visibility:public"], deps = [ ":nunitlite.dll", ], ) core_library( name = "nunit.testdata.dll", srcs = glob(["src/NUnitFramework/testdata/**/*.cs"]) + ["src/CommonAssemblyInfo.cs"], defines = COMMON_DEFINES, keyfile = "src/nunit.snk", visibility = ["//visibility:public"], deps = [ ":nunit.framework.dll", ], ) core_library( name = "slow-nunit-tests.dll", srcs = glob(["src/NUnitFramework/slow-tests/**/*.cs"]) + ["src/CommonAssemblyInfo.cs"], defines = COMMON_DEFINES, keyfile = "src/nunit.snk", visibility = ["//visibility:public"], deps = [ ":nunit.framework.dll", ], ) filegroup( name = "schemas", srcs = glob(["src/NUnitFramework/framework/Schemas/*"]), ) core_resource( name = "resource1", src = "src/NUnitFramework/tests/TestImage1.jpg", identifier = "NUnit.Framework.TestImage1.jpg", ) core_resource( name = "resource2", src = "src/NUnitFramework/tests/TestImage2.jpg", identifier = "NUnit.Framework.TestImage2.jpg", ) core_resource( name = "resource3", src = "src/NUnitFramework/tests/TestText1.txt", identifier = "NUnit.Framework.TestText1.txt", ) core_resource( name = "resource4", src = "src/NUnitFramework/tests/TestText2.txt", identifier = "NUnit.Framework.TestText2.txt", ) core_resource( name = "resource5", src = "src/NUnitFramework/tests/TestListFile.txt", identifier = "NUnit.Framework.TestListFile.txt", ) core_resource( name = "resource6", src = "src/NUnitFramework/tests/TestListFile2.txt", identifier = "NUnit.Framework.TestListFile2.txt", ) core_nunit3_test( name = "nunit.framework.tests.dll", srcs = glob( [ "src/NUnitFramework/tests/**/*.cs", "src/NUnitFramework/*.cs", ], exclude = ["**/RuntimeFrameworkTests.cs"], ) + ["src/CommonAssemblyInfo.cs"], data_with_dirs = { "@vstest.16.5//:Microsoft.TestPlatform.TestHostRuntimeProvider.dll": "Extensions", "@nunit3-vs-adapter.3.16.1//:NUnitTestAdapter.TestAdapter.dll": "Extensions", ":schemas": "Schemas", "@junit.testlogger//:extension": "Extensions", }, defines = COMMON_DEFINES, keyfile = "src/nunit.snk", resources = [ ":resource1", ":resource2", ":resource3", ":resource4", ":resource5", ":resource6", ], testlauncher = "@vstest.16.5//:vstest.console.exe", visibility = ["//visibility:public"], deps = [ ":mock-assembly.dll", ":nunit.framework.dll", ":nunit.testdata.dll", ":slow-nunit-tests.dll", "@nunit3-vs-adapter.3.16.1//:NUnitTestAdapter.TestAdapter.dll", ], )
load('@io_bazel_rules_dotnet//dotnet:defs.bzl', 'core_library', 'core_nunit3_test', 'core_resource') common_defines = ['NETSTANDARD2_0', 'NETCOREAPP2_0', 'SERIALIZATION', 'ASYNC', 'PARALLEL', 'TASK_PARALLEL_LIBRARY_API'] core_library(name='nunit.framework.dll', srcs=glob(['src/NUnitFramework/framework/**/*.cs']) + ['src/NUnitFramework/FrameworkVersion.cs', 'src/CommonAssemblyInfo.cs'], data=glob(['src/NUnitFramework/framework/Schemas/*.xsd']), defines=COMMON_DEFINES, keyfile='src/nunit.snk', visibility=['//visibility:public'], deps=['@core_sdk_stdlib//:libraryset']) core_library(name='nunitlite.dll', srcs=glob(['src/NUnitFramework/nunitlite/**/*.cs']) + ['src/CommonAssemblyInfo.cs'], data=glob(['src/NUnitFramework/framework/Schemas/*.xsd']) + glob(['src/NUnitFramework/nunitlite/Schemas/*.xsd']), defines=COMMON_DEFINES, keyfile='src/nunit.snk', visibility=['//visibility:public'], deps=[':nunit.framework.dll']) core_library(name='mock-assembly.dll', srcs=glob(['src/NUnitFramework/mock-assembly/**/*.cs']) + ['src/CommonAssemblyInfo.cs'], defines=COMMON_DEFINES, keyfile='src/nunit.snk', visibility=['//visibility:public'], deps=[':nunitlite.dll']) core_library(name='nunit.testdata.dll', srcs=glob(['src/NUnitFramework/testdata/**/*.cs']) + ['src/CommonAssemblyInfo.cs'], defines=COMMON_DEFINES, keyfile='src/nunit.snk', visibility=['//visibility:public'], deps=[':nunit.framework.dll']) core_library(name='slow-nunit-tests.dll', srcs=glob(['src/NUnitFramework/slow-tests/**/*.cs']) + ['src/CommonAssemblyInfo.cs'], defines=COMMON_DEFINES, keyfile='src/nunit.snk', visibility=['//visibility:public'], deps=[':nunit.framework.dll']) filegroup(name='schemas', srcs=glob(['src/NUnitFramework/framework/Schemas/*'])) core_resource(name='resource1', src='src/NUnitFramework/tests/TestImage1.jpg', identifier='NUnit.Framework.TestImage1.jpg') core_resource(name='resource2', src='src/NUnitFramework/tests/TestImage2.jpg', identifier='NUnit.Framework.TestImage2.jpg') core_resource(name='resource3', src='src/NUnitFramework/tests/TestText1.txt', identifier='NUnit.Framework.TestText1.txt') core_resource(name='resource4', src='src/NUnitFramework/tests/TestText2.txt', identifier='NUnit.Framework.TestText2.txt') core_resource(name='resource5', src='src/NUnitFramework/tests/TestListFile.txt', identifier='NUnit.Framework.TestListFile.txt') core_resource(name='resource6', src='src/NUnitFramework/tests/TestListFile2.txt', identifier='NUnit.Framework.TestListFile2.txt') core_nunit3_test(name='nunit.framework.tests.dll', srcs=glob(['src/NUnitFramework/tests/**/*.cs', 'src/NUnitFramework/*.cs'], exclude=['**/RuntimeFrameworkTests.cs']) + ['src/CommonAssemblyInfo.cs'], data_with_dirs={'@vstest.16.5//:Microsoft.TestPlatform.TestHostRuntimeProvider.dll': 'Extensions', '@nunit3-vs-adapter.3.16.1//:NUnitTestAdapter.TestAdapter.dll': 'Extensions', ':schemas': 'Schemas', '@junit.testlogger//:extension': 'Extensions'}, defines=COMMON_DEFINES, keyfile='src/nunit.snk', resources=[':resource1', ':resource2', ':resource3', ':resource4', ':resource5', ':resource6'], testlauncher='@vstest.16.5//:vstest.console.exe', visibility=['//visibility:public'], deps=[':mock-assembly.dll', ':nunit.framework.dll', ':nunit.testdata.dll', ':slow-nunit-tests.dll', '@nunit3-vs-adapter.3.16.1//:NUnitTestAdapter.TestAdapter.dll'])
# Strings Part-1 - Definition,casting and indexing my_string = "Python101!" another_string = 'Welcome ' # quoting the quote ! dialog = 'He asked , "But sir, python is a snake?!" ' reply = "Monty replied , 'Of course it is.' " multi_line = """ You cans freely type here , without worrying about using \n to go on to a new line... """ # Casting! txt_num = str(123) print(txt_num) # output : '123' # Indexing letter = my_string[0] print(letter) # output : 'P' print(my_string[3],my_string[7]) # output : h 0 my_string[0] = "p" # TypeError: 'str' object does not support item assignment !
my_string = 'Python101!' another_string = 'Welcome ' dialog = 'He asked , "But sir, python is a snake?!" ' reply = "Monty replied , 'Of course it is.' " multi_line = ' You cans freely type here , without worrying about\nusing \n to go on to a new line... ' txt_num = str(123) print(txt_num) letter = my_string[0] print(letter) print(my_string[3], my_string[7]) my_string[0] = 'p'
""" Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) Example 2: Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0. """ class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices)<=1: return 0 maxi = prices[0] mini = prices[0] maxa = 0 mina = 0 alldecreasing=True for i in range(1,len(prices)): if prices[i]>maxi: #print "Max is",prices[i]," at ",i maxi=prices[i] maxa=i if i == 1: alldecreasing=False if i > 1 and alldecreasing==True: #print "In Here" return self.maxProfit(prices[mina:]) elif prices[i]<=mini: #print "Min is",prices[i]," at ",i mini=prices[i] mina=i else: if alldecreasing==True: alldecreasing=False return self.maxProfit(prices[i-1:]) #print mina,maxa if mina<maxa: #print maxi-mini return maxi-mini elif mina==maxa: return 0 else: if alldecreasing==True: return 0 return max(self.maxProfit(prices[0:maxa+1]),self.maxProfit(prices[maxa+1:mina]),self.maxProfit(prices[mina:]),0)
""" Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit. Example 1: Input: [7, 1, 5, 3, 6, 4] Output: 5 max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price) Example 2: Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0. """ class Solution(object): def max_profit(self, prices): """ :type prices: List[int] :rtype: int """ if len(prices) <= 1: return 0 maxi = prices[0] mini = prices[0] maxa = 0 mina = 0 alldecreasing = True for i in range(1, len(prices)): if prices[i] > maxi: maxi = prices[i] maxa = i if i == 1: alldecreasing = False if i > 1 and alldecreasing == True: return self.maxProfit(prices[mina:]) elif prices[i] <= mini: mini = prices[i] mina = i elif alldecreasing == True: alldecreasing = False return self.maxProfit(prices[i - 1:]) if mina < maxa: return maxi - mini elif mina == maxa: return 0 else: if alldecreasing == True: return 0 return max(self.maxProfit(prices[0:maxa + 1]), self.maxProfit(prices[maxa + 1:mina]), self.maxProfit(prices[mina:]), 0)
def solution(l): parsed = [e.split(".") for e in l] toSort = [map(int, e) for e in parsed] sortedINTs = sorted(toSort) sortedJoined = [('.'.join(str(ee) for ee in e)) for e in sortedINTs] return sortedJoined
def solution(l): parsed = [e.split('.') for e in l] to_sort = [map(int, e) for e in parsed] sorted_in_ts = sorted(toSort) sorted_joined = ['.'.join((str(ee) for ee in e)) for e in sortedINTs] return sortedJoined
#!/usr/bin/env python # -*- coding: utf-8 -*- if __name__ == '__main__': print("************************************************************************") print("* WELCOME TO ZEROMCMP (OpenSource MultiCloud Management Platform) *") print("************************************************************************")
if __name__ == '__main__': print('************************************************************************') print('* WELCOME TO ZEROMCMP (OpenSource MultiCloud Management Platform) *') print('************************************************************************')
class Settings: def __init__(self): self.screen_width = 900 self.screen_height = 700 self.bg_color = (230, 230, 230) self.ship_speed_factor = 1 # bullet self.bullet_speed_factor = 1 self.bullet_width = 4 self.bullet_height = 4 self.bullet_color = (60, 60, 60) self.bullet_count = 4 # alien self.alien_speed_factor = 1 self.fleet_drop_factor = 10 self.fleet_direction = 1
class Settings: def __init__(self): self.screen_width = 900 self.screen_height = 700 self.bg_color = (230, 230, 230) self.ship_speed_factor = 1 self.bullet_speed_factor = 1 self.bullet_width = 4 self.bullet_height = 4 self.bullet_color = (60, 60, 60) self.bullet_count = 4 self.alien_speed_factor = 1 self.fleet_drop_factor = 10 self.fleet_direction = 1
def main() -> None: S = input() print("Yes" if "AC" in [S[i:i+2] for i in range(len(S)-1)] else "No") if __name__ == '__main__': main()
def main() -> None: s = input() print('Yes' if 'AC' in [S[i:i + 2] for i in range(len(S) - 1)] else 'No') if __name__ == '__main__': main()
i= 1 while i<=3: print("Guess:", i) i=i+1 print("sorry you failed")
i = 1 while i <= 3: print('Guess:', i) i = i + 1 print('sorry you failed')
config = { # application info 'name': "texfuuin", # navbar application name 'db_path': "./texfuuin-db.json", # path to tinydb file 'port': 5000, # port to listen in production mode 'devel': True, # use gevent or flask server 'recaptcha-sitekey': "6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI", 'recaptcha-secretkey': "6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe", # user management 'default_user': "anonymous", # user default in new post form 'admin_trip': "50a3cf2", # tripcode of admin 'trip_salt': "kasdjhfkasdhfklasjdhfksjadhfkljahsdlkjfhlskj", # salt added to tripcode # validation 'uname_limit': 32, 'title_limit': 32, 'message_limit': 5000, # error 'error_msgs': { 'post-id': """The specified post could not be found.""", 'uname-limit': """The specified username is not valid.""", 'title-limit': """The specified title is not valid.""", 'message-limit': """The specified message is not valid.""", 'no-auth': """The specified tripcode is incorrect.""", 'captcha': """The captcha is incorrect.""" } }
config = {'name': 'texfuuin', 'db_path': './texfuuin-db.json', 'port': 5000, 'devel': True, 'recaptcha-sitekey': '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI', 'recaptcha-secretkey': '6LeIxAcTAAAAAGG-vFI1TnRWxMZNFuojJ4WifJWe', 'default_user': 'anonymous', 'admin_trip': '50a3cf2', 'trip_salt': 'kasdjhfkasdhfklasjdhfksjadhfkljahsdlkjfhlskj', 'uname_limit': 32, 'title_limit': 32, 'message_limit': 5000, 'error_msgs': {'post-id': 'The specified post could not be found.', 'uname-limit': 'The specified username is not valid.', 'title-limit': 'The specified title is not valid.', 'message-limit': 'The specified message is not valid.', 'no-auth': 'The specified tripcode is incorrect.', 'captcha': 'The captcha is incorrect.'}}
src = Split(''' aos/soc_impl.c hal/uart.c hal/flash.c main.c ''') deps = Split(''' kernel/rhino platform/arch/arm/armv7m platform/mcu/wm_w600/ kernel/vcall kernel/init ''') global_macro = Split(''' STDIO_UART=0 CONFIG_NO_TCPIP RHINO_CONFIG_TICK_TASK=0 RHINO_CONFIG_WORKQUEUE=0 CONFIG_AOS_KV_MULTIPTN_MODE CONFIG_AOS_KV_PTN=5 CONFIG_AOS_KV_SECOND_PTN=6 CONFIG_AOS_KV_PTN_SIZE=4096 CONFIG_AOS_KV_BUFFER_SIZE=8192 SYSINFO_PRODUCT_MODEL=\\"ALI_AOS_WM_W600\\" SYSINFO_DEVICE_NAME=\\"WM_W600\\" ''') global_cflags = Split(''' -mcpu=cortex-m3 -mthumb -mfloat-abi=soft -march=armv7-m -mthumb -mthumb-interwork -mlittle-endian -w ''') local_cflags = Split(''' -Wall -Werror -Wno-unused-variable -Wno-unused-parameter -Wno-implicit-function-declaration -Wno-type-limits -Wno-sign-compare -Wno-pointer-sign -Wno-uninitialized -Wno-return-type -Wno-unused-function -Wno-unused-but-set-variable -Wno-unused-value -Wno-strict-aliasing ''') global_includes = Split(''' ../../arch/arm/armv7m/gcc/m3 ''') global_ldflags = Split(''' -mcpu=cortex-m3 -mthumb -mthumb-interwork -mlittle-endian -nostartfiles --specs=nosys.specs ''') prefix = '' if aos_global_config.compiler == "gcc": prefix = 'arm-none-eabi-' component = aos_mcu_component('WM_W600', prefix, src) component.set_global_arch('Cortex-M3') component.add_comp_deps(*deps) component.add_global_macros(*global_macro) component.add_global_cflags(*global_cflags) component.add_cflags(*local_cflags) component.add_global_includes(*global_includes) component.add_global_ldflags(*global_ldflags)
src = split('\n aos/soc_impl.c\n hal/uart.c\n hal/flash.c \n\tmain.c\n') deps = split('\n kernel/rhino\n platform/arch/arm/armv7m\n platform/mcu/wm_w600/\n kernel/vcall\n kernel/init\n') global_macro = split('\n STDIO_UART=0 \n CONFIG_NO_TCPIP\n RHINO_CONFIG_TICK_TASK=0 \n RHINO_CONFIG_WORKQUEUE=0\n CONFIG_AOS_KV_MULTIPTN_MODE\n CONFIG_AOS_KV_PTN=5\n CONFIG_AOS_KV_SECOND_PTN=6\n CONFIG_AOS_KV_PTN_SIZE=4096\n CONFIG_AOS_KV_BUFFER_SIZE=8192\n SYSINFO_PRODUCT_MODEL=\\"ALI_AOS_WM_W600\\" \n SYSINFO_DEVICE_NAME=\\"WM_W600\\"\n') global_cflags = split('\n -mcpu=cortex-m3\n -mthumb\n -mfloat-abi=soft\n -march=armv7-m\n -mthumb -mthumb-interwork\n -mlittle-endian\n -w\n ') local_cflags = split('\n -Wall \n -Werror\n -Wno-unused-variable\n -Wno-unused-parameter\n -Wno-implicit-function-declaration\n -Wno-type-limits\n -Wno-sign-compare\n -Wno-pointer-sign\n -Wno-uninitialized\n -Wno-return-type\n -Wno-unused-function\n -Wno-unused-but-set-variable\n -Wno-unused-value\n -Wno-strict-aliasing\n') global_includes = split('\n ../../arch/arm/armv7m/gcc/m3\n') global_ldflags = split('\n -mcpu=cortex-m3 \n -mthumb -mthumb-interwork\n -mlittle-endian\n -nostartfiles\n --specs=nosys.specs\n') prefix = '' if aos_global_config.compiler == 'gcc': prefix = 'arm-none-eabi-' component = aos_mcu_component('WM_W600', prefix, src) component.set_global_arch('Cortex-M3') component.add_comp_deps(*deps) component.add_global_macros(*global_macro) component.add_global_cflags(*global_cflags) component.add_cflags(*local_cflags) component.add_global_includes(*global_includes) component.add_global_ldflags(*global_ldflags)
# Test helper functions and classes class ParameterPassLevel: FLAG = 0 INI_KEY = 1 MARKER = 2 def _assert_result_outcomes( result, passed=0, skipped=0, failed=0, error=0, dynamic_rerun=0 ): outcomes = result.parseoutcomes() _check_outcome_field(outcomes, "passed", passed) _check_outcome_field(outcomes, "skipped", skipped) _check_outcome_field(outcomes, "failed", failed) _check_outcome_field(outcomes, "error", error) _check_outcome_field(outcomes, "dynamicrerun", dynamic_rerun) def _check_outcome_field(outcomes, field_name, expected_value): field_value = outcomes.get(field_name, 0) expected_value = int(expected_value) assert ( field_value == expected_value ), "outcomes.{} has unexpected value. Expected '{}' but got '{}'".format( field_name, expected_value, field_value )
class Parameterpasslevel: flag = 0 ini_key = 1 marker = 2 def _assert_result_outcomes(result, passed=0, skipped=0, failed=0, error=0, dynamic_rerun=0): outcomes = result.parseoutcomes() _check_outcome_field(outcomes, 'passed', passed) _check_outcome_field(outcomes, 'skipped', skipped) _check_outcome_field(outcomes, 'failed', failed) _check_outcome_field(outcomes, 'error', error) _check_outcome_field(outcomes, 'dynamicrerun', dynamic_rerun) def _check_outcome_field(outcomes, field_name, expected_value): field_value = outcomes.get(field_name, 0) expected_value = int(expected_value) assert field_value == expected_value, "outcomes.{} has unexpected value. Expected '{}' but got '{}'".format(field_name, expected_value, field_value)
# O(1) time | O(1) space def validIPAddresses(string): ipAddressesFound = [] for i in range(1, min(len(string), 4)): # from index 0 - 4 currentIPAddressParts = ["","","",""] currentIPAddressParts[0] = string[:i] # before the first period if not isValidPart(currentIPAddressParts[0]): continue for j in range(i + 1, i + min(len(string) - i, 4)): # i + 1 = for second period, placement of i at most in 3 positions past of i currentIPAddressParts[1] = string[i : j] # start from index i where the first position started to j at placement if not isValidPart(currentIPAddressParts[1]): continue for k in range(j + 1, j + min(len(string) - j, 4)): # j + 1 = for third period, placement of j at most in 3 positions past of j currentIPAddressParts[2] = string[j:k] # 3rd section currentIPAddressParts[3] = string[k:] # 4th section if isValidPart(currentIPAddressParts[2]) and isValidPart(currentIPAddressParts[3]): ipAddressesFound.append(".".join(currentIPAddressParts)) return ipAddressesFound def isValidPart(string): stringAsInt = int(string) if stringAsInt > 255: return False return len(string) == len(str(stringAsInt)) # check for leading 0 # 00 converted to 0, 01 converted to 1
def valid_ip_addresses(string): ip_addresses_found = [] for i in range(1, min(len(string), 4)): current_ip_address_parts = ['', '', '', ''] currentIPAddressParts[0] = string[:i] if not is_valid_part(currentIPAddressParts[0]): continue for j in range(i + 1, i + min(len(string) - i, 4)): currentIPAddressParts[1] = string[i:j] if not is_valid_part(currentIPAddressParts[1]): continue for k in range(j + 1, j + min(len(string) - j, 4)): currentIPAddressParts[2] = string[j:k] currentIPAddressParts[3] = string[k:] if is_valid_part(currentIPAddressParts[2]) and is_valid_part(currentIPAddressParts[3]): ipAddressesFound.append('.'.join(currentIPAddressParts)) return ipAddressesFound def is_valid_part(string): string_as_int = int(string) if stringAsInt > 255: return False return len(string) == len(str(stringAsInt))
REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", # TODO: 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', # django-oauth-toolkit >= 1.0.0 # 'rest_framework_social_oauth2.authentication.SocialAuthentication', ), "DEFAULT_RENDERER_CLASSES": ("rest_framework.renderers.JSONRenderer",), "DEFAULT_PARSER_CLASSES": ( "rest_framework.parsers.JSONParser", "rest_framework.parsers.FormParser", "rest_framework.parsers.MultiPartParser", "rest_framework.parsers.FileUploadParser", ), "DATETIME_FORMAT": "%d-%m-%Y %H:%M", "PAGE_SIZE": 10, "DEFAULT_PAGINATION_CLASS": "rest_framework.pagination.LimitOffsetPagination", "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.URLPathVersioning", }
rest_framework = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',), 'DEFAULT_RENDERER_CLASSES': ('rest_framework.renderers.JSONRenderer',), 'DEFAULT_PARSER_CLASSES': ('rest_framework.parsers.JSONParser', 'rest_framework.parsers.FormParser', 'rest_framework.parsers.MultiPartParser', 'rest_framework.parsers.FileUploadParser'), 'DATETIME_FORMAT': '%d-%m-%Y %H:%M', 'PAGE_SIZE': 10, 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination', 'DEFAULT_VERSIONING_CLASS': 'rest_framework.versioning.URLPathVersioning'}
def is_merge(s, part1, part2): all_chars = len(s) == len(part1) + len(part2) if not all_chars: return False d = {} for i, c in enumerate(s): d[c] = i indices1, indices2 = [d[c] for c in part1], [d[c] for c in part2] part1_good = indices1 == sorted(indices1) part2_good = indices2 == sorted(indices2) return part1_good and part2_good
def is_merge(s, part1, part2): all_chars = len(s) == len(part1) + len(part2) if not all_chars: return False d = {} for (i, c) in enumerate(s): d[c] = i (indices1, indices2) = ([d[c] for c in part1], [d[c] for c in part2]) part1_good = indices1 == sorted(indices1) part2_good = indices2 == sorted(indices2) return part1_good and part2_good
def Duplicate_Charaters(Test_String): Duplicates = [] for char in Test_String: if Test_String.count(char) > 1 and char not in Duplicates: Duplicates.append(char) return Duplicates Test_String = input("Enter a String: ") print(*(Duplicate_Charaters(Test_String)))
def duplicate__charaters(Test_String): duplicates = [] for char in Test_String: if Test_String.count(char) > 1 and char not in Duplicates: Duplicates.append(char) return Duplicates test__string = input('Enter a String: ') print(*duplicate__charaters(Test_String))
#!python3 def main(): with open('21.txt', 'r') as f, open('21_out.txt', 'w') as f_out: lines = f.readlines() # Part 1 answer = 0 print(answer) print(answer, file=f_out) # Part 2 print(answer) print(answer, file=f_out) if __name__ == '__main__': main()
def main(): with open('21.txt', 'r') as f, open('21_out.txt', 'w') as f_out: lines = f.readlines() answer = 0 print(answer) print(answer, file=f_out) print(answer) print(answer, file=f_out) if __name__ == '__main__': main()
class HashState: def __init__(self, player, cards, leading, upper, lower, tricks): self.current_player = player self.cards = cards self.upper_bound = upper self.lower_bound = lower self.leading_suite = leading self.tricks_left = tricks def get_current_player(self): return self.current_player def set_current_player(self, player): self.current_player = player def get_cards(self): return self.cards def set_cards(self, cards): self.cards = cards def get_upper_bound(self): return self.upper_bound def set_upper_bound(self, upper): self.upper_bound = upper def get_lower_bound(self): return self.lower_bound def set_lower_bound(self, lower): self.lower_bound = lower def get_leading_suite(self): return self.leading_suite def set_leading_suite(self, leading): self.leading_suite = leading def get_tricks_left(self): return self.tricks_left def set_tricks_left(self, tricks): self.tricks_left = tricks
class Hashstate: def __init__(self, player, cards, leading, upper, lower, tricks): self.current_player = player self.cards = cards self.upper_bound = upper self.lower_bound = lower self.leading_suite = leading self.tricks_left = tricks def get_current_player(self): return self.current_player def set_current_player(self, player): self.current_player = player def get_cards(self): return self.cards def set_cards(self, cards): self.cards = cards def get_upper_bound(self): return self.upper_bound def set_upper_bound(self, upper): self.upper_bound = upper def get_lower_bound(self): return self.lower_bound def set_lower_bound(self, lower): self.lower_bound = lower def get_leading_suite(self): return self.leading_suite def set_leading_suite(self, leading): self.leading_suite = leading def get_tricks_left(self): return self.tricks_left def set_tricks_left(self, tricks): self.tricks_left = tricks
# -*- coding: utf-8 -*- # License: See LICENSE file. required_states = ['position'] required_matrices = ['cellular_binary_grass'] def run(name, world, matrices, states, extra_life=10): y,x = states['position'] #if matrices['cellular_binary_grass'][int(y),int(x)]: # Eat the cell under the agent's position matrices['cellular_binary_grass'][int(y),int(x)] = False #endif
required_states = ['position'] required_matrices = ['cellular_binary_grass'] def run(name, world, matrices, states, extra_life=10): (y, x) = states['position'] matrices['cellular_binary_grass'][int(y), int(x)] = False
class Config: def __init__(self, classified_types: [str]): self.classified_types = classified_types
class Config: def __init__(self, classified_types: [str]): self.classified_types = classified_types
nterms = int(input("Stevilo cifr? ")) n1, n2 = 0, 1 count = 0 if nterms <= 0: print("Vnesi pozitivno stevilo: ") elif nterms == 1: print("Sekvenca do ",nterms,": ") print(n1) else: print("Sekvenca:") while count < nterms: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1
nterms = int(input('Stevilo cifr? ')) (n1, n2) = (0, 1) count = 0 if nterms <= 0: print('Vnesi pozitivno stevilo: ') elif nterms == 1: print('Sekvenca do ', nterms, ': ') print(n1) else: print('Sekvenca:') while count < nterms: print(n1) nth = n1 + n2 n1 = n2 n2 = nth count += 1
issues=[ dict(name='Habit',number=5,season='Winter 2012', description='commit to a change, experience it, and record'), dict(name='Interview', number=4, season='Autumn 2011', description="this is your opportunity to inhabit another's mind"), dict(name= 'Digital Presence', number= 3, season= 'Summer 2011', description='what does your digital self look like?'), dict(name= 'Adventure', number=2, season= 'Spring 2011', description='take an adventure and write about it.'), dict(name= 'Unplugging', number=1, season= 'Winter 2011', description='what are you looking forward to leaving?') ] siteroot='/Users/adam/open review quarterly/source/' infodir='/Users/adam/open review quarterly/info' skip_issues_before=5 illustration_tag='=== Illustration ===' illustration_tag_sized="=== Illustration width: 50% ==="
issues = [dict(name='Habit', number=5, season='Winter 2012', description='commit to a change, experience it, and record'), dict(name='Interview', number=4, season='Autumn 2011', description="this is your opportunity to inhabit another's mind"), dict(name='Digital Presence', number=3, season='Summer 2011', description='what does your digital self look like?'), dict(name='Adventure', number=2, season='Spring 2011', description='take an adventure and write about it.'), dict(name='Unplugging', number=1, season='Winter 2011', description='what are you looking forward to leaving?')] siteroot = '/Users/adam/open review quarterly/source/' infodir = '/Users/adam/open review quarterly/info' skip_issues_before = 5 illustration_tag = '=== Illustration ===' illustration_tag_sized = '=== Illustration width: 50% ==='
def bestSum(t, arr, memo=None): """ m: target sum, t n: len(arr) time = O(n^m*m) space = O(m*m) [in each stack frame, I am storing an array, which in worst case would be m] // Memoized complexity time = O(n*m*m) space = O(m*m) """ if memo is None: memo = {} if t in memo: return memo[t] if t == 0: return [] if t < 0: return None shortestCombination = None for ele in arr: r = t - ele rRes = bestSum(r, arr, memo) if rRes is not None: combination = rRes + [ele] # If the combination is shorter than current shortest, update it if (shortestCombination is None or len(combination) < len(shortestCombination)): shortestCombination = combination memo[t] = shortestCombination return memo[t] print(bestSum(7, [5,3,4,7])) print(bestSum(8, [2,3,5])) print(bestSum(8, [1,4,5])) print(bestSum(100, [1,2,5,25]))
def best_sum(t, arr, memo=None): """ m: target sum, t n: len(arr) time = O(n^m*m) space = O(m*m) [in each stack frame, I am storing an array, which in worst case would be m] // Memoized complexity time = O(n*m*m) space = O(m*m) """ if memo is None: memo = {} if t in memo: return memo[t] if t == 0: return [] if t < 0: return None shortest_combination = None for ele in arr: r = t - ele r_res = best_sum(r, arr, memo) if rRes is not None: combination = rRes + [ele] if shortestCombination is None or len(combination) < len(shortestCombination): shortest_combination = combination memo[t] = shortestCombination return memo[t] print(best_sum(7, [5, 3, 4, 7])) print(best_sum(8, [2, 3, 5])) print(best_sum(8, [1, 4, 5])) print(best_sum(100, [1, 2, 5, 25]))
"""Expectations that can be placed on an HTTP request""" class ResponseExpectation(object): """An expectation placed on an HTTP response.""" def __init__(self): pass def validate(self, validation, response): """If the expectation is met, do nothing. If the expectation is not met, call validation.fail(...) """ pass class _ExpectedStatusCodes(ResponseExpectation): """An expectation about an HTTP response's status code""" def __init__(self, status_codes): """Create an ExpectedStatusCodes object that expects the HTTP response's status code to be one of the elements in status_codes. """ ResponseExpectation.__init__(self) self.status_codes = status_codes def validate(self, validation, response): """This expectation is met if the HTTP response code is one of the elements of self.status_codes """ if response.status_code not in self.status_codes: string_code = ' or '.join(str(status) for status in self.status_codes) if len(string_code) > 33: string_code = string_code[:34] + "..." validation.fail( "expected status code: {0}, actual status code: {1} ({2})" .format(string_code, response.status_code, response.reason)) def __repr__(self): return "{}: Code {}".format(type(self).__name__, self.status_codes) class ExpectContainsText(ResponseExpectation): """An expectation that an HTTP response will include some text.""" def __init__(self, text): """Creates an ExpectContainsText object that expects the HTTP response text to contain the specified text. """ ResponseExpectation.__init__(self) self.text = text def validate(self, validation, response): if not self.text in response.text: validation.fail("could not find '{0}' in response body: '{1}'" .format(self.text, response.text)) def __repr__(self): return "{}: expect {}".format(type(self).__name__, self.text) class ExpectedHeader(ResponseExpectation): """An expectation that an HTTP response will include a header with a specific name and value. """ def __init__(self, name, value): """Creates an ExpectedHeader object.""" ResponseExpectation.__init__(self) self.name = name self.value = value def validate(self, validation, response): if self.name not in response.headers: validation.fail("No header named: '{0}'. Found header names: {1}" .format(self.name, ', '.join(list(response.headers.keys())))) elif self.value != response.headers[self.name]: validation.fail( "The value of the '{0}' header is '{1}', expected '{2}'" .format(self.name, response.headers[self.name], self.value)) def __repr__(self): return "{}: {} should be {}".format(type(self).__name__, self.name, self.value) class ExpectedContentType(ExpectedHeader): """An expectation that an HTTP response will have a particular content type """ def __init__(self, content_type): ExpectedHeader.__init__(self, "Content-Type", content_type)
"""Expectations that can be placed on an HTTP request""" class Responseexpectation(object): """An expectation placed on an HTTP response.""" def __init__(self): pass def validate(self, validation, response): """If the expectation is met, do nothing. If the expectation is not met, call validation.fail(...) """ pass class _Expectedstatuscodes(ResponseExpectation): """An expectation about an HTTP response's status code""" def __init__(self, status_codes): """Create an ExpectedStatusCodes object that expects the HTTP response's status code to be one of the elements in status_codes. """ ResponseExpectation.__init__(self) self.status_codes = status_codes def validate(self, validation, response): """This expectation is met if the HTTP response code is one of the elements of self.status_codes """ if response.status_code not in self.status_codes: string_code = ' or '.join((str(status) for status in self.status_codes)) if len(string_code) > 33: string_code = string_code[:34] + '...' validation.fail('expected status code: {0}, actual status code: {1} ({2})'.format(string_code, response.status_code, response.reason)) def __repr__(self): return '{}: Code {}'.format(type(self).__name__, self.status_codes) class Expectcontainstext(ResponseExpectation): """An expectation that an HTTP response will include some text.""" def __init__(self, text): """Creates an ExpectContainsText object that expects the HTTP response text to contain the specified text. """ ResponseExpectation.__init__(self) self.text = text def validate(self, validation, response): if not self.text in response.text: validation.fail("could not find '{0}' in response body: '{1}'".format(self.text, response.text)) def __repr__(self): return '{}: expect {}'.format(type(self).__name__, self.text) class Expectedheader(ResponseExpectation): """An expectation that an HTTP response will include a header with a specific name and value. """ def __init__(self, name, value): """Creates an ExpectedHeader object.""" ResponseExpectation.__init__(self) self.name = name self.value = value def validate(self, validation, response): if self.name not in response.headers: validation.fail("No header named: '{0}'. Found header names: {1}".format(self.name, ', '.join(list(response.headers.keys())))) elif self.value != response.headers[self.name]: validation.fail("The value of the '{0}' header is '{1}', expected '{2}'".format(self.name, response.headers[self.name], self.value)) def __repr__(self): return '{}: {} should be {}'.format(type(self).__name__, self.name, self.value) class Expectedcontenttype(ExpectedHeader): """An expectation that an HTTP response will have a particular content type """ def __init__(self, content_type): ExpectedHeader.__init__(self, 'Content-Type', content_type)
num = 1 factors = list() while num <= 100: if (num % 10) == 0: factors.append(num) num = num + 1 print("Factors :",factors)
num = 1 factors = list() while num <= 100: if num % 10 == 0: factors.append(num) num = num + 1 print('Factors :', factors)
#! /usr/bin/env python3 """ Print patterns based on Pascal's Triangle. """ class Triangle: """Represents a Pascal's Triangle which can be rendered as text. """ def __init__(self, num_rows): self.num_rows = num_rows self.rows = [[1]] prev_row = [1] for row_num in range(1, num_rows): this_row = [1] for col_num in range(1, row_num): this_row.append(prev_row[col_num-1] + prev_row[col_num]) this_row.append(1) self.rows.append(this_row) prev_row = this_row def printAsChars(self, modulus, chars=None): assert modulus > 1, "modulus too small" if chars is None: chars = "*" + " "*(modulus-1) if len(chars) < modulus: chars += " "*(modulus - len(chars)) for row in self.rows: print(" " * (self.num_rows - len(row)), end=" ") for i in row: print(chars[i % modulus], end=" ") print() def main(): tri = Triangle(16) print(tri.rows) tri.printAsChars(2) tri.printAsChars(4) tri.printAsChars(4, " +X+") tri.printAsChars(4, " .oO") main()
""" Print patterns based on Pascal's Triangle. """ class Triangle: """Represents a Pascal's Triangle which can be rendered as text. """ def __init__(self, num_rows): self.num_rows = num_rows self.rows = [[1]] prev_row = [1] for row_num in range(1, num_rows): this_row = [1] for col_num in range(1, row_num): this_row.append(prev_row[col_num - 1] + prev_row[col_num]) this_row.append(1) self.rows.append(this_row) prev_row = this_row def print_as_chars(self, modulus, chars=None): assert modulus > 1, 'modulus too small' if chars is None: chars = '*' + ' ' * (modulus - 1) if len(chars) < modulus: chars += ' ' * (modulus - len(chars)) for row in self.rows: print(' ' * (self.num_rows - len(row)), end=' ') for i in row: print(chars[i % modulus], end=' ') print() def main(): tri = triangle(16) print(tri.rows) tri.printAsChars(2) tri.printAsChars(4) tri.printAsChars(4, ' +X+') tri.printAsChars(4, ' .oO') main()
dict( source=["/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.diag.shuf.h5"], target=["/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.drug.shuf.h5"], indx_word="/home/yzhang3151/project/NMT/experiments/nmt/ivocab.diag.pkl", indx_word_target="/home/yzhang3151/project/NMT/experiments/nmt/ivocab.drug.pkl", word_indx="/home/yzhang3151/project/NMT/experiments/nmt/vocab.diag.pkl", word_indx_trgt="/home/yzhang3151/project/NMT/experiments/nmt/vocab.drug.pkl", null_sym_source=8360, null_sym_target=1010, n_sym_source=16001, n_sym_target=16001, loopIters=1000000, seqlen=50, bs=80, dim=1000, saveFreq=30, last_forward = False, forward = True, backward = True, last_backward = False, use_context_gate=True, ########## # for coverage maintain_coverage=True, # for linguistic coverage, the dim can only be 1 coverage_dim=10, #----------------------- use_linguistic_coverage=False, # added by Zhaopeng Tu, 2015-12-16 use_fertility_model=True, max_fertility=2, coverage_accumulated_operation = "additive", ########## use_recurrent_coverage=True, use_recurrent_gating_coverage=True, use_probability_for_recurrent_coverage=True, use_input_annotations_for_recurrent_coverage=True, use_decoding_state_for_recurrent_coverage=True, )
dict(source=['/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.diag.shuf.h5'], target=['/home/yzhang3151/project/NMT/experiments/nmt/binarized_text.drug.shuf.h5'], indx_word='/home/yzhang3151/project/NMT/experiments/nmt/ivocab.diag.pkl', indx_word_target='/home/yzhang3151/project/NMT/experiments/nmt/ivocab.drug.pkl', word_indx='/home/yzhang3151/project/NMT/experiments/nmt/vocab.diag.pkl', word_indx_trgt='/home/yzhang3151/project/NMT/experiments/nmt/vocab.drug.pkl', null_sym_source=8360, null_sym_target=1010, n_sym_source=16001, n_sym_target=16001, loopIters=1000000, seqlen=50, bs=80, dim=1000, saveFreq=30, last_forward=False, forward=True, backward=True, last_backward=False, use_context_gate=True, maintain_coverage=True, coverage_dim=10, use_linguistic_coverage=False, use_fertility_model=True, max_fertility=2, coverage_accumulated_operation='additive', use_recurrent_coverage=True, use_recurrent_gating_coverage=True, use_probability_for_recurrent_coverage=True, use_input_annotations_for_recurrent_coverage=True, use_decoding_state_for_recurrent_coverage=True)
#!/usr/bin/python -tt # Copyright 2010 Google Inc. # Licensed under the Apache License, Version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # Google's Python Class # http://code.google.com/edu/languages/google-python-class/ # Basic list exercises # Fill in the code for the functions below. main() is already set up # to call the functions with a few different inputs, # printing 'OK' when each function is correct. # The starter code for each function includes a 'return' # which is just a placeholder for your code. # It's ok if you do not complete all the functions, and there # are some additional functions to try in list2.py. # A. match_ends # Given a list of strings, return the count of the number of # strings where the string length is 2 or more and the first # and last chars of the string are the same. # Note: python does not have a ++ operator, but += works. def match_ends(words): return len([word for word in words if len(word)>=2 and word[0]==word[-1]]) #print(match_ends(['aaa', 'be', 'abc', 'hello'])) # test(match_ends(['aba', 'xyz', 'aa', 'x', 'bbb']), 3) # test(match_ends(['', 'x', 'xy', 'xyx', 'xx']), 2) # test(match_ends(['aaa', 'be', 'abc', 'hello']), 1) # B. front_x # Given a list of strings, return a list with the strings # in sorted order, except group all the strings that begin with 'x' first. # e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix'] # Hint: this can be done by making 2 lists and sorting each of them # before combining them. def front_x(words): strings_with_x = sorted([word for word in words if word[0] == 'x']) other_strings = sorted([word for word in words if word[0]!= 'x']) return strings_with_x + other_strings #print(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark'])) # test(front_x(['bbb', 'ccc', 'axx', 'xzz', 'xaa']), # ['xaa', 'xzz', 'axx', 'bbb', 'ccc']) # test(front_x(['ccc', 'bbb', 'aaa', 'xcc', 'xaa']), # ['xaa', 'xcc', 'aaa', 'bbb', 'ccc']) # test(front_x(['mix', 'xyz', 'apple', 'xanadu', 'aardvark']), # ['xanadu', 'xyz', 'aardvark', 'apple', 'mix']) # C. sort_last # Given a list of non-empty tuples, return a list sorted in increasing # order by the last element in each tuple. # e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields # [(2, 2), (1, 3), (3, 4, 5), (1, 7)] # Hint: use a custom key= function to extract the last element form each tuple. def sort_last(tuples): def last_element(tuples): return tuples[-1] return sorted(tuples, key=last_element) #print(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)])) # test(sort_last([(1, 3), (3, 2), (2, 1)]), # [(2, 1), (3, 2), (1, 3)]) # test(sort_last([(2, 3), (1, 2), (3, 1)]), # [(3, 1), (1, 2), (2, 3)]) # test(sort_last([(1, 7), (1, 3), (3, 4, 5), (2, 2)]), # [(2, 2), (1, 3), (3, 4, 5), (1, 7)]) #list2 # Additional basic list exercises # D. Given a list of numbers, return a list where # all adjacent == elements have been reduced to a single element, # so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or # modify the passed in list. def remove_adjacent(nums): result = [] if len(nums) > 0: for number in nums: if len(result) == 0: result.append(number) if number != result[-1]: result.append(number) return result print(remove_adjacent([2, 2, 3, 3, 3, 4, 3])) # test(remove_adjacent([1, 2, 2, 3]), [1, 2, 3]) # test(remove_adjacent([2, 2, 3, 3, 3]), [2, 3]) # test(remove_adjacent([]), []) # E. Given two lists sorted in increasing order, create and return a merged # list of all the elements in sorted order. You may modify the passed in lists. # Ideally, the solution should work in "linear" time, making a single # pass of both lists. def linear_merge(list1, list2): return sorted((list1+list2)) print(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb'])) # test(linear_merge(['aa', 'xx', 'zz'], ['bb', 'cc']), # ['aa', 'bb', 'cc', 'xx', 'zz']) # test(linear_merge(['aa', 'xx'], ['bb', 'cc', 'zz']), # ['aa', 'bb', 'cc', 'xx', 'zz']) # test(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']), # ['aa', 'aa', 'aa', 'bb', 'bb'])
def match_ends(words): return len([word for word in words if len(word) >= 2 and word[0] == word[-1]]) def front_x(words): strings_with_x = sorted([word for word in words if word[0] == 'x']) other_strings = sorted([word for word in words if word[0] != 'x']) return strings_with_x + other_strings def sort_last(tuples): def last_element(tuples): return tuples[-1] return sorted(tuples, key=last_element) def remove_adjacent(nums): result = [] if len(nums) > 0: for number in nums: if len(result) == 0: result.append(number) if number != result[-1]: result.append(number) return result print(remove_adjacent([2, 2, 3, 3, 3, 4, 3])) def linear_merge(list1, list2): return sorted(list1 + list2) print(linear_merge(['aa', 'aa'], ['aa', 'bb', 'bb']))
#HERE IS WHERE YOU CHANGE THE URL TO YOUR MOODLE SERVER #MAKE SURE ALL THE PHP FILES ARE IN THE API FOLDER FOR THIS TO WORK #CAN CHANGE THE API KEY HERE AS WELL loginAPIcall = 'http://157.245.126.159/api/login.php' getPointsAPIcall = 'http://157.245.126.159/api/get_user_points.php' removePointsAPIcall = 'http://157.245.126.159/api/cut_user_points.php' transactionsAPIcall = 'http://157.245.126.159/api/get_user_pointlist.php' changeNicknameAPIcall = 'http://157.245.126.159/api/getnickname.php' leaderboardAPIcall = 'http://157.245.126.159/api/get_leaderboard.php' changeAvatarAPIcall = 'http://157.245.126.159/api/changeavatar.php' APIkeys = ')ma#e*lz)m*881ghgwgkc&vodfodfdopvjdqp9vb_4pdohndpw2o8g2hf=s'
login_ap_icall = 'http://157.245.126.159/api/login.php' get_points_ap_icall = 'http://157.245.126.159/api/get_user_points.php' remove_points_ap_icall = 'http://157.245.126.159/api/cut_user_points.php' transactions_ap_icall = 'http://157.245.126.159/api/get_user_pointlist.php' change_nickname_ap_icall = 'http://157.245.126.159/api/getnickname.php' leaderboard_ap_icall = 'http://157.245.126.159/api/get_leaderboard.php' change_avatar_ap_icall = 'http://157.245.126.159/api/changeavatar.php' ap_ikeys = ')ma#e*lz)m*881ghgwgkc&vodfodfdopvjdqp9vb_4pdohndpw2o8g2hf=s'
# # PySNMP MIB module DELL-NETWORKING-FIB-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DELL-NETWORKING-FIB-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:37: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, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion") dellNetMgmt, = mibBuilder.importSymbols("DELL-NETWORKING-SMI", "dellNetMgmt") InterfaceIndexOrZero, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero") InetAddressPrefixLength, InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressPrefixLength", "InetAddress", "InetAddressType") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") MibIdentifier, TimeTicks, Integer32, Counter64, iso, Unsigned32, Gauge32, ModuleIdentity, Bits, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "TimeTicks", "Integer32", "Counter64", "iso", "Unsigned32", "Gauge32", "ModuleIdentity", "Bits", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "Counter32") TextualConvention, MacAddress, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "MacAddress", "DisplayString") dellNetIpForwardMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 6027, 3, 9)) dellNetIpForwardMib.setRevisions(('2011-07-08 12:00', '2007-09-14 12:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: dellNetIpForwardMib.setRevisionsDescriptions(('This version of MIB module deprecates the dellNetIpForwardTable and replaces it with dellNetInetCidrRouteTable which adds the IP Protocol Independance ', 'Initial version of this MIB module.',)) if mibBuilder.loadTexts: dellNetIpForwardMib.setLastUpdated('200709141200Z') if mibBuilder.loadTexts: dellNetIpForwardMib.setOrganization('Dell Inc') if mibBuilder.loadTexts: dellNetIpForwardMib.setContactInfo('http://www.dell.com/support') if mibBuilder.loadTexts: dellNetIpForwardMib.setDescription('This MIB module is used to display CIDR multipath IP Routes.') dellNetIpForwardMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1)) dellNetIpForwardMibConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2)) dellNetIpForwardVariable = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 3)) chSysCardNumber = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 9, 3, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: chSysCardNumber.setStatus('current') if mibBuilder.loadTexts: chSysCardNumber.setDescription('This is the card number assigned to the line cards and the RPM cards in the chassis. The line cards number are from 0 to 13 and the RPM are from 0 to 1.') dellNetIpForwardVersionTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1), ) if mibBuilder.loadTexts: dellNetIpForwardVersionTable.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardVersionTable.setDescription("This entity's IP forward version table.") dellNetIpForwardVersionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1, 1), ).setIndexNames((0, "DELL-NETWORKING-FIB-MIB", "chSysCardNumber"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetIpForwardAddrFamily")) if mibBuilder.loadTexts: dellNetIpForwardVersionEntry.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardVersionEntry.setDescription('The row definition for the ip forward version Table.') dellNetIpForwardAddrFamily = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1, 1, 1), InetAddressType()) if mibBuilder.loadTexts: dellNetIpForwardAddrFamily.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardAddrFamily.setDescription('Address Family of the IP Forwarding Table for which this entry provides the Version information. ') dellNetIpForwardVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1, 1, 2), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpForwardVersion.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardVersion.setDescription('A version number on the Forwarding Table. This is always fetched from one line card.') dellNetIpForwardTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2), ) if mibBuilder.loadTexts: dellNetIpForwardTable.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpForwardTable.setDescription("This entity's IP Routing table.") dellNetIpForwardEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1), ).setIndexNames((0, "DELL-NETWORKING-FIB-MIB", "chSysCardNumber"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetIpforwardDest"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetIpforwardMask"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetIpforwardNextHop"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetIpforwardFirstHop")) if mibBuilder.loadTexts: dellNetIpForwardEntry.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpForwardEntry.setDescription('A particular route to a particular destination, under a particular policy.') dellNetIpforwardDest = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 1), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardDest.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardDest.setDescription('The destination IP address of this route. An entry with a value of 0.0.0.0 is considered a default route.') dellNetIpforwardMask = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 2), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardMask.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardMask.setDescription('Indicate the mask to be logical-ANDed with the destination address before being compared to the value in the dellNetIpforwardDest field.') dellNetIpforwardNextHop = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardNextHop.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardNextHop.setDescription('On remote routes, the address of the next system en route; Otherwise, 0.0.0.0.') dellNetIpforwardFirstHop = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 4), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardFirstHop.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardFirstHop.setDescription('On remote routes, the address of the Gateway to the nexthop; 0.0.0.0 if the Nexthop itself is a Gateway to the Destination') dellNetIpforwardIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardIfIndex.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardIfIndex.setDescription('The ifIndex value which identifies the local interface through which the next hop of this route should be reached.') dellNetIpforwardMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 6), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardMacAddress.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardMacAddress.setDescription('The Mac address of the NextHop.') dellNetIpforwardEgressPort = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardEgressPort.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardEgressPort.setDescription('The name of the egress port to which the packets will be forwarded.') dellNetIpforwardCamIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetIpforwardCamIndex.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardCamIndex.setDescription('Cam Entry corresponding to a row.') dellNetInetCidrIpv4RouteNumber = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetInetCidrIpv4RouteNumber.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrIpv4RouteNumber.setDescription('The number of current dellNetInetCidrRouteTable entries that are not Invalid and whose dellNetInetCidrRouteDestType is ipv4(1)') dellNetInetCidrIpv6RouteNumber = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetInetCidrIpv6RouteNumber.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrIpv6RouteNumber.setDescription('The number of current dellNetInetCidrRouteTable entries that are not Invalid and whose dellNetInetCidrRouteDestType is ipv6(2)') dellNetInetCidrRouteTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5), ) if mibBuilder.loadTexts: dellNetInetCidrRouteTable.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteTable.setDescription("This entity's IP Routing table.") dellNetInetCidrRouteTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1), ).setIndexNames((0, "DELL-NETWORKING-FIB-MIB", "chSysCardNumber"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteDestType"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteDest"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRoutePfxLen"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteNextHopType"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteNextHop"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteFirstHopType"), (0, "DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteFirstHop")) if mibBuilder.loadTexts: dellNetInetCidrRouteTableEntry.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteTableEntry.setDescription('A particular route to a particular destination Implementers need to be aware that if the total number of elements (octets or sub-identifiers) in inetCidrRouteDest, inetCidrRoutePolicy, and inetCidrRouteNextHop exceeds 111, then OIDs of column instances in this table will have more than 128 sub- identifiers and cannot be accessed using SNMPv1, SNMPv2c, or SNMPv3. For S-Series Platform, Value of chSysCardNumber will always be zero') dellNetInetCidrRouteDestType = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 1), InetAddressType()) if mibBuilder.loadTexts: dellNetInetCidrRouteDestType.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteDestType.setDescription('The type of the inetCidrRouteDest address, as defined in the InetAddress MIB. Only those address types that may appear in an actual routing table are allowed as values of this object.') dellNetInetCidrRouteDest = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 2), InetAddress()) if mibBuilder.loadTexts: dellNetInetCidrRouteDest.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteDest.setDescription('The destination IP address of this route. The type of this address is determined by the value of the inetCidrRouteDestType object.') dellNetInetCidrRoutePfxLen = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 3), InetAddressPrefixLength()) if mibBuilder.loadTexts: dellNetInetCidrRoutePfxLen.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRoutePfxLen.setDescription('Indicates the number of leading one bits that form the mask to be logical-ANDed with the destination address before being compared to the value in the inetCidrRouteDest field.') dellNetInetCidrRouteNextHopType = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 4), InetAddressType()) if mibBuilder.loadTexts: dellNetInetCidrRouteNextHopType.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteNextHopType.setDescription('The type of the inetCidrRouteNextHop address, as defined in the InetAddress MIB. Value should be set to unknown(0) for non-remote routes. Only those address types that may appear in an actual routing table are allowed as values of this object.') dellNetInetCidrRouteNextHop = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 5), InetAddress()) if mibBuilder.loadTexts: dellNetInetCidrRouteNextHop.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteNextHop.setDescription('On remote routes, the address of the next system en route. For non-remote routes, a zero length string. The type of this address is determined by the value of the inetCidrRouteNextHopType object.') dellNetInetCidrRouteFirstHopType = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 6), InetAddressType()) if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHopType.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHopType.setDescription('The type of the inetCidrRouteFirstHop address, as defined in the InetAddress MIB. Value should be set to unknown(0) for non-remote routes. Only those address types that may appear in an actual routing table are allowed as values of this object.') dellNetInetCidrRouteFirstHop = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 7), InetAddress()) if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHop.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHop.setDescription('The address of the gateway to the Nexthop. If the nexthop itself is the gateway, a zero length string. The type of this address is determined by the value of the inetCidrRouteFirstHopType object.') dellNetInetCidrRouteIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 8), InterfaceIndexOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetInetCidrRouteIfIndex.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteIfIndex.setDescription('The ifIndex value that identifies the local interface through which the next hop of this route should be reached. A value of 0 is valid and represents the scenario where no interface is specified.') dellNetInetCidrRouteMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 9), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetInetCidrRouteMacAddress.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteMacAddress.setDescription('The Mac address of the NextHop.') dellNetInetCidrRouteEgressPort = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetInetCidrRouteEgressPort.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteEgressPort.setDescription('The name of the egress port to which the packets will be forwarded.') dellNetInetCidrRouteCamIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 11), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dellNetInetCidrRouteCamIndex.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteCamIndex.setDescription('Cam Entry corresponding to a row.') dellNetIpForwardMibCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 1)) dellNetIpForwardMibGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 2)) dellNetIpForwardMibCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 1, 1)).setObjects(("DELL-NETWORKING-FIB-MIB", "dellNetIpForwardObjectGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dellNetIpForwardMibCompliance = dellNetIpForwardMibCompliance.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardMibCompliance.setDescription('The basic implementation requirements for the Dell Networking OS Ip Forward MIB.') dellNetIpForwardObjectGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 2, 1)).setObjects(("DELL-NETWORKING-FIB-MIB", "dellNetIpForwardVersion"), ("DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteIfIndex"), ("DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteMacAddress"), ("DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteEgressPort"), ("DELL-NETWORKING-FIB-MIB", "dellNetInetCidrRouteCamIndex")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dellNetIpForwardObjectGroup = dellNetIpForwardObjectGroup.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardObjectGroup.setDescription('Objects for the IP aware Route Table.') mibBuilder.exportSymbols("DELL-NETWORKING-FIB-MIB", dellNetIpForwardMibGroups=dellNetIpForwardMibGroups, dellNetIpForwardEntry=dellNetIpForwardEntry, dellNetIpforwardDest=dellNetIpforwardDest, dellNetIpForwardObjectGroup=dellNetIpForwardObjectGroup, dellNetIpforwardCamIndex=dellNetIpforwardCamIndex, dellNetInetCidrIpv4RouteNumber=dellNetInetCidrIpv4RouteNumber, dellNetIpForwardMib=dellNetIpForwardMib, dellNetIpForwardMibCompliance=dellNetIpForwardMibCompliance, dellNetInetCidrRouteNextHopType=dellNetInetCidrRouteNextHopType, dellNetInetCidrRouteTableEntry=dellNetInetCidrRouteTableEntry, dellNetIpforwardIfIndex=dellNetIpforwardIfIndex, dellNetIpForwardVersionEntry=dellNetIpForwardVersionEntry, dellNetInetCidrRouteIfIndex=dellNetInetCidrRouteIfIndex, dellNetInetCidrRouteFirstHop=dellNetInetCidrRouteFirstHop, dellNetIpforwardEgressPort=dellNetIpforwardEgressPort, PYSNMP_MODULE_ID=dellNetIpForwardMib, dellNetIpForwardTable=dellNetIpForwardTable, dellNetInetCidrRouteEgressPort=dellNetInetCidrRouteEgressPort, dellNetInetCidrRouteCamIndex=dellNetInetCidrRouteCamIndex, dellNetInetCidrIpv6RouteNumber=dellNetInetCidrIpv6RouteNumber, chSysCardNumber=chSysCardNumber, dellNetInetCidrRouteTable=dellNetInetCidrRouteTable, dellNetIpForwardVersion=dellNetIpForwardVersion, dellNetInetCidrRouteNextHop=dellNetInetCidrRouteNextHop, dellNetInetCidrRouteMacAddress=dellNetInetCidrRouteMacAddress, dellNetIpforwardNextHop=dellNetIpforwardNextHop, dellNetIpForwardMibObjects=dellNetIpForwardMibObjects, dellNetIpforwardFirstHop=dellNetIpforwardFirstHop, dellNetInetCidrRouteFirstHopType=dellNetInetCidrRouteFirstHopType, dellNetInetCidrRouteDestType=dellNetInetCidrRouteDestType, dellNetInetCidrRouteDest=dellNetInetCidrRouteDest, dellNetIpForwardMibCompliances=dellNetIpForwardMibCompliances, dellNetIpForwardVariable=dellNetIpForwardVariable, dellNetIpforwardMacAddress=dellNetIpforwardMacAddress, dellNetInetCidrRoutePfxLen=dellNetInetCidrRoutePfxLen, dellNetIpForwardAddrFamily=dellNetIpForwardAddrFamily, dellNetIpforwardMask=dellNetIpforwardMask, dellNetIpForwardVersionTable=dellNetIpForwardVersionTable, dellNetIpForwardMibConformance=dellNetIpForwardMibConformance)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, constraints_intersection, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion') (dell_net_mgmt,) = mibBuilder.importSymbols('DELL-NETWORKING-SMI', 'dellNetMgmt') (interface_index_or_zero,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndexOrZero') (inet_address_prefix_length, inet_address, inet_address_type) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressPrefixLength', 'InetAddress', 'InetAddressType') (object_group, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'ModuleCompliance', 'NotificationGroup') (mib_identifier, time_ticks, integer32, counter64, iso, unsigned32, gauge32, module_identity, bits, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, ip_address, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'TimeTicks', 'Integer32', 'Counter64', 'iso', 'Unsigned32', 'Gauge32', 'ModuleIdentity', 'Bits', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'IpAddress', 'Counter32') (textual_convention, mac_address, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'MacAddress', 'DisplayString') dell_net_ip_forward_mib = module_identity((1, 3, 6, 1, 4, 1, 6027, 3, 9)) dellNetIpForwardMib.setRevisions(('2011-07-08 12:00', '2007-09-14 12:00')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: dellNetIpForwardMib.setRevisionsDescriptions(('This version of MIB module deprecates the dellNetIpForwardTable and replaces it with dellNetInetCidrRouteTable which adds the IP Protocol Independance ', 'Initial version of this MIB module.')) if mibBuilder.loadTexts: dellNetIpForwardMib.setLastUpdated('200709141200Z') if mibBuilder.loadTexts: dellNetIpForwardMib.setOrganization('Dell Inc') if mibBuilder.loadTexts: dellNetIpForwardMib.setContactInfo('http://www.dell.com/support') if mibBuilder.loadTexts: dellNetIpForwardMib.setDescription('This MIB module is used to display CIDR multipath IP Routes.') dell_net_ip_forward_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1)) dell_net_ip_forward_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2)) dell_net_ip_forward_variable = mib_identifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 3)) ch_sys_card_number = mib_scalar((1, 3, 6, 1, 4, 1, 6027, 3, 9, 3, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: chSysCardNumber.setStatus('current') if mibBuilder.loadTexts: chSysCardNumber.setDescription('This is the card number assigned to the line cards and the RPM cards in the chassis. The line cards number are from 0 to 13 and the RPM are from 0 to 1.') dell_net_ip_forward_version_table = mib_table((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1)) if mibBuilder.loadTexts: dellNetIpForwardVersionTable.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardVersionTable.setDescription("This entity's IP forward version table.") dell_net_ip_forward_version_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1, 1)).setIndexNames((0, 'DELL-NETWORKING-FIB-MIB', 'chSysCardNumber'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetIpForwardAddrFamily')) if mibBuilder.loadTexts: dellNetIpForwardVersionEntry.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardVersionEntry.setDescription('The row definition for the ip forward version Table.') dell_net_ip_forward_addr_family = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1, 1, 1), inet_address_type()) if mibBuilder.loadTexts: dellNetIpForwardAddrFamily.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardAddrFamily.setDescription('Address Family of the IP Forwarding Table for which this entry provides the Version information. ') dell_net_ip_forward_version = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 1, 1, 2), counter64()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpForwardVersion.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardVersion.setDescription('A version number on the Forwarding Table. This is always fetched from one line card.') dell_net_ip_forward_table = mib_table((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2)) if mibBuilder.loadTexts: dellNetIpForwardTable.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpForwardTable.setDescription("This entity's IP Routing table.") dell_net_ip_forward_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1)).setIndexNames((0, 'DELL-NETWORKING-FIB-MIB', 'chSysCardNumber'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetIpforwardDest'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetIpforwardMask'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetIpforwardNextHop'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetIpforwardFirstHop')) if mibBuilder.loadTexts: dellNetIpForwardEntry.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpForwardEntry.setDescription('A particular route to a particular destination, under a particular policy.') dell_net_ipforward_dest = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 1), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardDest.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardDest.setDescription('The destination IP address of this route. An entry with a value of 0.0.0.0 is considered a default route.') dell_net_ipforward_mask = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 2), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardMask.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardMask.setDescription('Indicate the mask to be logical-ANDed with the destination address before being compared to the value in the dellNetIpforwardDest field.') dell_net_ipforward_next_hop = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 3), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardNextHop.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardNextHop.setDescription('On remote routes, the address of the next system en route; Otherwise, 0.0.0.0.') dell_net_ipforward_first_hop = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 4), ip_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardFirstHop.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardFirstHop.setDescription('On remote routes, the address of the Gateway to the nexthop; 0.0.0.0 if the Nexthop itself is a Gateway to the Destination') dell_net_ipforward_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardIfIndex.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardIfIndex.setDescription('The ifIndex value which identifies the local interface through which the next hop of this route should be reached.') dell_net_ipforward_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 6), mac_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardMacAddress.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardMacAddress.setDescription('The Mac address of the NextHop.') dell_net_ipforward_egress_port = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardEgressPort.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardEgressPort.setDescription('The name of the egress port to which the packets will be forwarded.') dell_net_ipforward_cam_index = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 2, 1, 8), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetIpforwardCamIndex.setStatus('deprecated') if mibBuilder.loadTexts: dellNetIpforwardCamIndex.setDescription('Cam Entry corresponding to a row.') dell_net_inet_cidr_ipv4_route_number = mib_scalar((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetInetCidrIpv4RouteNumber.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrIpv4RouteNumber.setDescription('The number of current dellNetInetCidrRouteTable entries that are not Invalid and whose dellNetInetCidrRouteDestType is ipv4(1)') dell_net_inet_cidr_ipv6_route_number = mib_scalar((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetInetCidrIpv6RouteNumber.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrIpv6RouteNumber.setDescription('The number of current dellNetInetCidrRouteTable entries that are not Invalid and whose dellNetInetCidrRouteDestType is ipv6(2)') dell_net_inet_cidr_route_table = mib_table((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5)) if mibBuilder.loadTexts: dellNetInetCidrRouteTable.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteTable.setDescription("This entity's IP Routing table.") dell_net_inet_cidr_route_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1)).setIndexNames((0, 'DELL-NETWORKING-FIB-MIB', 'chSysCardNumber'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteDestType'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteDest'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRoutePfxLen'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteNextHopType'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteNextHop'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteFirstHopType'), (0, 'DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteFirstHop')) if mibBuilder.loadTexts: dellNetInetCidrRouteTableEntry.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteTableEntry.setDescription('A particular route to a particular destination Implementers need to be aware that if the total number of elements (octets or sub-identifiers) in inetCidrRouteDest, inetCidrRoutePolicy, and inetCidrRouteNextHop exceeds 111, then OIDs of column instances in this table will have more than 128 sub- identifiers and cannot be accessed using SNMPv1, SNMPv2c, or SNMPv3. For S-Series Platform, Value of chSysCardNumber will always be zero') dell_net_inet_cidr_route_dest_type = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 1), inet_address_type()) if mibBuilder.loadTexts: dellNetInetCidrRouteDestType.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteDestType.setDescription('The type of the inetCidrRouteDest address, as defined in the InetAddress MIB. Only those address types that may appear in an actual routing table are allowed as values of this object.') dell_net_inet_cidr_route_dest = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 2), inet_address()) if mibBuilder.loadTexts: dellNetInetCidrRouteDest.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteDest.setDescription('The destination IP address of this route. The type of this address is determined by the value of the inetCidrRouteDestType object.') dell_net_inet_cidr_route_pfx_len = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 3), inet_address_prefix_length()) if mibBuilder.loadTexts: dellNetInetCidrRoutePfxLen.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRoutePfxLen.setDescription('Indicates the number of leading one bits that form the mask to be logical-ANDed with the destination address before being compared to the value in the inetCidrRouteDest field.') dell_net_inet_cidr_route_next_hop_type = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 4), inet_address_type()) if mibBuilder.loadTexts: dellNetInetCidrRouteNextHopType.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteNextHopType.setDescription('The type of the inetCidrRouteNextHop address, as defined in the InetAddress MIB. Value should be set to unknown(0) for non-remote routes. Only those address types that may appear in an actual routing table are allowed as values of this object.') dell_net_inet_cidr_route_next_hop = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 5), inet_address()) if mibBuilder.loadTexts: dellNetInetCidrRouteNextHop.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteNextHop.setDescription('On remote routes, the address of the next system en route. For non-remote routes, a zero length string. The type of this address is determined by the value of the inetCidrRouteNextHopType object.') dell_net_inet_cidr_route_first_hop_type = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 6), inet_address_type()) if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHopType.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHopType.setDescription('The type of the inetCidrRouteFirstHop address, as defined in the InetAddress MIB. Value should be set to unknown(0) for non-remote routes. Only those address types that may appear in an actual routing table are allowed as values of this object.') dell_net_inet_cidr_route_first_hop = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 7), inet_address()) if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHop.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteFirstHop.setDescription('The address of the gateway to the Nexthop. If the nexthop itself is the gateway, a zero length string. The type of this address is determined by the value of the inetCidrRouteFirstHopType object.') dell_net_inet_cidr_route_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 8), interface_index_or_zero()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetInetCidrRouteIfIndex.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteIfIndex.setDescription('The ifIndex value that identifies the local interface through which the next hop of this route should be reached. A value of 0 is valid and represents the scenario where no interface is specified.') dell_net_inet_cidr_route_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 9), mac_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetInetCidrRouteMacAddress.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteMacAddress.setDescription('The Mac address of the NextHop.') dell_net_inet_cidr_route_egress_port = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 10), octet_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetInetCidrRouteEgressPort.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteEgressPort.setDescription('The name of the egress port to which the packets will be forwarded.') dell_net_inet_cidr_route_cam_index = mib_table_column((1, 3, 6, 1, 4, 1, 6027, 3, 9, 1, 5, 1, 11), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dellNetInetCidrRouteCamIndex.setStatus('current') if mibBuilder.loadTexts: dellNetInetCidrRouteCamIndex.setDescription('Cam Entry corresponding to a row.') dell_net_ip_forward_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 1)) dell_net_ip_forward_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 2)) dell_net_ip_forward_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 1, 1)).setObjects(('DELL-NETWORKING-FIB-MIB', 'dellNetIpForwardObjectGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dell_net_ip_forward_mib_compliance = dellNetIpForwardMibCompliance.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardMibCompliance.setDescription('The basic implementation requirements for the Dell Networking OS Ip Forward MIB.') dell_net_ip_forward_object_group = object_group((1, 3, 6, 1, 4, 1, 6027, 3, 9, 2, 2, 1)).setObjects(('DELL-NETWORKING-FIB-MIB', 'dellNetIpForwardVersion'), ('DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteIfIndex'), ('DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteMacAddress'), ('DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteEgressPort'), ('DELL-NETWORKING-FIB-MIB', 'dellNetInetCidrRouteCamIndex')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dell_net_ip_forward_object_group = dellNetIpForwardObjectGroup.setStatus('current') if mibBuilder.loadTexts: dellNetIpForwardObjectGroup.setDescription('Objects for the IP aware Route Table.') mibBuilder.exportSymbols('DELL-NETWORKING-FIB-MIB', dellNetIpForwardMibGroups=dellNetIpForwardMibGroups, dellNetIpForwardEntry=dellNetIpForwardEntry, dellNetIpforwardDest=dellNetIpforwardDest, dellNetIpForwardObjectGroup=dellNetIpForwardObjectGroup, dellNetIpforwardCamIndex=dellNetIpforwardCamIndex, dellNetInetCidrIpv4RouteNumber=dellNetInetCidrIpv4RouteNumber, dellNetIpForwardMib=dellNetIpForwardMib, dellNetIpForwardMibCompliance=dellNetIpForwardMibCompliance, dellNetInetCidrRouteNextHopType=dellNetInetCidrRouteNextHopType, dellNetInetCidrRouteTableEntry=dellNetInetCidrRouteTableEntry, dellNetIpforwardIfIndex=dellNetIpforwardIfIndex, dellNetIpForwardVersionEntry=dellNetIpForwardVersionEntry, dellNetInetCidrRouteIfIndex=dellNetInetCidrRouteIfIndex, dellNetInetCidrRouteFirstHop=dellNetInetCidrRouteFirstHop, dellNetIpforwardEgressPort=dellNetIpforwardEgressPort, PYSNMP_MODULE_ID=dellNetIpForwardMib, dellNetIpForwardTable=dellNetIpForwardTable, dellNetInetCidrRouteEgressPort=dellNetInetCidrRouteEgressPort, dellNetInetCidrRouteCamIndex=dellNetInetCidrRouteCamIndex, dellNetInetCidrIpv6RouteNumber=dellNetInetCidrIpv6RouteNumber, chSysCardNumber=chSysCardNumber, dellNetInetCidrRouteTable=dellNetInetCidrRouteTable, dellNetIpForwardVersion=dellNetIpForwardVersion, dellNetInetCidrRouteNextHop=dellNetInetCidrRouteNextHop, dellNetInetCidrRouteMacAddress=dellNetInetCidrRouteMacAddress, dellNetIpforwardNextHop=dellNetIpforwardNextHop, dellNetIpForwardMibObjects=dellNetIpForwardMibObjects, dellNetIpforwardFirstHop=dellNetIpforwardFirstHop, dellNetInetCidrRouteFirstHopType=dellNetInetCidrRouteFirstHopType, dellNetInetCidrRouteDestType=dellNetInetCidrRouteDestType, dellNetInetCidrRouteDest=dellNetInetCidrRouteDest, dellNetIpForwardMibCompliances=dellNetIpForwardMibCompliances, dellNetIpForwardVariable=dellNetIpForwardVariable, dellNetIpforwardMacAddress=dellNetIpforwardMacAddress, dellNetInetCidrRoutePfxLen=dellNetInetCidrRoutePfxLen, dellNetIpForwardAddrFamily=dellNetIpForwardAddrFamily, dellNetIpforwardMask=dellNetIpforwardMask, dellNetIpForwardVersionTable=dellNetIpForwardVersionTable, dellNetIpForwardMibConformance=dellNetIpForwardMibConformance)
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 elif l2 is None: return l1 head = ph = ListNode(-1) pl1 = l1 pl2 = l2 while pl1 is not None and pl2 is not None: if pl1.val > pl2.val: ph.next = pl2 pl2 = pl2.next else: ph.next = pl1 pl1 = pl1.next ph = ph.next if pl1 is not None: ph.next = pl1 if pl2 is not None: ph.next = pl2 return head.next
class Listnode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 elif l2 is None: return l1 head = ph = list_node(-1) pl1 = l1 pl2 = l2 while pl1 is not None and pl2 is not None: if pl1.val > pl2.val: ph.next = pl2 pl2 = pl2.next else: ph.next = pl1 pl1 = pl1.next ph = ph.next if pl1 is not None: ph.next = pl1 if pl2 is not None: ph.next = pl2 return head.next
class AuthNError(Exception): """AuthN is missing something. Either URL and/or API Keys Args: Exception ([type]): [description] """ pass
class Authnerror(Exception): """AuthN is missing something. Either URL and/or API Keys Args: Exception ([type]): [description] """ pass
def fib(n): f1 = 1 f2 = 2 s = 2 while f2 < n: nxt = f1 + f2 f1 = f2 f2 = nxt if nxt & 1 == 0: s += nxt return s print(fib(4000000))
def fib(n): f1 = 1 f2 = 2 s = 2 while f2 < n: nxt = f1 + f2 f1 = f2 f2 = nxt if nxt & 1 == 0: s += nxt return s print(fib(4000000))
num1=100 num2=200 num3=300
num1 = 100 num2 = 200 num3 = 300
class FieldType: def __init__(self): pass Invalid = 0 Integer = 1 Text = 2 Note = 3 DateTime = 4 Counter = 5 Choice = 6 Lookup = 7 Boolean = 8 Number = 9 Currency = 10 URL = 11 Computed = 12 Threading = 13 Guid = 14 MultiChoice = 15 GridChoice = 16 Calculated = 17 File = 18 Attachments = 19 User = 20 Recurrence = 21 CrossProjectLink = 22 ModStat = 23 Error = 24 ContentTypeId = 25 PageSeparator = 26 ThreadIndex = 27 WorkflowStatus = 28 AllDayEvent = 29 WorkflowEventType = 30 Geolocation = 31 OutcomeChoice = 32 MaxItems = 33
class Fieldtype: def __init__(self): pass invalid = 0 integer = 1 text = 2 note = 3 date_time = 4 counter = 5 choice = 6 lookup = 7 boolean = 8 number = 9 currency = 10 url = 11 computed = 12 threading = 13 guid = 14 multi_choice = 15 grid_choice = 16 calculated = 17 file = 18 attachments = 19 user = 20 recurrence = 21 cross_project_link = 22 mod_stat = 23 error = 24 content_type_id = 25 page_separator = 26 thread_index = 27 workflow_status = 28 all_day_event = 29 workflow_event_type = 30 geolocation = 31 outcome_choice = 32 max_items = 33
'''Challenges Set 1 Challenge 3 Single-byte XOR cipher''' # http://www.data-compression.com/english.html CHARACTER_FREQ = { 'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.0158610, 'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l': 0.0331490, 'm': 0.0202124, 'n': 0.0564513, 'o': 0.0596302, 'p': 0.0137645, 'q': 0.0008606, 'r': 0.0497563, 's': 0.0515760, 't': 0.0729357, 'u': 0.0225134, 'v': 0.0082903, 'w': 0.0171272, 'x': 0.0013692, 'y': 0.0145984, 'z': 0.0007836, ' ': 0.1918182 } ''' crypto is a hex string, without 0x. key is a char ''' def denc_xor(crypto, key): hex_data = crypto.decode('hex') buf = [] for ch in hex_data: buf.append(chr(ord(ch) ^ ord(key))) return ''.join(buf) def calc_score(string): score = 0 for c in string: c = c.lower() if c in CHARACTER_FREQ: score = score + CHARACTER_FREQ[c] return score def get_plain_text(hex_string): text_list = [] for i in range(256): text = denc_xor(hex_string, chr(i)) score = calc_score(text) result = { 'key':chr(i), 'plain_text':text, 'score':score } text_list.append(result) return sorted(text_list, key = lambda i: i['score'])[-1] def main(): data = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' '''Output: Cooking MC's like a pound of bacon''' print(get_plain_text(data)) if __name__ == '__main__': main()
"""Challenges Set 1 Challenge 3 Single-byte XOR cipher""" character_freq = {'a': 0.0651738, 'b': 0.0124248, 'c': 0.0217339, 'd': 0.0349835, 'e': 0.1041442, 'f': 0.0197881, 'g': 0.015861, 'h': 0.0492888, 'i': 0.0558094, 'j': 0.0009033, 'k': 0.0050529, 'l': 0.033149, 'm': 0.0202124, 'n': 0.0564513, 'o': 0.0596302, 'p': 0.0137645, 'q': 0.0008606, 'r': 0.0497563, 's': 0.051576, 't': 0.0729357, 'u': 0.0225134, 'v': 0.0082903, 'w': 0.0171272, 'x': 0.0013692, 'y': 0.0145984, 'z': 0.0007836, ' ': 0.1918182} '\ncrypto is a hex string, without 0x. key is a char\n' def denc_xor(crypto, key): hex_data = crypto.decode('hex') buf = [] for ch in hex_data: buf.append(chr(ord(ch) ^ ord(key))) return ''.join(buf) def calc_score(string): score = 0 for c in string: c = c.lower() if c in CHARACTER_FREQ: score = score + CHARACTER_FREQ[c] return score def get_plain_text(hex_string): text_list = [] for i in range(256): text = denc_xor(hex_string, chr(i)) score = calc_score(text) result = {'key': chr(i), 'plain_text': text, 'score': score} text_list.append(result) return sorted(text_list, key=lambda i: i['score'])[-1] def main(): data = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' "Output: Cooking MC's like a pound of bacon" print(get_plain_text(data)) if __name__ == '__main__': main()
bids_schema = { # BIDS identification bits 'modality': { 'type': 'string', 'required': True }, 'subject_id': { 'type': 'string', 'required': True }, 'session_id': {'type': 'string'}, 'run_id': {'type': 'string'}, 'acq_id': {'type': 'string'}, 'task_id': {'type': 'string'}, 'run_id': {'type': 'string'}, # BIDS metadata 'AccelNumReferenceLines': {'type': 'integer'}, 'AccelerationFactorPE': {'type': 'integer'}, 'AcquisitionMatrix': {'type': 'string'}, 'CogAtlasID': {'type': 'string'}, 'CogPOID': {'type': 'string'}, 'CoilCombinationMethod': {'type': 'string'}, 'ContrastBolusIngredient': {'type': 'string'}, 'ConversionSoftware': {'type': 'string'}, 'ConversionSoftwareVersion': {'type': 'string'}, 'DelayTime': {'type': 'float'}, 'DeviceSerialNumber': {'type': 'string'}, 'EchoTime': {'type': 'float'}, 'EchoTrainLength': {'type': 'integer'}, 'EffectiveEchoSpacing': {'type': 'float'}, 'FlipAngle': {'type': 'integer'}, 'GradientSetType': {'type': 'string'}, 'HardcopyDeviceSoftwareVersion': {'type': 'string'}, 'ImagingFrequency': {'type': 'integer'}, 'InPlanePhaseEncodingDirection': {'type': 'string'}, 'InstitutionAddress': {'type': 'string'}, 'InstitutionName': {'type': 'string'}, 'Instructions': {'type': 'string'}, 'InversionTime': {'type': 'float'}, 'MRAcquisitionType': {'type': 'string'}, 'MRTransmitCoilSequence': {'type': 'string'}, 'MagneticFieldStrength': {'type': 'float'}, 'Manufacturer': {'type': 'string'}, 'ManufacturersModelName': {'type': 'string'}, 'MatrixCoilMode': {'type': 'string'}, 'MultibandAccelerationFactor': {'type': 'float'}, 'NumberOfAverages': {'type': 'integer'}, 'NumberOfPhaseEncodingSteps': {'type': 'integer'}, 'NumberOfVolumesDiscardedByScanner': {'type': 'float'}, 'NumberOfVolumesDiscardedByUser': {'type': 'float'}, 'NumberShots': {'type': 'integer'}, 'ParallelAcquisitionTechnique': {'type': 'string'}, 'ParallelReductionFactorInPlane': {'type': 'float'}, 'PartialFourier': {'type': 'boolean'}, 'PartialFourierDirection': {'type': 'string'}, 'PatientPosition': {'type': 'string'}, 'PercentPhaseFieldOfView': {'type': 'integer'}, 'PercentSampling': {'type': 'integer'}, 'PhaseEncodingDirection': {'type': 'string'}, 'PixelBandwidth': {'type': 'integer'}, 'ProtocolName': {'type': 'string'}, 'PulseSequenceDetails': {'type': 'string'}, 'PulseSequenceType': {'type': 'string'}, 'ReceiveCoilName': {'type': 'string'}, 'RepetitionTime': {'type': 'float'}, 'ScanOptions': {'type': 'string'}, 'ScanningSequence': {'type': 'string'}, 'SequenceName': {'type': 'string'}, 'SequenceVariant': {'type': 'string'}, 'SliceEncodingDirection': {'type': 'string'}, 'SoftwareVersions': {'type': 'string'}, 'TaskDescription': {'type': 'string'}, 'TotalReadoutTime': {'type': 'float'}, 'TotalScanTimeSec': {'type': 'integer'}, 'TransmitCoilName': {'type': 'string'}, 'VariableFlipAngleFlag': {'type': 'string'}, } prov_schema = { 'version': { 'type': 'string', 'required': True }, 'md5sum': { 'type': 'string', 'required': True }, 'software': { 'type': 'string', 'required': True }, 'settings': { 'type': 'dict', 'schema': { 'fd_thres': {'type': 'float'}, 'hmc_fsl': {'type': 'boolean'}, 'testing': {'type': 'boolean'} }, }, 'mriqc_pred': {'type': 'integer'}, 'email': {'type': 'string'}, } bold_iqms_schema = { 'aor': { 'type': 'float', 'required': True }, 'aqi': { 'type': 'float', 'required': True }, 'dummy_trs': {'type': 'integer'}, 'dvars_nstd': { 'type': 'float', 'required': True }, 'dvars_std': { 'type': 'float', 'required': True }, 'dvars_vstd': { 'type': 'float', 'required': True }, 'efc': { 'type': 'float', 'required': True }, 'fber': { 'type': 'float', 'required': True }, 'fd_mean': { 'type': 'float', 'required': True }, 'fd_num': { 'type': 'float', 'required': True }, 'fd_perc': { 'type': 'float', 'required': True }, 'fwhm_avg': { 'type': 'float', 'required': True }, 'fwhm_x': { 'type': 'float', 'required': True }, 'fwhm_y': { 'type': 'float', 'required': True }, 'fwhm_z': { 'type': 'float', 'required': True }, 'gcor': { 'type': 'float', 'required': True }, 'gsr_x': { 'type': 'float', 'required': True }, 'gsr_y': { 'type': 'float', 'required': True }, 'size_t': { 'type': 'float', 'required': True }, 'size_x': { 'type': 'float', 'required': True }, 'size_y': { 'type': 'float', 'required': True }, 'size_z': { 'type': 'float', 'required': True }, 'snr': { 'type': 'float', 'required': True }, 'spacing_tr': { 'type': 'float', 'required': True }, 'spacing_x': { 'type': 'float', 'required': True }, 'spacing_y': { 'type': 'float', 'required': True }, 'spacing_z': { 'type': 'float', 'required': True }, 'summary_bg_k': { 'type': 'float', 'required': True }, 'summary_bg_mean': { 'type': 'float', 'required': True }, 'summary_bg_median': { 'type': 'float', 'required': True }, 'summary_bg_mad': { 'type': 'float', 'required': True }, 'summary_bg_p05': { 'type': 'float', 'required': True }, 'summary_bg_p95': { 'type': 'float', 'required': True }, 'summary_bg_stdv': { 'type': 'float', 'required': True }, 'summary_bg_n': { 'type': 'float', 'required': True }, 'summary_fg_k': { 'type': 'float', 'required': True }, 'summary_fg_mean': { 'type': 'float', 'required': True }, 'summary_fg_median': { 'type': 'float', 'required': True }, 'summary_fg_mad': { 'type': 'float', 'required': True }, 'summary_fg_p05': { 'type': 'float', 'required': True }, 'summary_fg_p95': { 'type': 'float', 'required': True }, 'summary_fg_stdv': { 'type': 'float', 'required': True }, 'summary_fg_n': { 'type': 'float', 'required': True }, 'tsnr': { 'type': 'float', 'required': True }, } struct_iqms_schema = { 'cjv': { 'type': 'float', 'required': True }, 'cnr': { 'type': 'float', 'required': True }, 'efc': { 'type': 'float', 'required': True }, 'fber': { 'type': 'float', 'required': True }, 'fwhm_avg': { 'type': 'float', 'required': True }, 'fwhm_x': { 'type': 'float', 'required': True }, 'fwhm_y': { 'type': 'float', 'required': True }, 'fwhm_z': { 'type': 'float', 'required': True }, 'icvs_csf': { 'type': 'float', 'required': True }, 'icvs_gm': { 'type': 'float', 'required': True }, 'icvs_wm': { 'type': 'float', 'required': True }, 'inu_med': { 'type': 'float', 'required': True }, 'inu_range': { 'type': 'float', 'required': True }, 'qi_1': { 'type': 'float', 'required': True }, 'qi_2': { 'type': 'float', 'required': True }, 'rpve_csf': { 'type': 'float', 'required': True }, 'rpve_gm': { 'type': 'float', 'required': True }, 'rpve_wm': { 'type': 'float', 'required': True }, 'size_x': { 'type': 'integer', 'required': True }, 'size_y': { 'type': 'integer', 'required': True }, 'size_z': { 'type': 'integer', 'required': True }, 'snr_csf': { 'type': 'float', 'required': True }, 'snr_gm': { 'type': 'float', 'required': True }, 'snr_total': { 'type': 'float', 'required': True }, 'snr_wm': { 'type': 'float', 'required': True }, 'snrd_csf': { 'type': 'float', 'required': True }, 'snrd_gm': { 'type': 'float', 'required': True }, 'snrd_total': { 'type': 'float', 'required': True }, 'snrd_wm': { 'type': 'float', 'required': True }, 'spacing_x': { 'type': 'float', 'required': True }, 'spacing_y': { 'type': 'float', 'required': True }, 'spacing_z': { 'type': 'float', 'required': True }, 'summary_bg_k': { 'type': 'float', 'required': True }, 'summary_bg_mean': { 'type': 'float', 'required': True }, 'summary_bg_median': { 'type': 'float' }, 'summary_bg_mad': { 'type': 'float' }, 'summary_bg_p05': { 'type': 'float', 'required': True }, 'summary_bg_p95': { 'type': 'float', 'required': True }, 'summary_bg_stdv': { 'type': 'float', 'required': True }, 'summary_bg_n': { 'type': 'float' }, 'summary_csf_k': { 'type': 'float', 'required': True }, 'summary_csf_mean': { 'type': 'float', 'required': True }, 'summary_csf_median': { 'type': 'float' }, 'summary_csf_mad': { 'type': 'float' }, 'summary_csf_p05': { 'type': 'float', 'required': True }, 'summary_csf_p95': { 'type': 'float', 'required': True }, 'summary_csf_stdv': { 'type': 'float', 'required': True }, 'summary_csf_n': { 'type': 'float' }, 'summary_gm_k': { 'type': 'float', 'required': True }, 'summary_gm_mean': { 'type': 'float', 'required': True }, 'summary_gm_median': { 'type': 'float' }, 'summary_gm_mad': { 'type': 'float' }, 'summary_gm_p05': { 'type': 'float', 'required': True }, 'summary_gm_p95': { 'type': 'float', 'required': True }, 'summary_gm_stdv': { 'type': 'float', 'required': True }, 'summary_gm_n': { 'type': 'float' }, 'summary_wm_k': { 'type': 'float', 'required': True }, 'summary_wm_mean': { 'type': 'float', 'required': True }, 'summary_wm_median': { 'type': 'float' }, 'summary_wm_mad': { 'type': 'float' }, 'summary_wm_p05': { 'type': 'float', 'required': True }, 'summary_wm_p95': { 'type': 'float', 'required': True }, 'summary_wm_stdv': { 'type': 'float', 'required': True }, 'summary_wm_n': { 'type': 'float' }, 'tpm_overlap_csf': { 'type': 'float', 'required': True }, 'tpm_overlap_gm': { 'type': 'float', 'required': True }, 'tpm_overlap_wm': { 'type': 'float', 'required': True }, 'wm2max': { 'type': 'float', 'required': True }, } rating_schema = { 'rating': { 'type': 'string', 'required': True }, 'name': { 'type': 'string', 'required': False }, 'comment': { 'type': 'string', 'required': False }, 'md5sum': { 'type': 'string', 'required': True } }
bids_schema = {'modality': {'type': 'string', 'required': True}, 'subject_id': {'type': 'string', 'required': True}, 'session_id': {'type': 'string'}, 'run_id': {'type': 'string'}, 'acq_id': {'type': 'string'}, 'task_id': {'type': 'string'}, 'run_id': {'type': 'string'}, 'AccelNumReferenceLines': {'type': 'integer'}, 'AccelerationFactorPE': {'type': 'integer'}, 'AcquisitionMatrix': {'type': 'string'}, 'CogAtlasID': {'type': 'string'}, 'CogPOID': {'type': 'string'}, 'CoilCombinationMethod': {'type': 'string'}, 'ContrastBolusIngredient': {'type': 'string'}, 'ConversionSoftware': {'type': 'string'}, 'ConversionSoftwareVersion': {'type': 'string'}, 'DelayTime': {'type': 'float'}, 'DeviceSerialNumber': {'type': 'string'}, 'EchoTime': {'type': 'float'}, 'EchoTrainLength': {'type': 'integer'}, 'EffectiveEchoSpacing': {'type': 'float'}, 'FlipAngle': {'type': 'integer'}, 'GradientSetType': {'type': 'string'}, 'HardcopyDeviceSoftwareVersion': {'type': 'string'}, 'ImagingFrequency': {'type': 'integer'}, 'InPlanePhaseEncodingDirection': {'type': 'string'}, 'InstitutionAddress': {'type': 'string'}, 'InstitutionName': {'type': 'string'}, 'Instructions': {'type': 'string'}, 'InversionTime': {'type': 'float'}, 'MRAcquisitionType': {'type': 'string'}, 'MRTransmitCoilSequence': {'type': 'string'}, 'MagneticFieldStrength': {'type': 'float'}, 'Manufacturer': {'type': 'string'}, 'ManufacturersModelName': {'type': 'string'}, 'MatrixCoilMode': {'type': 'string'}, 'MultibandAccelerationFactor': {'type': 'float'}, 'NumberOfAverages': {'type': 'integer'}, 'NumberOfPhaseEncodingSteps': {'type': 'integer'}, 'NumberOfVolumesDiscardedByScanner': {'type': 'float'}, 'NumberOfVolumesDiscardedByUser': {'type': 'float'}, 'NumberShots': {'type': 'integer'}, 'ParallelAcquisitionTechnique': {'type': 'string'}, 'ParallelReductionFactorInPlane': {'type': 'float'}, 'PartialFourier': {'type': 'boolean'}, 'PartialFourierDirection': {'type': 'string'}, 'PatientPosition': {'type': 'string'}, 'PercentPhaseFieldOfView': {'type': 'integer'}, 'PercentSampling': {'type': 'integer'}, 'PhaseEncodingDirection': {'type': 'string'}, 'PixelBandwidth': {'type': 'integer'}, 'ProtocolName': {'type': 'string'}, 'PulseSequenceDetails': {'type': 'string'}, 'PulseSequenceType': {'type': 'string'}, 'ReceiveCoilName': {'type': 'string'}, 'RepetitionTime': {'type': 'float'}, 'ScanOptions': {'type': 'string'}, 'ScanningSequence': {'type': 'string'}, 'SequenceName': {'type': 'string'}, 'SequenceVariant': {'type': 'string'}, 'SliceEncodingDirection': {'type': 'string'}, 'SoftwareVersions': {'type': 'string'}, 'TaskDescription': {'type': 'string'}, 'TotalReadoutTime': {'type': 'float'}, 'TotalScanTimeSec': {'type': 'integer'}, 'TransmitCoilName': {'type': 'string'}, 'VariableFlipAngleFlag': {'type': 'string'}} prov_schema = {'version': {'type': 'string', 'required': True}, 'md5sum': {'type': 'string', 'required': True}, 'software': {'type': 'string', 'required': True}, 'settings': {'type': 'dict', 'schema': {'fd_thres': {'type': 'float'}, 'hmc_fsl': {'type': 'boolean'}, 'testing': {'type': 'boolean'}}}, 'mriqc_pred': {'type': 'integer'}, 'email': {'type': 'string'}} bold_iqms_schema = {'aor': {'type': 'float', 'required': True}, 'aqi': {'type': 'float', 'required': True}, 'dummy_trs': {'type': 'integer'}, 'dvars_nstd': {'type': 'float', 'required': True}, 'dvars_std': {'type': 'float', 'required': True}, 'dvars_vstd': {'type': 'float', 'required': True}, 'efc': {'type': 'float', 'required': True}, 'fber': {'type': 'float', 'required': True}, 'fd_mean': {'type': 'float', 'required': True}, 'fd_num': {'type': 'float', 'required': True}, 'fd_perc': {'type': 'float', 'required': True}, 'fwhm_avg': {'type': 'float', 'required': True}, 'fwhm_x': {'type': 'float', 'required': True}, 'fwhm_y': {'type': 'float', 'required': True}, 'fwhm_z': {'type': 'float', 'required': True}, 'gcor': {'type': 'float', 'required': True}, 'gsr_x': {'type': 'float', 'required': True}, 'gsr_y': {'type': 'float', 'required': True}, 'size_t': {'type': 'float', 'required': True}, 'size_x': {'type': 'float', 'required': True}, 'size_y': {'type': 'float', 'required': True}, 'size_z': {'type': 'float', 'required': True}, 'snr': {'type': 'float', 'required': True}, 'spacing_tr': {'type': 'float', 'required': True}, 'spacing_x': {'type': 'float', 'required': True}, 'spacing_y': {'type': 'float', 'required': True}, 'spacing_z': {'type': 'float', 'required': True}, 'summary_bg_k': {'type': 'float', 'required': True}, 'summary_bg_mean': {'type': 'float', 'required': True}, 'summary_bg_median': {'type': 'float', 'required': True}, 'summary_bg_mad': {'type': 'float', 'required': True}, 'summary_bg_p05': {'type': 'float', 'required': True}, 'summary_bg_p95': {'type': 'float', 'required': True}, 'summary_bg_stdv': {'type': 'float', 'required': True}, 'summary_bg_n': {'type': 'float', 'required': True}, 'summary_fg_k': {'type': 'float', 'required': True}, 'summary_fg_mean': {'type': 'float', 'required': True}, 'summary_fg_median': {'type': 'float', 'required': True}, 'summary_fg_mad': {'type': 'float', 'required': True}, 'summary_fg_p05': {'type': 'float', 'required': True}, 'summary_fg_p95': {'type': 'float', 'required': True}, 'summary_fg_stdv': {'type': 'float', 'required': True}, 'summary_fg_n': {'type': 'float', 'required': True}, 'tsnr': {'type': 'float', 'required': True}} struct_iqms_schema = {'cjv': {'type': 'float', 'required': True}, 'cnr': {'type': 'float', 'required': True}, 'efc': {'type': 'float', 'required': True}, 'fber': {'type': 'float', 'required': True}, 'fwhm_avg': {'type': 'float', 'required': True}, 'fwhm_x': {'type': 'float', 'required': True}, 'fwhm_y': {'type': 'float', 'required': True}, 'fwhm_z': {'type': 'float', 'required': True}, 'icvs_csf': {'type': 'float', 'required': True}, 'icvs_gm': {'type': 'float', 'required': True}, 'icvs_wm': {'type': 'float', 'required': True}, 'inu_med': {'type': 'float', 'required': True}, 'inu_range': {'type': 'float', 'required': True}, 'qi_1': {'type': 'float', 'required': True}, 'qi_2': {'type': 'float', 'required': True}, 'rpve_csf': {'type': 'float', 'required': True}, 'rpve_gm': {'type': 'float', 'required': True}, 'rpve_wm': {'type': 'float', 'required': True}, 'size_x': {'type': 'integer', 'required': True}, 'size_y': {'type': 'integer', 'required': True}, 'size_z': {'type': 'integer', 'required': True}, 'snr_csf': {'type': 'float', 'required': True}, 'snr_gm': {'type': 'float', 'required': True}, 'snr_total': {'type': 'float', 'required': True}, 'snr_wm': {'type': 'float', 'required': True}, 'snrd_csf': {'type': 'float', 'required': True}, 'snrd_gm': {'type': 'float', 'required': True}, 'snrd_total': {'type': 'float', 'required': True}, 'snrd_wm': {'type': 'float', 'required': True}, 'spacing_x': {'type': 'float', 'required': True}, 'spacing_y': {'type': 'float', 'required': True}, 'spacing_z': {'type': 'float', 'required': True}, 'summary_bg_k': {'type': 'float', 'required': True}, 'summary_bg_mean': {'type': 'float', 'required': True}, 'summary_bg_median': {'type': 'float'}, 'summary_bg_mad': {'type': 'float'}, 'summary_bg_p05': {'type': 'float', 'required': True}, 'summary_bg_p95': {'type': 'float', 'required': True}, 'summary_bg_stdv': {'type': 'float', 'required': True}, 'summary_bg_n': {'type': 'float'}, 'summary_csf_k': {'type': 'float', 'required': True}, 'summary_csf_mean': {'type': 'float', 'required': True}, 'summary_csf_median': {'type': 'float'}, 'summary_csf_mad': {'type': 'float'}, 'summary_csf_p05': {'type': 'float', 'required': True}, 'summary_csf_p95': {'type': 'float', 'required': True}, 'summary_csf_stdv': {'type': 'float', 'required': True}, 'summary_csf_n': {'type': 'float'}, 'summary_gm_k': {'type': 'float', 'required': True}, 'summary_gm_mean': {'type': 'float', 'required': True}, 'summary_gm_median': {'type': 'float'}, 'summary_gm_mad': {'type': 'float'}, 'summary_gm_p05': {'type': 'float', 'required': True}, 'summary_gm_p95': {'type': 'float', 'required': True}, 'summary_gm_stdv': {'type': 'float', 'required': True}, 'summary_gm_n': {'type': 'float'}, 'summary_wm_k': {'type': 'float', 'required': True}, 'summary_wm_mean': {'type': 'float', 'required': True}, 'summary_wm_median': {'type': 'float'}, 'summary_wm_mad': {'type': 'float'}, 'summary_wm_p05': {'type': 'float', 'required': True}, 'summary_wm_p95': {'type': 'float', 'required': True}, 'summary_wm_stdv': {'type': 'float', 'required': True}, 'summary_wm_n': {'type': 'float'}, 'tpm_overlap_csf': {'type': 'float', 'required': True}, 'tpm_overlap_gm': {'type': 'float', 'required': True}, 'tpm_overlap_wm': {'type': 'float', 'required': True}, 'wm2max': {'type': 'float', 'required': True}} rating_schema = {'rating': {'type': 'string', 'required': True}, 'name': {'type': 'string', 'required': False}, 'comment': {'type': 'string', 'required': False}, 'md5sum': {'type': 'string', 'required': True}}
# Python - 2.7.6 class Ship: def __init__(self, draft, crew): self.draft = draft self.crew = crew def is_worth_it(self): return (self.draft - self.crew * 1.5) > 20
class Ship: def __init__(self, draft, crew): self.draft = draft self.crew = crew def is_worth_it(self): return self.draft - self.crew * 1.5 > 20
# Copyright 2018 The Bazel Authors. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. load("//go/private:providers.bzl", "GoStdLib") def _pure_transition_impl(settings, attr): return {"//go/config:pure": True} pure_transition = transition( implementation = _pure_transition_impl, inputs = ["//go/config:pure"], outputs = ["//go/config:pure"], ) def _stdlib_files_impl(ctx): # When a transition is used, ctx.attr._stdlib is a list of Target instead # of a Target. Possibly a bug? libs = ctx.attr._stdlib[0][GoStdLib].libs runfiles = ctx.runfiles(files = libs) return [DefaultInfo( files = depset(libs), runfiles = runfiles, )] stdlib_files = rule( implementation = _stdlib_files_impl, attrs = { "_stdlib": attr.label( default = "@io_bazel_rules_go//:stdlib", providers = [GoStdLib], cfg = pure_transition, # force recompilation ), "_whitelist_function_transition": attr.label( default = "@bazel_tools//tools/whitelists/function_transition_whitelist", ), }, )
load('//go/private:providers.bzl', 'GoStdLib') def _pure_transition_impl(settings, attr): return {'//go/config:pure': True} pure_transition = transition(implementation=_pure_transition_impl, inputs=['//go/config:pure'], outputs=['//go/config:pure']) def _stdlib_files_impl(ctx): libs = ctx.attr._stdlib[0][GoStdLib].libs runfiles = ctx.runfiles(files=libs) return [default_info(files=depset(libs), runfiles=runfiles)] stdlib_files = rule(implementation=_stdlib_files_impl, attrs={'_stdlib': attr.label(default='@io_bazel_rules_go//:stdlib', providers=[GoStdLib], cfg=pure_transition), '_whitelist_function_transition': attr.label(default='@bazel_tools//tools/whitelists/function_transition_whitelist')})
def is_palindrome(word: str) -> bool: word = word.replace(' ','').lower() #Take out every space and convert to lowercase the entire string assert len(word) > 0 , 'Error: Cannot process empty words' return word == word[::-1] def main(): word: str = input('Write a word: ') if is_palindrome(word): print(f'{word} is a palindrome!') else: print(f'{word} is NOT a palindrome!') if __name__ == '__main__': main()
def is_palindrome(word: str) -> bool: word = word.replace(' ', '').lower() assert len(word) > 0, 'Error: Cannot process empty words' return word == word[::-1] def main(): word: str = input('Write a word: ') if is_palindrome(word): print(f'{word} is a palindrome!') else: print(f'{word} is NOT a palindrome!') if __name__ == '__main__': main()
# Python allows you to assign values to multiple variables in one line: x, y, z = "Orange", "Banana", "Cherry" print(x) print(y) print(z) # And you can assign the same value to multiple variables in one line: x = y = z = "Orange" print(x) print(y) print(z)
(x, y, z) = ('Orange', 'Banana', 'Cherry') print(x) print(y) print(z) x = y = z = 'Orange' print(x) print(y) print(z)
frogs = input().split() while True: line = input() tokens = line.split() command = tokens[0] if command == 'Join': name = tokens[1] frogs.append(name) elif command == 'Jump': name = tokens[1] index = int(tokens[2]) if 0 <= index < len(frogs): frogs.insert(index, name) elif command == 'Dive': index = int(tokens[1]) if 0 <= index < len(frogs): frogs.pop(index) elif command == 'First': count = int(tokens[1]) frogs_to_print = frogs[:count] print(" ".join(frogs_to_print)) elif command == 'Last': count = int(tokens[1]) slice_count = len(frogs) - count frogs_to_print = frogs[slice_count:] print(" ".join(frogs_to_print)) elif command == 'Print': if tokens[1] == 'Reversed': frogs = frogs[::-1] final_frogs = " ".join(frogs) print(f'Frogs: {final_frogs}') break
frogs = input().split() while True: line = input() tokens = line.split() command = tokens[0] if command == 'Join': name = tokens[1] frogs.append(name) elif command == 'Jump': name = tokens[1] index = int(tokens[2]) if 0 <= index < len(frogs): frogs.insert(index, name) elif command == 'Dive': index = int(tokens[1]) if 0 <= index < len(frogs): frogs.pop(index) elif command == 'First': count = int(tokens[1]) frogs_to_print = frogs[:count] print(' '.join(frogs_to_print)) elif command == 'Last': count = int(tokens[1]) slice_count = len(frogs) - count frogs_to_print = frogs[slice_count:] print(' '.join(frogs_to_print)) elif command == 'Print': if tokens[1] == 'Reversed': frogs = frogs[::-1] final_frogs = ' '.join(frogs) print(f'Frogs: {final_frogs}') break
print('===== DESAFIO 065 =====') op = '' count = 0 media = 0 maior = menor = 0 while op != 'n': num = int(input('digite um valor: ')) count += 1 media += num if count == 1: maior = num menor = num else: if num > maior: maior = num if num < menor: menor = num op = str(input('vc deseja continuar: ')) print(f'a media dos numeros foi de {media/count}') print(f'o maior numero foi {maior} e o menor foi {menor}')
print('===== DESAFIO 065 =====') op = '' count = 0 media = 0 maior = menor = 0 while op != 'n': num = int(input('digite um valor: ')) count += 1 media += num if count == 1: maior = num menor = num else: if num > maior: maior = num if num < menor: menor = num op = str(input('vc deseja continuar: ')) print(f'a media dos numeros foi de {media / count}') print(f'o maior numero foi {maior} e o menor foi {menor}')
def max_sub_array_of_size_k(k, arr): # TODO: Write your code here if not arr: return -1 curSum = 0 i = 0 j = len(arr) -1 while i < j: subarr = arr[i:k] print(subarr) total = 0 for num in subarr: total += num if total > curSum: curSum = total total = 0 else: total = 0 i += 1 k += 1 return curSum print(max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])) print(max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])) print(max_sub_array_of_size_k(5, [10, 3, 4, 1, 5, 9, 2, 1, 8]))
def max_sub_array_of_size_k(k, arr): if not arr: return -1 cur_sum = 0 i = 0 j = len(arr) - 1 while i < j: subarr = arr[i:k] print(subarr) total = 0 for num in subarr: total += num if total > curSum: cur_sum = total total = 0 else: total = 0 i += 1 k += 1 return curSum print(max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2])) print(max_sub_array_of_size_k(2, [2, 3, 4, 1, 5])) print(max_sub_array_of_size_k(5, [10, 3, 4, 1, 5, 9, 2, 1, 8]))