content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
# -*- coding: utf-8 -*- class Base(RuntimeError): """An extendible class for responding to exceptions caused within your application. Usage: .. code-block: python class MyRestError(errors.Base): pass # somewhere in your code... raise MyRestError(code=01, message='You broke it', developer_message='Invalid index supplied') # {'code': '01406', message='You broke it', 'developer_message': 'Invalid index supplied'} """ class Meta(object): attributes = ( 'code', 'status', 'message', 'developer_message') def __init__( self, code, message='Unknown Error', status_code=406, developer_message=None): """Initialize the error. Args: code (int/string): A unique exception code for the error, gets combined with the status_code status_code (int): The HTTP status code associated with the response (see https://httpstatuses.com/) message (string): A human friendly exception message developer_message (string): A more complex exception message aimed at deveopers """ super(Base, self).__init__(message) self.status_code = status_code self.code = '{}{}'.format(status_code, code) self.message = message self.developer_message = '{}: {}'.format( self.__class__.__name__, developer_message or message)
class Base(RuntimeError): """An extendible class for responding to exceptions caused within your application. Usage: .. code-block: python class MyRestError(errors.Base): pass # somewhere in your code... raise MyRestError(code=01, message='You broke it', developer_message='Invalid index supplied') # {'code': '01406', message='You broke it', 'developer_message': 'Invalid index supplied'} """ class Meta(object): attributes = ('code', 'status', 'message', 'developer_message') def __init__(self, code, message='Unknown Error', status_code=406, developer_message=None): """Initialize the error. Args: code (int/string): A unique exception code for the error, gets combined with the status_code status_code (int): The HTTP status code associated with the response (see https://httpstatuses.com/) message (string): A human friendly exception message developer_message (string): A more complex exception message aimed at deveopers """ super(Base, self).__init__(message) self.status_code = status_code self.code = '{}{}'.format(status_code, code) self.message = message self.developer_message = '{}: {}'.format(self.__class__.__name__, developer_message or message)
# initialize/define the blockchain list blockchain = [] open_txs = [] def get_last_blockchain_val(): """ Returns the last element of the blockchain list. """ if len(blockchain) < 1: return None return blockchain[-1] def add_tx(tx_amt, last_tx=[1]): """ Adds the last transaction amount and current transaction amount to the blockchain list. Parameters: <tx_amt> current transaction amount. <last_tx> last transaction (default: [1]). """ if last_tx is None: last_tx = [1] return blockchain.append([last_tx, tx_amt]) def get_tx_amt(): """ Gets and returns user input (transaction amount) from the user as a float. """ return float(input("Please enter transaction amount: ")) def get_user_choice(): """ Gets and returns user input (user choice) from the user. """ return input("Please enter choice: ").upper() def mine_block(): pass def print_out_blockchain(blockchain): """ Prints out the blockchain. """ print("The entire blockchain:") print(blockchain) print("Printing out the blocks...") i = 0 for block in blockchain: print(f" Block[{i}]: {block}") i += 1 else: print("-" * 20) def validate_blockchain(blockchain): """ Validates the blockchain. """ is_valid = True print("Validating the blockchain...") for i in range(len(blockchain)): if i == 0: continue else: print( f" Comparing block[{i}] ({blockchain[i]})", f"first element ({blockchain[i][0]})", ) print(f" and previous block[{i-1}]", f"({blockchain[i-1]})... ", end="") if blockchain[i][0] == blockchain[i - 1]: print("match") is_valid = True else: print("mis-match") is_valid = False break # # --- original attempt --- # if len(blockchain) > 1: # for i in range(1, len(blockchain)): # print( # f" Comparing block[{i - 1}] ({blockchain[i - 1]})", # f"and block[{i}][0] ({blockchain[i]})... ", # end="", # ) # if blockchain[i - 1] == blockchain[i][0]: # print("match") # else: # print("mis-match") # # --- original attempt --- # # --- second attempt --- # i = 0 # for block in blockchain: # if i == 0: # i += 1 # continue # else: # print(f" Comparing block[{i}] ({block})", f"first element ({block[0]})") # print( # f" and previous block[{i-1}] ({blockchain[(i-1)]})... ", end="", # ) # if block[0] == blockchain[(i - 1)]: # print("match") # is_valid = True # else: # print("mis-match") # is_valid = False # break # i += 1 # # --- second attempt --- return is_valid more_input = True while more_input: print("Please choose") print(" a: Add a transaction value") print(" p: Print the blockchain blocks") print(" m: Manipulate the blockchain") print(" v: Validate the blockchain") print(" q: Quit") usr_choice = get_user_choice() if usr_choice == "A": tx_amt = get_tx_amt() add_tx(tx_amt, get_last_blockchain_val()) elif usr_choice == "P": print_out_blockchain(blockchain) elif usr_choice == "M": if len(blockchain) > 0: blockchain[0] = [2] elif usr_choice == "V": validate_blockchain(blockchain) elif usr_choice == "Q": more_input = False else: print(f"Not a valid choice: '{usr_choice}'") # add_tx(last_tx=get_last_blockchain_val(), tx_amt=tx_amt) if not validate_blockchain(blockchain): print(f"Not a valid blockchain! Exiting...") break else: print("No more input") print("Done!")
blockchain = [] open_txs = [] def get_last_blockchain_val(): """ Returns the last element of the blockchain list. """ if len(blockchain) < 1: return None return blockchain[-1] def add_tx(tx_amt, last_tx=[1]): """ Adds the last transaction amount and current transaction amount to the blockchain list. Parameters: <tx_amt> current transaction amount. <last_tx> last transaction (default: [1]). """ if last_tx is None: last_tx = [1] return blockchain.append([last_tx, tx_amt]) def get_tx_amt(): """ Gets and returns user input (transaction amount) from the user as a float. """ return float(input('Please enter transaction amount: ')) def get_user_choice(): """ Gets and returns user input (user choice) from the user. """ return input('Please enter choice: ').upper() def mine_block(): pass def print_out_blockchain(blockchain): """ Prints out the blockchain. """ print('The entire blockchain:') print(blockchain) print('Printing out the blocks...') i = 0 for block in blockchain: print(f' Block[{i}]: {block}') i += 1 else: print('-' * 20) def validate_blockchain(blockchain): """ Validates the blockchain. """ is_valid = True print('Validating the blockchain...') for i in range(len(blockchain)): if i == 0: continue else: print(f' Comparing block[{i}] ({blockchain[i]})', f'first element ({blockchain[i][0]})') print(f' and previous block[{i - 1}]', f'({blockchain[i - 1]})... ', end='') if blockchain[i][0] == blockchain[i - 1]: print('match') is_valid = True else: print('mis-match') is_valid = False break return is_valid more_input = True while more_input: print('Please choose') print(' a: Add a transaction value') print(' p: Print the blockchain blocks') print(' m: Manipulate the blockchain') print(' v: Validate the blockchain') print(' q: Quit') usr_choice = get_user_choice() if usr_choice == 'A': tx_amt = get_tx_amt() add_tx(tx_amt, get_last_blockchain_val()) elif usr_choice == 'P': print_out_blockchain(blockchain) elif usr_choice == 'M': if len(blockchain) > 0: blockchain[0] = [2] elif usr_choice == 'V': validate_blockchain(blockchain) elif usr_choice == 'Q': more_input = False else: print(f"Not a valid choice: '{usr_choice}'") if not validate_blockchain(blockchain): print(f'Not a valid blockchain! Exiting...') break else: print('No more input') print('Done!')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ .. py:currentmodule:: leepstools.file.angle .. moduleauthor:: Hendrix Demers <[email protected]> Read angle distribution result from LEEPS simulation. """ ############################################################################### # Copyright 2017 Hendrix Demers # # 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. ############################################################################### # Standard library modules. # Third party modules. # Local modules. # Project modules. # Globals and constants variables. class Angle(): def __init__(self): self.theta_deg = [] self.probability_1_sr = [] self.stu_1_sr = [] def read(self, file_path): lines = [] with open(file_path) as input_file: lines = input_file.readlines() for line in lines: line = line .strip() if not line.startswith('#'): items = line.split() try: theta_deg = float(items[0]) probability_1_sr = float(items[1]) stu_1_sr = float(items[2]) self.theta_deg.append(theta_deg) self.probability_1_sr.append(probability_1_sr) self.stu_1_sr.append(stu_1_sr) except IndexError: pass
""" .. py:currentmodule:: leepstools.file.angle .. moduleauthor:: Hendrix Demers <[email protected]> Read angle distribution result from LEEPS simulation. """ class Angle: def __init__(self): self.theta_deg = [] self.probability_1_sr = [] self.stu_1_sr = [] def read(self, file_path): lines = [] with open(file_path) as input_file: lines = input_file.readlines() for line in lines: line = line.strip() if not line.startswith('#'): items = line.split() try: theta_deg = float(items[0]) probability_1_sr = float(items[1]) stu_1_sr = float(items[2]) self.theta_deg.append(theta_deg) self.probability_1_sr.append(probability_1_sr) self.stu_1_sr.append(stu_1_sr) except IndexError: pass
# coding=utf-8 class AutumnInvokeException(Exception): pass class InvocationTargetException(Exception): pass if __name__ == '__main__': pass
class Autumninvokeexception(Exception): pass class Invocationtargetexception(Exception): pass if __name__ == '__main__': pass
class Solution: def fourSum(self, nums: List[int], target: int) -> List[List[int]]: ''' T: O(n log n + n^3) S: O(1) ''' n = len(nums) if n < 4: return [] nums.sort() results = set() for x in range(n): for y in range(x+1, n): i, j = y + 1, n-1 while i < j: summ = nums[x] + nums[y] + nums[i] + nums[j] if summ == target: results.add((nums[x],nums[y], nums[i], nums[j])) i += 1 elif summ < target: i += 1 else: j -= 1 return results
class Solution: def four_sum(self, nums: List[int], target: int) -> List[List[int]]: """ T: O(n log n + n^3) S: O(1) """ n = len(nums) if n < 4: return [] nums.sort() results = set() for x in range(n): for y in range(x + 1, n): (i, j) = (y + 1, n - 1) while i < j: summ = nums[x] + nums[y] + nums[i] + nums[j] if summ == target: results.add((nums[x], nums[y], nums[i], nums[j])) i += 1 elif summ < target: i += 1 else: j -= 1 return results
class event_meta(object): def __init__(self): super(event_meta, self).__init__() def n_views(self): return max(self._n_views, 1) def refresh(self, meta_vec): self._n_views = len(meta_vec) self._x_min = [] self._y_min = [] self._x_max = [] self._y_max = [] self._y_n_pixels = [] self._x_n_pixels = [] x_ind = 0 y_ind = 1 for meta in meta_vec: self._x_min.append(meta.origin(0)) self._y_min.append(meta.origin(1)) self._x_max.append(meta.image_size(0) + meta.origin(0)) self._y_max.append(meta.image_size(1) + meta.origin(1)) self._x_n_pixels.append(meta.number_of_voxels(0)) self._y_n_pixels.append(meta.number_of_voxels(1)) for i in range(self._n_views): if self._x_min[i] == self._x_max[i]: self._x_max[i] = self._x_min[i] + self._x_n_pixels[i] if self._y_min[i] == self._y_max[i]: self._y_max[i] = self._y_min[i] + self._y_n_pixels[i] def cols(self, plane): return self._x_n_pixels[plane] def width(self, plane): return self._x_max[plane] - self._x_min[plane] def comp_x(self, plane): return self.width(plane) / self.cols(plane) def rows(self, plane): return self._y_n_pixels[plane] def height(self, plane): return self._y_max[plane] - self._y_min[plane] def comp_y(self, plane): return self.height(plane) / self.rows(plane) def wire_to_col(self, wire, plane): return self.cols(plane) * (1.0*(wire - self.min_x(plane)) / self.width(plane)) def time_to_row(self, time, plane): return self.rows(plane) * (1.0*(time - self.min_y(plane)) / self.height(plane)) def min_y(self, plane): return self._y_min[plane] def max_y(self, plane): return self._y_max[plane] def min_x(self, plane): return self._x_min[plane] def max_x(self, plane): return self._x_max[plane] def range(self, plane): if plane >= 0 and plane < self._n_views: return ((self._x_min[plane], self._x_min[plane] ), (self._x_min[plane], self._x_min[plane])) else: print("ERROR: plane {} not available.".format(plane)) return ((-1, 1), (-1, 1)) class event_meta3D(object): def __init__(self): super(event_meta3D, self).__init__() def refresh(self, meta): x_ind = 0 y_ind = 1 z_ind = 2 self._x_min = meta.origin(x_ind) self._y_min = meta.origin(y_ind) self._z_min = meta.origin(z_ind) self._x_max = meta.image_size(x_ind) + meta.origin(x_ind) self._y_max = meta.image_size(y_ind) + meta.origin(y_ind) self._z_max = meta.image_size(z_ind) + meta.origin(z_ind) self._y_n_pixels = meta.number_of_voxels(x_ind) self._x_n_pixels = meta.number_of_voxels(y_ind) self._z_n_pixels = meta.number_of_voxels(z_ind) def size_voxel_x(self): return (self._x_max - self._x_min) / self._x_n_pixels def size_voxel_y(self): return (self._y_max - self._y_min) / self._y_n_pixels def size_voxel_z(self): return (self._z_max - self._z_min) / self._z_n_pixels def n_voxels_x(self): return self._x_n_pixels def n_voxels_y(self): return self._y_n_pixels def n_voxels_z(self): return self._z_n_pixels def dim_x(self): return self._x_max - self._x_min def dim_y(self): return self._y_max - self._y_min def dim_z(self): return self._z_max - self._z_min def width(self): return self.dim_x() def height(self): return self.dim_y() def length(self): return self.dim_z() def min_y(self): return self._y_min def max_y(self): return self._y_max def min_x(self): return self._x_min def max_x(self): return self._x_max def min_z(self): return self._z_min def max_z(self): return self._z_max
class Event_Meta(object): def __init__(self): super(event_meta, self).__init__() def n_views(self): return max(self._n_views, 1) def refresh(self, meta_vec): self._n_views = len(meta_vec) self._x_min = [] self._y_min = [] self._x_max = [] self._y_max = [] self._y_n_pixels = [] self._x_n_pixels = [] x_ind = 0 y_ind = 1 for meta in meta_vec: self._x_min.append(meta.origin(0)) self._y_min.append(meta.origin(1)) self._x_max.append(meta.image_size(0) + meta.origin(0)) self._y_max.append(meta.image_size(1) + meta.origin(1)) self._x_n_pixels.append(meta.number_of_voxels(0)) self._y_n_pixels.append(meta.number_of_voxels(1)) for i in range(self._n_views): if self._x_min[i] == self._x_max[i]: self._x_max[i] = self._x_min[i] + self._x_n_pixels[i] if self._y_min[i] == self._y_max[i]: self._y_max[i] = self._y_min[i] + self._y_n_pixels[i] def cols(self, plane): return self._x_n_pixels[plane] def width(self, plane): return self._x_max[plane] - self._x_min[plane] def comp_x(self, plane): return self.width(plane) / self.cols(plane) def rows(self, plane): return self._y_n_pixels[plane] def height(self, plane): return self._y_max[plane] - self._y_min[plane] def comp_y(self, plane): return self.height(plane) / self.rows(plane) def wire_to_col(self, wire, plane): return self.cols(plane) * (1.0 * (wire - self.min_x(plane)) / self.width(plane)) def time_to_row(self, time, plane): return self.rows(plane) * (1.0 * (time - self.min_y(plane)) / self.height(plane)) def min_y(self, plane): return self._y_min[plane] def max_y(self, plane): return self._y_max[plane] def min_x(self, plane): return self._x_min[plane] def max_x(self, plane): return self._x_max[plane] def range(self, plane): if plane >= 0 and plane < self._n_views: return ((self._x_min[plane], self._x_min[plane]), (self._x_min[plane], self._x_min[plane])) else: print('ERROR: plane {} not available.'.format(plane)) return ((-1, 1), (-1, 1)) class Event_Meta3D(object): def __init__(self): super(event_meta3D, self).__init__() def refresh(self, meta): x_ind = 0 y_ind = 1 z_ind = 2 self._x_min = meta.origin(x_ind) self._y_min = meta.origin(y_ind) self._z_min = meta.origin(z_ind) self._x_max = meta.image_size(x_ind) + meta.origin(x_ind) self._y_max = meta.image_size(y_ind) + meta.origin(y_ind) self._z_max = meta.image_size(z_ind) + meta.origin(z_ind) self._y_n_pixels = meta.number_of_voxels(x_ind) self._x_n_pixels = meta.number_of_voxels(y_ind) self._z_n_pixels = meta.number_of_voxels(z_ind) def size_voxel_x(self): return (self._x_max - self._x_min) / self._x_n_pixels def size_voxel_y(self): return (self._y_max - self._y_min) / self._y_n_pixels def size_voxel_z(self): return (self._z_max - self._z_min) / self._z_n_pixels def n_voxels_x(self): return self._x_n_pixels def n_voxels_y(self): return self._y_n_pixels def n_voxels_z(self): return self._z_n_pixels def dim_x(self): return self._x_max - self._x_min def dim_y(self): return self._y_max - self._y_min def dim_z(self): return self._z_max - self._z_min def width(self): return self.dim_x() def height(self): return self.dim_y() def length(self): return self.dim_z() def min_y(self): return self._y_min def max_y(self): return self._y_max def min_x(self): return self._x_min def max_x(self): return self._x_max def min_z(self): return self._z_min def max_z(self): return self._z_max
def sum(a, b): return a + b a = int(input("Enter a number: ")) b = int(input("Enter another number: ")) c = sum(a, b) print("The sum of the two numbers is: ", c)
def sum(a, b): return a + b a = int(input('Enter a number: ')) b = int(input('Enter another number: ')) c = sum(a, b) print('The sum of the two numbers is: ', c)
#testing_loops.py """n = 1 # while the value of n is less than 5, print n. add 1 to n each time # use while loops for infinate loops or for a set number of executions/loops while n<5: print(n) n = n + 1""" """ num = float(input("Enter a postive number:")) while num <= 0: print("That's not a positive number!") num = float(input("Enter a positive number:")) """ """# use for loops to loop over a collection of items for letter in "Python": print(letter)""" # loop over a range of numbers with range / any positive #, n times # range(5) returns range of integers starting with 0 and up to, not including, 5. (0,1,2,3,4) """for n in range(5): print("Python is awesome")""" # you can give range a starting point (great for dice rolls) """for n in range(10,20): print(n * n)""" # you can use it to calculate a split check: amount = float(input("Enter an amount:")) for num_people in range(2,6): print(f"{num_people} people: ${amount / num_people:,.2f} each")
"""n = 1 # while the value of n is less than 5, print n. add 1 to n each time # use while loops for infinate loops or for a set number of executions/loops while n<5: print(n) n = n + 1""" '\nnum = float(input("Enter a postive number:"))\n\nwhile num <= 0:\n print("That\'s not a positive number!")\n\n num = float(input("Enter a positive number:"))\n' '# use for loops to loop over a collection of items\nfor letter in "Python":\n print(letter)' 'for n in range(5):\n print("Python is awesome")' 'for n in range(10,20):\n print(n * n)' amount = float(input('Enter an amount:')) for num_people in range(2, 6): print(f'{num_people} people: ${amount / num_people:,.2f} each')
module_attribute = "hello!" def extension(app): """This extension will work""" return "extension loaded" def assertive_extension(app): """This extension won't work""" assert False
module_attribute = 'hello!' def extension(app): """This extension will work""" return 'extension loaded' def assertive_extension(app): """This extension won't work""" assert False
class Solution: def sortedSquares(self, nums: List[int]) -> List[int]: positives_and_zero = collections.deque() negatives = collections.deque() for x in nums: if x < 0: negatives.appendleft(x * x) else: positives_and_zero.append(x * x) ans = [] while(len(negatives) > 0 and len(positives_and_zero) > 0): if positives_and_zero < negatives: ans.append(positives_and_zero.popleft()) else: ans.append(negatives.popleft()) # one of them is empty so order doesn't matter ans += positives_and_zero + negatives return ans
class Solution: def sorted_squares(self, nums: List[int]) -> List[int]: positives_and_zero = collections.deque() negatives = collections.deque() for x in nums: if x < 0: negatives.appendleft(x * x) else: positives_and_zero.append(x * x) ans = [] while len(negatives) > 0 and len(positives_and_zero) > 0: if positives_and_zero < negatives: ans.append(positives_and_zero.popleft()) else: ans.append(negatives.popleft()) ans += positives_and_zero + negatives return ans
class Solution: # @param A : list of integers # @param B : list of integers # @return an integer def computeGCD(self, x, y): if x > y: small = y else: small = x gcd = 1 for i in range(1, small + 1): if ((x % i == 0) and (y % i == 0)): gcd = i return gcd def maxPoints(self, A, B): N = len(A) if N <= 2: return N max_points = 0 for i in range(N): hash_map = {} horizontal = 0 vertical = 0 overlap = 1 x1, y1 = A[i], B[i] for j in range(i + 1, N): x2, y2 = A[j], B[j] if x1 == x2 and y1 == y2: overlap += 1 elif x1 == x2: vertical += 1 elif y1 == y2: horizontal += 1 else: dy = y2 - y1 dx = x2 - x1 slope = 1.0* dy / dx if slope in hash_map: hash_map[slope] = hash_map[slope] + 1 else: hash_map[slope] = 1 curr_max = max(list(hash_map.values()) + [vertical, horizontal]) curr_max += overlap max_points = max(max_points, curr_max) return max_points
class Solution: def compute_gcd(self, x, y): if x > y: small = y else: small = x gcd = 1 for i in range(1, small + 1): if x % i == 0 and y % i == 0: gcd = i return gcd def max_points(self, A, B): n = len(A) if N <= 2: return N max_points = 0 for i in range(N): hash_map = {} horizontal = 0 vertical = 0 overlap = 1 (x1, y1) = (A[i], B[i]) for j in range(i + 1, N): (x2, y2) = (A[j], B[j]) if x1 == x2 and y1 == y2: overlap += 1 elif x1 == x2: vertical += 1 elif y1 == y2: horizontal += 1 else: dy = y2 - y1 dx = x2 - x1 slope = 1.0 * dy / dx if slope in hash_map: hash_map[slope] = hash_map[slope] + 1 else: hash_map[slope] = 1 curr_max = max(list(hash_map.values()) + [vertical, horizontal]) curr_max += overlap max_points = max(max_points, curr_max) return max_points
TVOC =2300 if TVOC <=2500 and TVOC >=2000: print("Level-5", "Unhealty") print("Hygienic Rating - Situation not acceptable") print("Recommendation - Use only if unavoidable/Intense ventilation necessary") print("Exposure Limit - Hours")
tvoc = 2300 if TVOC <= 2500 and TVOC >= 2000: print('Level-5', 'Unhealty') print('Hygienic Rating - Situation not acceptable') print('Recommendation - Use only if unavoidable/Intense ventilation necessary') print('Exposure Limit - Hours')
for i in range(10): print(i) i = 1 while i < 6: print(i) i += 1
for i in range(10): print(i) i = 1 while i < 6: print(i) i += 1
'''Spiral Matrix''' # spiral :: Int -> [[Int]] def spiral(n): '''The rows of a spiral matrix of order N. ''' def go(rows, cols, x): return [list(range(x, x + cols))] + [ list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols)) ] if 0 < rows else [[]] return go(n, n, 0) # TEST ---------------------------------------------------- # main :: IO () def main(): '''Spiral matrix of order 5, in wiki table markup''' print(wikiTable( spiral(5) )) # FORMATTING ---------------------------------------------- # wikiTable :: [[a]] -> String def wikiTable(rows): '''Wiki markup for a no-frills tabulation of rows.''' return '{| class="wikitable" style="' + ( 'width:12em;height:12em;table-layout:fixed;"|-\n' ) + '\n|-\n'.join([ '| ' + ' || '.join([str(cell) for cell in row]) for row in rows ]) + '\n|}' # MAIN --- if __name__ == '__main__': main()
"""Spiral Matrix""" def spiral(n): """The rows of a spiral matrix of order N. """ def go(rows, cols, x): return [list(range(x, x + cols))] + [list(reversed(x)) for x in zip(*go(cols, rows - 1, x + cols))] if 0 < rows else [[]] return go(n, n, 0) def main(): """Spiral matrix of order 5, in wiki table markup""" print(wiki_table(spiral(5))) def wiki_table(rows): """Wiki markup for a no-frills tabulation of rows.""" return '{| class="wikitable" style="' + 'width:12em;height:12em;table-layout:fixed;"|-\n' + '\n|-\n'.join(['| ' + ' || '.join([str(cell) for cell in row]) for row in rows]) + '\n|}' if __name__ == '__main__': main()
""" This module contains some constants that can be reused ==================================== Copyright SSS_Says_Snek, 2021-present ==================================== """ __version__ = "2.0" __license__ = "MIT" __name__ = "hisock" __copyright__ = "SSS-Says-Snek, 2021-present" __author__ = "SSS-Says-Snek"
""" This module contains some constants that can be reused ==================================== Copyright SSS_Says_Snek, 2021-present ==================================== """ __version__ = '2.0' __license__ = 'MIT' __name__ = 'hisock' __copyright__ = 'SSS-Says-Snek, 2021-present' __author__ = 'SSS-Says-Snek'
class Flight: def __init__(self, origin, destination, month, fare, currency, fare_type, date): self.origin = origin self.destination = destination self.month = month self.fare = fare self.currency = currency self.fare_type = fare_type self.date = date def __str__(self): return self.origin + self.destination + self.month + self.fare + self.currency + self.fare_type + self.date
class Flight: def __init__(self, origin, destination, month, fare, currency, fare_type, date): self.origin = origin self.destination = destination self.month = month self.fare = fare self.currency = currency self.fare_type = fare_type self.date = date def __str__(self): return self.origin + self.destination + self.month + self.fare + self.currency + self.fare_type + self.date
# Users to create/delete users = [ {'name': 'user1', 'password': 'passwd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': False} ] # Roles to create/delete roles = [ {'name': 'SomeRole'} ] # Keypairs to create/delete # Connected to user's list keypairs = [ {'name': 'key1', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7' '/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly' '8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq' '+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkW' 'mTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmk' 'SHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'}, {'name': 'key2', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7' '/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly' '8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq' '+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkW' 'mTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmk' 'SHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'} ] # Images to create/delete images = [ {'name': 'image1', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/ci' 'rros-0.3.3-x86_64-disk.img', 'is_public': True}, {'name': 'image2', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/ci' 'rros-0.3.3-x86_64-disk.img', 'container_format': 'bare', 'disk_format': 'qcow2', 'is_public': False} ] # Flavors to create/delete flavors = [ {'name': 'm1.tiny'} # {'name': 'flavorname1', 'disk': '7', 'ram': '64', 'vcpus': '1'}, # Disabled for now, but in the future we need to generate non-pubic flavors # {'name': 'flavorname3', 'disk': '10', 'ram': '32', 'vcpus': '1', # 'is_public': False}, # {'name': 'flavorname2', 'disk': '5', 'ram': '48', 'vcpus': '2'} ] # Security groups to create/delete security_groups = [{'security_groups': [ {'name': 'sg11', 'description': 'Blah blah group', 'rules': [{'ip_protocol': 'icmp', 'from_port': '0', 'to_port': '255', 'cidr': '0.0.0.0/0'}, {'ip_protocol': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr': '0.0.0.0/0'}]}, {'name': 'sg12', 'description': 'Blah blah group2'}]}] # Networks to create/delete # Connected to tenants ext_net = {'name': 'shared_net', 'admin_state_up': True, 'shared': True, 'router:external': True} networks = [ {'name': 'mynetwork1', 'admin_state_up': True}, ] # Subnets to create/delete ext_subnet = {'cidr': '172.18.10.0/24', 'ip_version': 4} subnets = [ {'cidr': '10.4.2.0/24', 'ip_version': 4}, ] # VM's to create/delete vms = [ {'name': 'server1', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server2', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server3', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server4', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server5', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server6', 'image': 'image1', 'flavor': 'm1.tiny'} ] routers = [ { 'router': { 'name': 'ext_router', 'external_gateway_info': { 'network_id': 'shared_net'}, 'admin_state_up': True}} ] # VM's snapshots to create/delete snapshots = [ {'server': 'server2', 'image_name': 'asdasd'} ] # Cinder images to create/delete cinder_volumes = [ {'name': 'cinder_volume1', 'size': 1}, {'name': 'cinder_volume2', 'size': 1, 'server_to_attach': 'server2', 'device': '/dev/vdb'} ] # Cinder snapshots to create/delete cinder_snapshots = [ {'display_name': 'snapsh1', 'volume_id': 'cinder_volume1'} ] # Emulate different VM states vm_states = [ {'name': 'server1', 'state': 'error'}, {'name': 'server2', 'state': 'stop'}, {'name': 'server3', 'state': 'suspend'}, {'name': 'server4', 'state': 'pause'}, {'name': 'server5', 'state': 'resize'} ] # Client's versions NOVA_CLIENT_VERSION = '1.1' GLANCE_CLIENT_VERSION = '1' NEUTRON_CLIENT_VERSION = '2.0' CINDER_CLIENT_VERSION = '1'
users = [{'name': 'user1', 'password': 'passwd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': True}, {'name': 'user3', 'password': 'paafdssswd1', 'email': '[email protected]', 'tenant': 'tenant1', 'enabled': False}] roles = [{'name': 'SomeRole'}] keypairs = [{'name': 'key1', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkWmTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmkSHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'}, {'name': 'key2', 'public_key': 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCn4vaa1MvLLIQM9G2i9eo2OWoW66i7/tz+F+sSBxjiscmXMGSUxZN1a0yK4TO2l71/MenfAsHCSgu75vyno62JTOLo+QKG07ly8vx9RF+mp+bP/6g0nhcgndOD30NPLEv3vtZbZRDiYeb3inc/ZmAy8kLoRPXE3sW4v+xq+PB2nqu38DUemKU9WlZ9F5Fbhz7aVFDhBjvFNDw7w5nO7zeAFz2RbajJksQlHP62VmkWmTgu/otEuhM8GcjZIXlfHJtv0utMNfqQsNQ8qzt38OKXn/k2czmZX59DXomwdo3DUSmkSHym3kZtZPSTgT6GIGoWA1+QHlhx5kiMVEN+YRZF vagrant'}] images = [{'name': 'image1', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/cirros-0.3.3-x86_64-disk.img', 'is_public': True}, {'name': 'image2', 'copy_from': 'http://download.cirros-cloud.net/0.3.3/cirros-0.3.3-x86_64-disk.img', 'container_format': 'bare', 'disk_format': 'qcow2', 'is_public': False}] flavors = [{'name': 'm1.tiny'}] security_groups = [{'security_groups': [{'name': 'sg11', 'description': 'Blah blah group', 'rules': [{'ip_protocol': 'icmp', 'from_port': '0', 'to_port': '255', 'cidr': '0.0.0.0/0'}, {'ip_protocol': 'tcp', 'from_port': '80', 'to_port': '80', 'cidr': '0.0.0.0/0'}]}, {'name': 'sg12', 'description': 'Blah blah group2'}]}] ext_net = {'name': 'shared_net', 'admin_state_up': True, 'shared': True, 'router:external': True} networks = [{'name': 'mynetwork1', 'admin_state_up': True}] ext_subnet = {'cidr': '172.18.10.0/24', 'ip_version': 4} subnets = [{'cidr': '10.4.2.0/24', 'ip_version': 4}] vms = [{'name': 'server1', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server2', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server3', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server4', 'image': 'image2', 'flavor': 'm1.tiny'}, {'name': 'server5', 'image': 'image1', 'flavor': 'm1.tiny'}, {'name': 'server6', 'image': 'image1', 'flavor': 'm1.tiny'}] routers = [{'router': {'name': 'ext_router', 'external_gateway_info': {'network_id': 'shared_net'}, 'admin_state_up': True}}] snapshots = [{'server': 'server2', 'image_name': 'asdasd'}] cinder_volumes = [{'name': 'cinder_volume1', 'size': 1}, {'name': 'cinder_volume2', 'size': 1, 'server_to_attach': 'server2', 'device': '/dev/vdb'}] cinder_snapshots = [{'display_name': 'snapsh1', 'volume_id': 'cinder_volume1'}] vm_states = [{'name': 'server1', 'state': 'error'}, {'name': 'server2', 'state': 'stop'}, {'name': 'server3', 'state': 'suspend'}, {'name': 'server4', 'state': 'pause'}, {'name': 'server5', 'state': 'resize'}] nova_client_version = '1.1' glance_client_version = '1' neutron_client_version = '2.0' cinder_client_version = '1'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Mar 15 16:13:20 2018 @author: efrem """ class Coordinate(object): def __init__(self,x,y): self.x = x self.y = y def getX(self): # Getter method for a Coordinate object's x coordinate. # Getter methods are better practice than just accessing an attribute directly return self.x def getY(self): # Getter method for a Coordinate object's y coordinate return self.y def __str__(self): return '<' + str(self.getX()) + ',' + str(self.getY()) + '>' def __eq__(self, other): return self.x == other.x and self.y == other.y def __repr__(self): return "Coordinate(%d,%d)" % (self.x, self.y)
""" Created on Thu Mar 15 16:13:20 2018 @author: efrem """ class Coordinate(object): def __init__(self, x, y): self.x = x self.y = y def get_x(self): return self.x def get_y(self): return self.y def __str__(self): return '<' + str(self.getX()) + ',' + str(self.getY()) + '>' def __eq__(self, other): return self.x == other.x and self.y == other.y def __repr__(self): return 'Coordinate(%d,%d)' % (self.x, self.y)
# -*- coding: utf-8 -*- __title__ = 'ci_release_publisher' __description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases' __version__ = '0.2.0' __url__ = 'https://github.com/nurupo/ci-release-publisher' __author__ = 'Maxim Biro' __author_email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2018-2020 Maxim Biro'
__title__ = 'ci_release_publisher' __description__ = 'A script for publishing Travis-CI build artifacts on GitHub Releases' __version__ = '0.2.0' __url__ = 'https://github.com/nurupo/ci-release-publisher' __author__ = 'Maxim Biro' __author_email__ = '[email protected]' __license__ = 'MIT' __copyright__ = 'Copyright 2018-2020 Maxim Biro'
n=1260 count=0 list=[500,100,50,10] for coin in list: count += n//coin n %= coin print(count)
n = 1260 count = 0 list = [500, 100, 50, 10] for coin in list: count += n // coin n %= coin print(count)
# MEDIUM # inorder traversal using iterative # Time O(N) Space O(H) class Solution: def kthSmallest(self, root: TreeNode, k: int) -> int: return self.iterative(root,k) self.index= 1 self.result = -1 self.inOrder(root,k) return self.result def iterative(self,root,k): stack = [] i = 1 while root or stack: while root: stack.append(root) root = root.left curr = stack.pop() # print(curr.val) if i == k: return curr.val i += 1 if curr.right: root = curr.right def inOrder(self,root,k): if not root: return self.inOrder(root.left,k) # print(root.val,self.index) if self.index == k: self.result = root.val self.index += 1 self.inOrder(root.right,k)
class Solution: def kth_smallest(self, root: TreeNode, k: int) -> int: return self.iterative(root, k) self.index = 1 self.result = -1 self.inOrder(root, k) return self.result def iterative(self, root, k): stack = [] i = 1 while root or stack: while root: stack.append(root) root = root.left curr = stack.pop() if i == k: return curr.val i += 1 if curr.right: root = curr.right def in_order(self, root, k): if not root: return self.inOrder(root.left, k) if self.index == k: self.result = root.val self.index += 1 self.inOrder(root.right, k)
def solution(N): A, B = 0, 0 mult = 1 while N > 0: q, r = divmod(N, 10) if r == 5: A, B = A + mult * 2, B + mult * 3 elif r == 0: A, B = A + mult, B + mult * 9 q -= 1 else: A, B = A + mult, B + mult * (r - 1) mult *= 10 N = q print(A+B) return str(A) + ' ' + str(B) def main(): T = int(input()) for t in range(T): N = int(input()) answer = solution(N) print('Case #' + str(t+1) + ': ' + answer) if __name__ == '__main__': main()
def solution(N): (a, b) = (0, 0) mult = 1 while N > 0: (q, r) = divmod(N, 10) if r == 5: (a, b) = (A + mult * 2, B + mult * 3) elif r == 0: (a, b) = (A + mult, B + mult * 9) q -= 1 else: (a, b) = (A + mult, B + mult * (r - 1)) mult *= 10 n = q print(A + B) return str(A) + ' ' + str(B) def main(): t = int(input()) for t in range(T): n = int(input()) answer = solution(N) print('Case #' + str(t + 1) + ': ' + answer) if __name__ == '__main__': main()
def sum_digits(n): s=0 while n: s += n % 10 n /= 10 return s def factorial(n): if n == 0: return 1 else: return n*factorial(n-1) def sum_factorial_digits(n): return sum_digits(factorial(n)) def main(): print(sum_factorial_digits(10)) print(sum_factorial_digits(100)) print(sum_factorial_digits(500)) if __name__ == "__main__": #test() main()
def sum_digits(n): s = 0 while n: s += n % 10 n /= 10 return s def factorial(n): if n == 0: return 1 else: return n * factorial(n - 1) def sum_factorial_digits(n): return sum_digits(factorial(n)) def main(): print(sum_factorial_digits(10)) print(sum_factorial_digits(100)) print(sum_factorial_digits(500)) if __name__ == '__main__': main()
username = input("Please enter your name: ") lastLength = 0 while True: f = open('msgbuffer.txt', 'r+') messages = f.readlines() mailboxSize = len(messages) if mailboxSize > 0 and mailboxSize > lastLength: print( messages[-1] ) lastLength = mailboxSize message = input("|") if message == 'read': print( messages[-1] ) f.write( '%s:%s' % (username, message) ) f.write('\n') f.close()
username = input('Please enter your name: ') last_length = 0 while True: f = open('msgbuffer.txt', 'r+') messages = f.readlines() mailbox_size = len(messages) if mailboxSize > 0 and mailboxSize > lastLength: print(messages[-1]) last_length = mailboxSize message = input('|') if message == 'read': print(messages[-1]) f.write('%s:%s' % (username, message)) f.write('\n') f.close()
#! /usr/bin/env python # _*_ coding:utf-8 _*_ class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def isSameTree(self, p, q): if not p and not q: return True elif not p or not q: return False elif p.val != q.val: return False if self.isSameTree(p.left, q.left): return self.isSameTree(p.right, q.right) else: return False def gen_tree(nums): for i, n in enumerate(nums): node = TreeNode(n) nums[i] = node root = nums[0] if __name__ == '__main__': so = Solution() def test(): pass test()
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def is_same_tree(self, p, q): if not p and (not q): return True elif not p or not q: return False elif p.val != q.val: return False if self.isSameTree(p.left, q.left): return self.isSameTree(p.right, q.right) else: return False def gen_tree(nums): for (i, n) in enumerate(nums): node = tree_node(n) nums[i] = node root = nums[0] if __name__ == '__main__': so = solution() def test(): pass test()
class disjoint_set: def __init__(self,vertex): self.parent = self self.rank = 0 self.vertex = vertex def find(self): if self.parent != self: self.parent = self.parent.find() return self.parent def joinSets(self,otherTree): root = self.find() otherTreeRoot = otherTree.find() if root == otherTreeRoot: return if root.rank < otherTreeRoot.rank: root.parent = otherTreeRoot elif otherTreeRoot.rank < root.rank: otherTreeRoot.parent = root else: otherTreeRoot.parent = root root.rank += 1
class Disjoint_Set: def __init__(self, vertex): self.parent = self self.rank = 0 self.vertex = vertex def find(self): if self.parent != self: self.parent = self.parent.find() return self.parent def join_sets(self, otherTree): root = self.find() other_tree_root = otherTree.find() if root == otherTreeRoot: return if root.rank < otherTreeRoot.rank: root.parent = otherTreeRoot elif otherTreeRoot.rank < root.rank: otherTreeRoot.parent = root else: otherTreeRoot.parent = root root.rank += 1
def get_test_data(): return { "contact": { "name": "Paul Kempa", "company": "Baltimore Steel Factory" }, "invoice": { "items": [ { "quantity": 12, "description": "Item description No.0", "unitprice": 12000.3, "linetotal": 20 }, { "quantity": 1290, "description": "Item description No.0", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.1", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.2", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.3", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.4", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.5", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.6", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.7", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.8", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.9", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.10", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.11", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.12", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.13", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.14", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.15", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.16", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.17", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.18", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.19", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.20", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.21", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.22", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.23", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.24", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.25", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.26", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.27", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.28", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.29", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.30", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.31", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.32", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.33", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.34", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.35", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.36", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.37", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.38", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.39", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.40", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.41", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.42", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.43", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.44", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.45", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.46", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.47", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.48", "unitprice": 12.3, "linetotal": 20000 }, { "quantity": 1290, "description": "Item description No.49", "unitprice": 12.3, "linetotal": 20000 } ], "total": 50000000.01 } }
def get_test_data(): return {'contact': {'name': 'Paul Kempa', 'company': 'Baltimore Steel Factory'}, 'invoice': {'items': [{'quantity': 12, 'description': 'Item description No.0', 'unitprice': 12000.3, 'linetotal': 20}, {'quantity': 1290, 'description': 'Item description No.0', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.1', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.2', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.3', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.4', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.5', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.6', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.7', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.8', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.9', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.10', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.11', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.12', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.13', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.14', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.15', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.16', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.17', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.18', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.19', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.20', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.21', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.22', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.23', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.24', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.25', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.26', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.27', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.28', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.29', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.30', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.31', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.32', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.33', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.34', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.35', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.36', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.37', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.38', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.39', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.40', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.41', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.42', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.43', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.44', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.45', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.46', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.47', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.48', 'unitprice': 12.3, 'linetotal': 20000}, {'quantity': 1290, 'description': 'Item description No.49', 'unitprice': 12.3, 'linetotal': 20000}], 'total': 50000000.01}}
class Node: def __init__(self, data, next=None): self.data = data self.next = next class LinkedList: def __init__(self, *args, **kwargs): self.head = Node(None) def appende(self, data): node = Node(data) node.next = self.head self.head = node # Print linked list def print_my_list(self): node = self.head while node.next is not None: print(node.data, end=" ") node = node.next # count number of node in linked list def countNodes(self): count = 0 node = self.head while node.next is not None: count += 1 node = node.next return count def Kth(self, k): # Count nodes in linked list n = self.countNodes() # check if k is valid if n < k: return if (2 * k - 1) == n: return x = self.head x_prev = Node(None) for i in range(k - 1): x_prev = x x = x.next y = self.head y_prev = Node(None) for i in range(n - k): y_prev = y y = y.next if x_prev is not None: x_prev.next = y # Same thing applies to y_prev if y_prev is not None: y_prev.next = x temp = x.next x.next = y.next y.next = temp # Change head pointers when k is 1 or n if k == 1: self.head = y if k == n: self.head = x if __name__ == '__main__': My_List = LinkedList() for i in range(8, 0, -1): My_List.appende(i) My_List.appende(7) My_List.appende(6) My_List.appende(5) My_List.appende(4) My_List.appende(3) My_List.appende(2) My_List.appende(1) My_List.print_my_list() for i in range(1, 9): My_List.Kth(i) print("Modified List for k = ", i) My_List.print_my_list() print("\n")
class Node: def __init__(self, data, next=None): self.data = data self.next = next class Linkedlist: def __init__(self, *args, **kwargs): self.head = node(None) def appende(self, data): node = node(data) node.next = self.head self.head = node def print_my_list(self): node = self.head while node.next is not None: print(node.data, end=' ') node = node.next def count_nodes(self): count = 0 node = self.head while node.next is not None: count += 1 node = node.next return count def kth(self, k): n = self.countNodes() if n < k: return if 2 * k - 1 == n: return x = self.head x_prev = node(None) for i in range(k - 1): x_prev = x x = x.next y = self.head y_prev = node(None) for i in range(n - k): y_prev = y y = y.next if x_prev is not None: x_prev.next = y if y_prev is not None: y_prev.next = x temp = x.next x.next = y.next y.next = temp if k == 1: self.head = y if k == n: self.head = x if __name__ == '__main__': my__list = linked_list() for i in range(8, 0, -1): My_List.appende(i) My_List.appende(7) My_List.appende(6) My_List.appende(5) My_List.appende(4) My_List.appende(3) My_List.appende(2) My_List.appende(1) My_List.print_my_list() for i in range(1, 9): My_List.Kth(i) print('Modified List for k = ', i) My_List.print_my_list() print('\n')
# # PySNMP MIB module Wellfleet-NPK-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NPK-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:34:31 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") MibIdentifier, Gauge32, Bits, Counter32, NotificationType, IpAddress, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Counter64, TimeTicks, ModuleIdentity, Integer32, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Gauge32", "Bits", "Counter32", "NotificationType", "IpAddress", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Counter64", "TimeTicks", "ModuleIdentity", "Integer32", "ObjectIdentity") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") wfGameGroup, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfGameGroup") wfNpkBase = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8)) wfNpkBaseCreate = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseCreate.setStatus('mandatory') wfNpkBaseHash = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 2), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseHash.setStatus('mandatory') wfNpkBaseLastMod = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 3), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNpkBaseLastMod.setStatus('mandatory') mibBuilder.exportSymbols("Wellfleet-NPK-MIB", wfNpkBase=wfNpkBase, wfNpkBaseHash=wfNpkBaseHash, wfNpkBaseLastMod=wfNpkBaseLastMod, wfNpkBaseCreate=wfNpkBaseCreate)
(octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, constraints_intersection, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueSizeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (mib_identifier, gauge32, bits, counter32, notification_type, ip_address, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, counter64, time_ticks, module_identity, integer32, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'Gauge32', 'Bits', 'Counter32', 'NotificationType', 'IpAddress', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'Counter64', 'TimeTicks', 'ModuleIdentity', 'Integer32', 'ObjectIdentity') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (wf_game_group,) = mibBuilder.importSymbols('Wellfleet-COMMON-MIB', 'wfGameGroup') wf_npk_base = mib_identifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8)) wf_npk_base_create = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('created', 1), ('deleted', 2))).clone('created')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNpkBaseCreate.setStatus('mandatory') wf_npk_base_hash = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 2), octet_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNpkBaseHash.setStatus('mandatory') wf_npk_base_last_mod = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 5, 8, 3), display_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNpkBaseLastMod.setStatus('mandatory') mibBuilder.exportSymbols('Wellfleet-NPK-MIB', wfNpkBase=wfNpkBase, wfNpkBaseHash=wfNpkBaseHash, wfNpkBaseLastMod=wfNpkBaseLastMod, wfNpkBaseCreate=wfNpkBaseCreate)
def retrieveDB_data(db, option, title): data_ref = db.collection(option).document(title) docs = data_ref.get() return docs.to_dict() async def initDB(db, objectList, objectDb, firestore): if objectList is None: data = {"create": "create"} objectDb.set(data) objectDb.update({"create": firestore.DELETE_FIELD}) return async def checkChannel(db, firestore, channelId, guildId): channel_fetch = retrieveDB_data(db, option="channel-list", title=str(guildId)) channel_DB_init = db.collection("channel-list").document(str(guildId)) await initDB(db, channel_fetch, channel_DB_init, firestore) try: channelVerify = channel_fetch[f"{channelId}"] except (KeyError, TypeError): return return channelVerify async def checkUser(db, firestore, userId, guildId): user_projects = retrieveDB_data(db, option="user-projects", title=str(guildId)) user_projectsDB = db.collection("user-projects").document(str(guildId)) await initDB(db, user_projects, user_projectsDB, firestore) try: userVerify = user_projects[str(userId)] except (KeyError, TypeError): return return userVerify async def check_existingProject(db, mention, project, guildId): user_projects = retrieveDB_data(db, option="user-projects", title=str(guildId)) userProject = user_projects[str(mention)] if str(userProject) != str(project): return userProject return
def retrieve_db_data(db, option, title): data_ref = db.collection(option).document(title) docs = data_ref.get() return docs.to_dict() async def initDB(db, objectList, objectDb, firestore): if objectList is None: data = {'create': 'create'} objectDb.set(data) objectDb.update({'create': firestore.DELETE_FIELD}) return async def checkChannel(db, firestore, channelId, guildId): channel_fetch = retrieve_db_data(db, option='channel-list', title=str(guildId)) channel_db_init = db.collection('channel-list').document(str(guildId)) await init_db(db, channel_fetch, channel_DB_init, firestore) try: channel_verify = channel_fetch[f'{channelId}'] except (KeyError, TypeError): return return channelVerify async def checkUser(db, firestore, userId, guildId): user_projects = retrieve_db_data(db, option='user-projects', title=str(guildId)) user_projects_db = db.collection('user-projects').document(str(guildId)) await init_db(db, user_projects, user_projectsDB, firestore) try: user_verify = user_projects[str(userId)] except (KeyError, TypeError): return return userVerify async def check_existingProject(db, mention, project, guildId): user_projects = retrieve_db_data(db, option='user-projects', title=str(guildId)) user_project = user_projects[str(mention)] if str(userProject) != str(project): return userProject return
class Board: def __init__(self, data): self.rows = data self.marked = [[0 for _ in range(0, 5)] for _ in range(0, 5)] def __str__(self): """String representation""" res = "BOARD:" for r in self.rows: res = res + "\n" + str(r) res = res + "\nMARKED:" for r in self.marked: res = res + "\n" + str(r) return res def mark_number(self, number:int) -> None : """ Marks a number in the bingo board. :param number: Number to be looked up in the board's numbers. :return: None """ for i, row in enumerate(self.rows): for j, cell in enumerate(row): if cell == number: self.marked[i][j] = 1 def check_winning_conditions(self) -> bool: """ Checks whether a winning condition (5x "1" in a row or a columN) is fulfilled in the board. :return: Boolean, signifying win/loss """ for row in self.marked: # sum rows if sum(row) == 5: return True for i in range(0, 5): # sum columns if sum([x[i] for x in self.marked]) == 5: return True return False def calculate_score(self) -> int: """ Calculates sum of unmarked cells. :return: score """ score = 0 for i, row in enumerate(self.marked): for j, cell in enumerate(row): if cell == 0: # sum unmarked score += self.rows[i][j] return score
class Board: def __init__(self, data): self.rows = data self.marked = [[0 for _ in range(0, 5)] for _ in range(0, 5)] def __str__(self): """String representation""" res = 'BOARD:' for r in self.rows: res = res + '\n' + str(r) res = res + '\nMARKED:' for r in self.marked: res = res + '\n' + str(r) return res def mark_number(self, number: int) -> None: """ Marks a number in the bingo board. :param number: Number to be looked up in the board's numbers. :return: None """ for (i, row) in enumerate(self.rows): for (j, cell) in enumerate(row): if cell == number: self.marked[i][j] = 1 def check_winning_conditions(self) -> bool: """ Checks whether a winning condition (5x "1" in a row or a columN) is fulfilled in the board. :return: Boolean, signifying win/loss """ for row in self.marked: if sum(row) == 5: return True for i in range(0, 5): if sum([x[i] for x in self.marked]) == 5: return True return False def calculate_score(self) -> int: """ Calculates sum of unmarked cells. :return: score """ score = 0 for (i, row) in enumerate(self.marked): for (j, cell) in enumerate(row): if cell == 0: score += self.rows[i][j] return score
BLACK = -999 DEFAULT = 0 NORMAL = 1 PRIVATE = 10 ADMIN = 21 OWNER = 22 WHITE = 51 SUPERUSER = 999 SU = SUPERUSER
black = -999 default = 0 normal = 1 private = 10 admin = 21 owner = 22 white = 51 superuser = 999 su = SUPERUSER
################################################# Cars = [["Lamborghini", 1000000, 2, 40000], ["Ferrari", 1500000, 2.5, 50000], ["BMW", 800000, 1.5, 20000]] ################################################# print("#"*80) print("#" + "Welcome to XYZ Car Dealership".center(78) + "#") print("#"*80 + "\n") while True: print("#"*80) print("#" + "What Would You Like To Do Today?".center(78) + "#") print("#" + "A) Buy A Car ".center(78) + "#") print("#" + "B) Rent A Car".center(78) + "#") print("#"*80 + "\n") mode = input("Choose Option (A/B):\t").lower() while mode not in "ab" and mode != "ab": mode = input("Choose Option (A/B):\t").lower() if mode == "a": print("#"*80) print("#" + "Choose A Car".center(78) + "#") print("#" + "1) Lamborghini ".center(78) + "#") print("#" + "2) Ferrari ".center(78) + "#") print("#" + "3) BMW ".center(78) + "#") print("#" + "4) Input Your own Car".center(78) + "#") print("#"*80) op = int(input("Choose Option: ")) while op != 1 and op != 2 and op != 3 and op != 4: op = int(input("Choose Option: ")) if op == 4: buyPrice = int(input("Enter Buy Price of Car: ")) maintainanceCostPercentage = int(input("Enter Annual Maintainance Percentage of Car: ")) years = int(input("How many Years: ")) else: i = op-1 print("Checking for " + Cars[i][0] + "...") years = int(input("How many Years: ")) buyPrice = Cars[i][1] maintainanceCostPercentage = Cars[i][2] Price = buyPrice + buyPrice * (years-1) * maintainanceCostPercentage / 100 p = "Buy For $" + str(Price) print("\n" + "#"*80) print("#" + "Receipt".center(78) + "#") print("#" + "-------".center(78) + "#") print("#" + "".center(78) + "#") print("#" + p.center(78) + "#") print("#"*80) elif mode == "b": print("#"*80) print("#" + "Choose A Car".center(78) + "#") print("#" + "1) Lamborghini ".center(78) + "#") print("#" + "2) Ferrari ".center(78) + "#") print("#" + "3) BMW ".center(78) + "#") print("#" + "4) Input Your own Car".center(78) + "#") print("#"*80) op = int(input("Choose Option: ")) while op != 1 and op != 2 and op != 3 and op != 4: op = int(input("Choose Option: ")) if op == 4: rent = int(input("Enter monthly Rental Price of Car: ")) months = int(input("How many Months: ")) else: i = op-1 months = int(input("How many Months: ")) rent = Cars[i][3] Price = months * rent p = "\n\nPrice to rent for " + str(months) + " months is $" + str(Price) print("\n" + "#"*80) print("#" + "Receipt".center(78) + "#") print("#" + "-------".center(78) + "#") print("#" + "".center(78) + "#") print("#" + p.center(78) + "#") print("#"*80) if input("Would You like to Exit? (y/n) ").lower() == "y": break print("#"*80) print("#" + "Thank You!".center(78) + "#") print("#"*80)
cars = [['Lamborghini', 1000000, 2, 40000], ['Ferrari', 1500000, 2.5, 50000], ['BMW', 800000, 1.5, 20000]] print('#' * 80) print('#' + 'Welcome to XYZ Car Dealership'.center(78) + '#') print('#' * 80 + '\n') while True: print('#' * 80) print('#' + 'What Would You Like To Do Today?'.center(78) + '#') print('#' + 'A) Buy A Car '.center(78) + '#') print('#' + 'B) Rent A Car'.center(78) + '#') print('#' * 80 + '\n') mode = input('Choose Option (A/B):\t').lower() while mode not in 'ab' and mode != 'ab': mode = input('Choose Option (A/B):\t').lower() if mode == 'a': print('#' * 80) print('#' + 'Choose A Car'.center(78) + '#') print('#' + '1) Lamborghini '.center(78) + '#') print('#' + '2) Ferrari '.center(78) + '#') print('#' + '3) BMW '.center(78) + '#') print('#' + '4) Input Your own Car'.center(78) + '#') print('#' * 80) op = int(input('Choose Option: ')) while op != 1 and op != 2 and (op != 3) and (op != 4): op = int(input('Choose Option: ')) if op == 4: buy_price = int(input('Enter Buy Price of Car: ')) maintainance_cost_percentage = int(input('Enter Annual Maintainance Percentage of Car: ')) years = int(input('How many Years: ')) else: i = op - 1 print('Checking for ' + Cars[i][0] + '...') years = int(input('How many Years: ')) buy_price = Cars[i][1] maintainance_cost_percentage = Cars[i][2] price = buyPrice + buyPrice * (years - 1) * maintainanceCostPercentage / 100 p = 'Buy For $' + str(Price) print('\n' + '#' * 80) print('#' + 'Receipt'.center(78) + '#') print('#' + '-------'.center(78) + '#') print('#' + ''.center(78) + '#') print('#' + p.center(78) + '#') print('#' * 80) elif mode == 'b': print('#' * 80) print('#' + 'Choose A Car'.center(78) + '#') print('#' + '1) Lamborghini '.center(78) + '#') print('#' + '2) Ferrari '.center(78) + '#') print('#' + '3) BMW '.center(78) + '#') print('#' + '4) Input Your own Car'.center(78) + '#') print('#' * 80) op = int(input('Choose Option: ')) while op != 1 and op != 2 and (op != 3) and (op != 4): op = int(input('Choose Option: ')) if op == 4: rent = int(input('Enter monthly Rental Price of Car: ')) months = int(input('How many Months: ')) else: i = op - 1 months = int(input('How many Months: ')) rent = Cars[i][3] price = months * rent p = '\n\nPrice to rent for ' + str(months) + ' months is $' + str(Price) print('\n' + '#' * 80) print('#' + 'Receipt'.center(78) + '#') print('#' + '-------'.center(78) + '#') print('#' + ''.center(78) + '#') print('#' + p.center(78) + '#') print('#' * 80) if input('Would You like to Exit? (y/n) ').lower() == 'y': break print('#' * 80) print('#' + 'Thank You!'.center(78) + '#') print('#' * 80)
n1 = 0 n2 = 0 choice = 4 high_number = n1 while choice != 5: while choice == 4: print('=' * 50) n1 = int(input('Choose a number: ')) n2 = int(input('Choose another number: ')) if n1 > n2: high_number = n1 else: high_number = n2 print('=' * 45) print('What do you want to do with the numbers?') print('[1] to add them up.') print('[2] to multiply them.') print('[3] to find the higher number.') print('[4] to choose new numbers.') print('[5] nothing, quit the program.') choice = int(input('')) if choice == 1: print(f'The sum of the entered values is {n1 + n2}.') choice = 5 elif choice == 2: print(f'The product of the numbers entered is {n1 * n2}') choice = 5 elif choice == 3: print(f'The higher number entered was {high_number}') choice = 5
n1 = 0 n2 = 0 choice = 4 high_number = n1 while choice != 5: while choice == 4: print('=' * 50) n1 = int(input('Choose a number: ')) n2 = int(input('Choose another number: ')) if n1 > n2: high_number = n1 else: high_number = n2 print('=' * 45) print('What do you want to do with the numbers?') print('[1] to add them up.') print('[2] to multiply them.') print('[3] to find the higher number.') print('[4] to choose new numbers.') print('[5] nothing, quit the program.') choice = int(input('')) if choice == 1: print(f'The sum of the entered values is {n1 + n2}.') choice = 5 elif choice == 2: print(f'The product of the numbers entered is {n1 * n2}') choice = 5 elif choice == 3: print(f'The higher number entered was {high_number}') choice = 5
white = { "Flour": "100", "Water": "65", "Oil": "4", "Salt": "2", "Yeast": "1.5" }
white = {'Flour': '100', 'Water': '65', 'Oil': '4', 'Salt': '2', 'Yeast': '1.5'}
class Row: def __init__(self, title=None, columns=None, properties=None): self.title = title self.columns = columns or [] self.properties = properties or [] def __str__(self): return str(self.title) def __len__(self): return len(self.title or '') def __iter__(self): yield from self.columns def add_cell(self, cell): self.columns.append(cell) def add_property(self, property): self.properties.append(property)
class Row: def __init__(self, title=None, columns=None, properties=None): self.title = title self.columns = columns or [] self.properties = properties or [] def __str__(self): return str(self.title) def __len__(self): return len(self.title or '') def __iter__(self): yield from self.columns def add_cell(self, cell): self.columns.append(cell) def add_property(self, property): self.properties.append(property)
"""6.1.5 Multiple Definition of Product Group ID For each Product Group ID (type /$defs/product_group_id_t) Product Group elements (/product_tree/product_groups[]) it must be tested that the group_id was not already defined within the same document. The relevant path for this test is: /product_tree/product_groups[]/group_id Example 44 which fails the test: "product_tree": { "full_product_names": [ { "product_id": "CSAFPID-9080700", "name": "Product A" }, { "product_id": "CSAFPID-9080701", "name": "Product B" }, { "product_id": "CSAFPID-9080702", "name": "Product C" } ], "product_groups": [ { "group_id": "CSAFGID-1020300", "product_ids": [ "CSAFPID-9080700", "CSAFPID-9080701" ] }, { "group_id": "CSAFGID-1020300", "product_ids": [ "CSAFPID-9080700", "CSAFPID-9080702" ] } ] } CSAFGID-1020300 was defined twice. """ ID = (6, 1, 5) TOPIC = 'Multiple Definition of Product Group ID' CONDITION_PATH = '/product_tree/product_groups[]/group_id' CONDITION_JMES_PATH = CONDITION_PATH.lstrip('/').replace('/', '.') PATHS = (CONDITION_PATH,)
"""6.1.5 Multiple Definition of Product Group ID For each Product Group ID (type /$defs/product_group_id_t) Product Group elements (/product_tree/product_groups[]) it must be tested that the group_id was not already defined within the same document. The relevant path for this test is: /product_tree/product_groups[]/group_id Example 44 which fails the test: "product_tree": { "full_product_names": [ { "product_id": "CSAFPID-9080700", "name": "Product A" }, { "product_id": "CSAFPID-9080701", "name": "Product B" }, { "product_id": "CSAFPID-9080702", "name": "Product C" } ], "product_groups": [ { "group_id": "CSAFGID-1020300", "product_ids": [ "CSAFPID-9080700", "CSAFPID-9080701" ] }, { "group_id": "CSAFGID-1020300", "product_ids": [ "CSAFPID-9080700", "CSAFPID-9080702" ] } ] } CSAFGID-1020300 was defined twice. """ id = (6, 1, 5) topic = 'Multiple Definition of Product Group ID' condition_path = '/product_tree/product_groups[]/group_id' condition_jmes_path = CONDITION_PATH.lstrip('/').replace('/', '.') paths = (CONDITION_PATH,)
#!/usr/bin/env python3 def readFile(filename): #READFILE reads a file and returns its entire contents # file_contents = READFILE(filename) reads a file and returns its entire # contents in file_contents # # Load File with open(filename) as fid: file_contents = fid.read() #end return file_contents #end
def read_file(filename): with open(filename) as fid: file_contents = fid.read() return file_contents
# values_only # Function which accepts a dictionary of key value pairs and returns a new flat list of only the values. # # Uses the .items() function with a for loop on the dictionary to track both the key and value of the iteration and # returns a new list by appending the values to it. Best used on 1 level-deep key:value pair dictionaries and not # nested data-structures. def values_only(dictionary): lst = [] for v in dictionary.values(): lst.append(v) # for k, v in dictionary.items(): # lst.append(v) return lst ages = { "Peter": 10, "Isabel": 11, "Anna": 9, } print(values_only(ages)) # [10, 11, 9]
def values_only(dictionary): lst = [] for v in dictionary.values(): lst.append(v) return lst ages = {'Peter': 10, 'Isabel': 11, 'Anna': 9} print(values_only(ages))
# Example 1: Showing the Root Mean Squared Error (RMSE) metric. Penalises large residuals # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {"objective":"reg:linear", "max_depth":4} # Perform cross-validation: cv_results cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='rmse', as_pandas=True, seed=123) # Print cv_results print(cv_results) # Extract and print final boosting round metric print((cv_results["test-rmse-mean"]).tail(1)) # Example 2: Showing the Mean Absolute Error (MAE) metric # Create the DMatrix: housing_dmatrix housing_dmatrix = xgb.DMatrix(data=X, label=y) # Create the parameter dictionary: params params = {"objective":"reg:linear", "max_depth":4} # Perform cross-validation: cv_results cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='mae', as_pandas=True, seed=123) # Print cv_results print(cv_results) # Extract and print final boosting round metric print((cv_results["test-mae-mean"]).tail(1))
housing_dmatrix = xgb.DMatrix(data=X, label=y) params = {'objective': 'reg:linear', 'max_depth': 4} cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='rmse', as_pandas=True, seed=123) print(cv_results) print(cv_results['test-rmse-mean'].tail(1)) housing_dmatrix = xgb.DMatrix(data=X, label=y) params = {'objective': 'reg:linear', 'max_depth': 4} cv_results = xgb.cv(dtrain=housing_dmatrix, params=params, nfold=4, num_boost_round=5, metrics='mae', as_pandas=True, seed=123) print(cv_results) print(cv_results['test-mae-mean'].tail(1))
buildcode=""" function Get-ExternalIP(){ $extern_ip_mask = @() while ($response.IPAddress -eq $null){ $response = Resolve-DnsName -Name myip.opendns.com -Server resolver1.opendns.com Start-Sleep -s 1 } $octet1, $octet2, $octet3, $octet4 = $response.IPAddress.Split(".") $extern_ip_mask += $response.IPAddress $extern_ip_mask += [string]$octet1 + "." + [string]$octet2 + "." + [string]$octet3 + ".0" $extern_ip_mask += [string]$octet1 + "." + [string]$octet2 + ".0.0" $extern_ip_mask += [string]$octet1 + ".0.0.0" return $extern_ip_mask } """ callcode=""" $key_combos += ,(Get-ExternalIP) """
buildcode = '\nfunction Get-ExternalIP(){\n\t$extern_ip_mask = @()\n\twhile ($response.IPAddress -eq $null){\n\t\t$response = Resolve-DnsName -Name myip.opendns.com -Server resolver1.opendns.com\n\t\tStart-Sleep -s 1\n\n\t}\n\t$octet1, $octet2, $octet3, $octet4 = $response.IPAddress.Split(".")\n\t$extern_ip_mask += $response.IPAddress\n\t$extern_ip_mask += [string]$octet1 + "." + [string]$octet2 + "." + [string]$octet3 + ".0"\n\t$extern_ip_mask += [string]$octet1 + "." + [string]$octet2 + ".0.0"\n\t$extern_ip_mask += [string]$octet1 + ".0.0.0"\n\treturn $extern_ip_mask\n}\n\t\n' callcode = '\n\t$key_combos += ,(Get-ExternalIP)\n'
""" Constants definition """ ########################################## ## Configurable constants # AREA_WIDTH = 40.0 # width (in meters) of the drawing area CANVAS_WIDTH = 900 # width (in pixels) of the drawing area CANVAS_HEIGHT = 700 # height (in pixels) of the drawing area SCROLLABLE_CANVAS_WIDTH = 4 * CANVAS_WIDTH # scrollable width (in pxls) of the drawing area SCROLLABLE_CANVAS_HEIGHT = 4 * CANVAS_HEIGHT # scrollable height (in pxls) of the drawing area TRACK_WIDTH = 3.0 # track width in meters WAYPOINTS_RADIUS = 5 # radius (in pixels) of the circle corresponding to a waypoint CONE_RADIUS = 0.3 # radius (in meters) of the cones DEFAULT_SPACING_CONES = 3.0 # defaut distance between each cones DEFAULT_SPACING_ORANGE = 0.5 # default distance between orange cones DEFAULT_TURNING_RADIUS = 10.0 # default maximum turning radius (in m) DEFAULT_GRID_SIZE = 1.0 INIT_OFFSET_X = -2.0 # initial offset for the starting pose (along longitudinal axis) INIT_OFFSET_Y = 0.0 # initial offset for the starting pose (along lateral axis) INIT_OFFSET_YAW = 0.0 # initial offset for the starting pose (yaw, in degrees) ########################################## ## Useful constants # ADD_STATE = 'add' # Adding waypoints DELETE_STATE = 'delete' # Removing waypoints
""" Constants definition """ area_width = 40.0 canvas_width = 900 canvas_height = 700 scrollable_canvas_width = 4 * CANVAS_WIDTH scrollable_canvas_height = 4 * CANVAS_HEIGHT track_width = 3.0 waypoints_radius = 5 cone_radius = 0.3 default_spacing_cones = 3.0 default_spacing_orange = 0.5 default_turning_radius = 10.0 default_grid_size = 1.0 init_offset_x = -2.0 init_offset_y = 0.0 init_offset_yaw = 0.0 add_state = 'add' delete_state = 'delete'
# Author: Isabella Doyle # this is the menu def displayMenu(): print("What would you like to do?") print("\t(a) Add new student") print("\t(v) View students") print("\t(q) Quit") # strips any whitespace from the left/right of the string option = input("Please select an option (a/v/q): ").strip() return option def doAdd(students): studentDict = {} studentDict["Name"] = input("Enter student's name: ") studentDict["module"] = readModules() students.append(studentDict) def readModules(): modules = [] moduleName = input("\tEnter the first module name (blank to quit): ").strip() while moduleName != "": module = {} module["Name"] = moduleName module["Grade"] = int(input("\t\tEnter grade: ").strip()) modules.append(module) moduleName = input("\tEnter the next module name (blank to quit): ").strip() return modules def doView(): print(students) # main program students = [] selection = displayMenu() while (selection != ""): if selection == "a": doAdd(students) elif selection == "v": doView() else: print("Invalid input entered.") print(students)
def display_menu(): print('What would you like to do?') print('\t(a) Add new student') print('\t(v) View students') print('\t(q) Quit') option = input('Please select an option (a/v/q): ').strip() return option def do_add(students): student_dict = {} studentDict['Name'] = input("Enter student's name: ") studentDict['module'] = read_modules() students.append(studentDict) def read_modules(): modules = [] module_name = input('\tEnter the first module name (blank to quit): ').strip() while moduleName != '': module = {} module['Name'] = moduleName module['Grade'] = int(input('\t\tEnter grade: ').strip()) modules.append(module) module_name = input('\tEnter the next module name (blank to quit): ').strip() return modules def do_view(): print(students) students = [] selection = display_menu() while selection != '': if selection == 'a': do_add(students) elif selection == 'v': do_view() else: print('Invalid input entered.') print(students)
def my_sum(n): return sum(list(map(int, n))) def resolve(): n, a, b = list(map(int, input().split())) counter = 0 for i in range(n + 1): if a <= my_sum(str(i)) <= b: counter += i print(counter)
def my_sum(n): return sum(list(map(int, n))) def resolve(): (n, a, b) = list(map(int, input().split())) counter = 0 for i in range(n + 1): if a <= my_sum(str(i)) <= b: counter += i print(counter)
""" Billing tests docstring """ # from django.test import TestCase # Create your tests here.
""" Billing tests docstring """
class AllJobsTerminated(Exception): """This class is a special exception that is raised if a job assigned to a thread should be properly terminated """ def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) def signal_cleanup_handler(signum, frame): """A function that cleans up the thread job properly if a specific signal is emitted. :raises: AllJobsTerminated: a job termination exception. """ raise AllJobsTerminated
class Alljobsterminated(Exception): """This class is a special exception that is raised if a job assigned to a thread should be properly terminated """ def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs) def signal_cleanup_handler(signum, frame): """A function that cleans up the thread job properly if a specific signal is emitted. :raises: AllJobsTerminated: a job termination exception. """ raise AllJobsTerminated
""" Mergesort in Python https://en.wikipedia.org/wiki/Merge_sort """ def merge(left, right): """ Take two sorted lists and merge them into sorted list """ left_len = len(left) right_len = len(right) min_len = min(left_len, right_len) merged_lis = [] i, j = 0, 0 while i < min_len and j < min_len: if left[i] < right[j]: merged_lis.append(left[i]) i += 1 else: merged_lis.append(right[j]) j += 1 merged_lis.extend(left[i:]) merged_lis.extend(right[j:]) return merged_lis def mergesort(lis): """ Take a list and return sorted list using mergesort. Doesn't modify original list """ n = len(lis) if n == 1 or n == 0: # If list is empty or single element is present then return list (Base case of recursion) return lis mid = n//2 # Divide list in two parts: left_lis and right_lis at mid point left_lis = lis[:mid] right_lis = lis[mid:] left_lis = mergesort(left_lis) # Recursively sort left_lis by mergesort right_lis = mergesort(right_lis) # Recursively sort right_lis by mergesort mergesorted_lis = merge(left_lis, right_lis) # Merge sorted lists return mergesorted_lis def main(): assert mergesort([4, 1, 2, 3, 9]) == [1, 2, 3, 4, 9] assert mergesort([1]) == [1] assert mergesort([2, 2, 1, -1, 0, 4, 5, 2]) == [-1, 0, 1, 2, 2, 2, 4, 5] if __name__ == '__main__': main()
""" Mergesort in Python https://en.wikipedia.org/wiki/Merge_sort """ def merge(left, right): """ Take two sorted lists and merge them into sorted list """ left_len = len(left) right_len = len(right) min_len = min(left_len, right_len) merged_lis = [] (i, j) = (0, 0) while i < min_len and j < min_len: if left[i] < right[j]: merged_lis.append(left[i]) i += 1 else: merged_lis.append(right[j]) j += 1 merged_lis.extend(left[i:]) merged_lis.extend(right[j:]) return merged_lis def mergesort(lis): """ Take a list and return sorted list using mergesort. Doesn't modify original list """ n = len(lis) if n == 1 or n == 0: return lis mid = n // 2 left_lis = lis[:mid] right_lis = lis[mid:] left_lis = mergesort(left_lis) right_lis = mergesort(right_lis) mergesorted_lis = merge(left_lis, right_lis) return mergesorted_lis def main(): assert mergesort([4, 1, 2, 3, 9]) == [1, 2, 3, 4, 9] assert mergesort([1]) == [1] assert mergesort([2, 2, 1, -1, 0, 4, 5, 2]) == [-1, 0, 1, 2, 2, 2, 4, 5] if __name__ == '__main__': main()
def main(): n=int(input()) a=list(map(int, input().split())) mp=(None,None) d=0 for i in range(0, n-1, 2): if a[i+1] - a[i] > d: mp=(i,i+1) a[mp[0]], a[mp[1]] = a[mp[1]], a[mp[0]] print(sum(a[::2])) if __name__ == '__main__': t=int(input()) for _ in range(t): main()
def main(): n = int(input()) a = list(map(int, input().split())) mp = (None, None) d = 0 for i in range(0, n - 1, 2): if a[i + 1] - a[i] > d: mp = (i, i + 1) (a[mp[0]], a[mp[1]]) = (a[mp[1]], a[mp[0]]) print(sum(a[::2])) if __name__ == '__main__': t = int(input()) for _ in range(t): main()
#!/usr/bin/env python # -*- coding: UTF-8 -*- __all__ = ["CoordinateFrame"] class CoordinateFrame(object): """ CoordinateFrame: Base coordinate frame class. Parameters ---------- frameName : str Name of the coordinate system. coordinateRanges : dict Dictionary with coordinate names as keys and two-element lists containing the lower and upper limits for the coordinate as values. """ def __init__(self, frameName="CoordinateFrame", coordinateRanges={}): self._frameName = frameName self._coordinateRanges = {} @property def frameName(self): return self._frameName @frameName.setter def frameName(self, value): self._frameName = value @frameName.deleter def frameName(self): del self._frameName @property def coordinateRanges(self): return self._coordinateRanges @coordinateRanges.setter def coordinateRanges(self, value): self._coordinateRanges = value @coordinateRanges.deleter def coordinateRanges(self): del self._coordinateRanges def convertToCartesian(self): """ This method should convert the coordinates from this frame to cartesian coordinates. This method is particularly used for plotting purposes. Throws NotImplementedError if not defined. """ raise NotImplementedError("convertToCartesian is not defined.") def surfaceElement(self): """ This method should calculate the surface element for this coordinate frame. This method is used when integrating over the surface of an asteroid. Throws NotImplementedError if not defined. """ raise NotImplementedError("surfaceElement is not defined.")
__all__ = ['CoordinateFrame'] class Coordinateframe(object): """ CoordinateFrame: Base coordinate frame class. Parameters ---------- frameName : str Name of the coordinate system. coordinateRanges : dict Dictionary with coordinate names as keys and two-element lists containing the lower and upper limits for the coordinate as values. """ def __init__(self, frameName='CoordinateFrame', coordinateRanges={}): self._frameName = frameName self._coordinateRanges = {} @property def frame_name(self): return self._frameName @frameName.setter def frame_name(self, value): self._frameName = value @frameName.deleter def frame_name(self): del self._frameName @property def coordinate_ranges(self): return self._coordinateRanges @coordinateRanges.setter def coordinate_ranges(self, value): self._coordinateRanges = value @coordinateRanges.deleter def coordinate_ranges(self): del self._coordinateRanges def convert_to_cartesian(self): """ This method should convert the coordinates from this frame to cartesian coordinates. This method is particularly used for plotting purposes. Throws NotImplementedError if not defined. """ raise not_implemented_error('convertToCartesian is not defined.') def surface_element(self): """ This method should calculate the surface element for this coordinate frame. This method is used when integrating over the surface of an asteroid. Throws NotImplementedError if not defined. """ raise not_implemented_error('surfaceElement is not defined.')
x = int(input('Enter an integer:')) y = int(input('Enter an integer:')) if x ^ y!=0: print(x,' and ', y, ' are different') else: print(x,' and ', y, ' are same')
x = int(input('Enter an integer:')) y = int(input('Enter an integer:')) if x ^ y != 0: print(x, ' and ', y, ' are different') else: print(x, ' and ', y, ' are same')
#!/usr/bin/env python ####################################### # Installation module for AttackSurfaceMapper ####################################### DESCRIPTION="This module will install/update Attack Surface Mapper (ASM) by Andreas Georgiou - A tool that aim to automate the recon process" AUTHOR="Andrew Schwartz" INSTALL_TYPE="GIT" REPOSITORY_LOCATION="https://github.com/superhedgy/AttackSurfaceMapper.git" INSTALL_LOCATION="ASM" DEBIAN="python3,pip" AFTER_COMMANDS="cd {INSTALL_LOCATION},python3 -m pip install --no-cache-dir -r requirements.txt"
description = 'This module will install/update Attack Surface Mapper (ASM) by Andreas Georgiou - A tool that aim to automate the recon process' author = 'Andrew Schwartz' install_type = 'GIT' repository_location = 'https://github.com/superhedgy/AttackSurfaceMapper.git' install_location = 'ASM' debian = 'python3,pip' after_commands = 'cd {INSTALL_LOCATION},python3 -m pip install --no-cache-dir -r requirements.txt'
def k_to_c(k): c = (k - 273.15) return c k = 268.0 c = k_to_c(k) print("kelvin of" + str(k) + "is" + str(c) + "in kelvin" )
def k_to_c(k): c = k - 273.15 return c k = 268.0 c = k_to_c(k) print('kelvin of' + str(k) + 'is' + str(c) + 'in kelvin')
# Autogenerated file for Reflected light # Add missing from ... import const _JD_SERVICE_CLASS_REFLECTED_LIGHT = const(0x126c4cb2) _JD_REFLECTED_LIGHT_VARIANT_INFRARED_DIGITAL = const(0x1) _JD_REFLECTED_LIGHT_VARIANT_INFRARED_ANALOG = const(0x2) _JD_REFLECTED_LIGHT_REG_BRIGHTNESS = const(JD_REG_READING) _JD_REFLECTED_LIGHT_REG_VARIANT = const(JD_REG_VARIANT) _JD_REFLECTED_LIGHT_EV_DARK = const(JD_EV_INACTIVE) _JD_REFLECTED_LIGHT_EV_LIGHT = const(JD_EV_ACTIVE)
_jd_service_class_reflected_light = const(309087410) _jd_reflected_light_variant_infrared_digital = const(1) _jd_reflected_light_variant_infrared_analog = const(2) _jd_reflected_light_reg_brightness = const(JD_REG_READING) _jd_reflected_light_reg_variant = const(JD_REG_VARIANT) _jd_reflected_light_ev_dark = const(JD_EV_INACTIVE) _jd_reflected_light_ev_light = const(JD_EV_ACTIVE)
# https://leetcode.com/problems/unique-morse-code-words/ mapping = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."] class Solution: def uniqueMorseRepresentations(self, words): """ :type words: List[str] :rtype: int """ transformations = set() for word in words: transformations.add(''.join([mapping[ord(c) - ord('a')] for c in word])) return len(transformations)
mapping = ['.-', '-...', '-.-.', '-..', '.', '..-.', '--.', '....', '..', '.---', '-.-', '.-..', '--', '-.', '---', '.--.', '--.-', '.-.', '...', '-', '..-', '...-', '.--', '-..-', '-.--', '--..'] class Solution: def unique_morse_representations(self, words): """ :type words: List[str] :rtype: int """ transformations = set() for word in words: transformations.add(''.join([mapping[ord(c) - ord('a')] for c in word])) return len(transformations)
#!/bin/python3 # Designer Door Mat # https://www.hackerrank.com/challenges/designer-door-mat/problem n, m = map(int, input().split()) init = ".|." for i in range(n // 2): print(init.center(m, "-")) init = ".|." + init + ".|." print("WELCOME".center(m, "-")) for i in range(n // 2): linit = list(init) init = "".join(linit[3:len(linit) - 3]) print(init.center(m, "-"))
(n, m) = map(int, input().split()) init = '.|.' for i in range(n // 2): print(init.center(m, '-')) init = '.|.' + init + '.|.' print('WELCOME'.center(m, '-')) for i in range(n // 2): linit = list(init) init = ''.join(linit[3:len(linit) - 3]) print(init.center(m, '-'))
# albus.exceptions class AlbusError(Exception): def __init__(self, message, inner=None, detail=None): self.message = message self.inner = inner self.detail = detail
class Albuserror(Exception): def __init__(self, message, inner=None, detail=None): self.message = message self.inner = inner self.detail = detail
# Created by MechAviv # Nyen Damage Skin | (2438086) if sm.addDamageSkin(2438086): sm.chat("'Nyen Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
if sm.addDamageSkin(2438086): sm.chat("'Nyen Damage Skin' Damage Skin has been added to your account's damage skin collection.") sm.consumeItem()
# -*- coding: utf-8 -*- # # Copyright 2016 Civic Knowledge. All Rights Reserved # This software may be modified and distributed under the terms of the BSD license. # See the LICENSE file for details. def get_root(): return ['do some magic?','or don\'t'] def get_measure_root(id): return "got id {} ({}) ".format(id, type(id))
def get_root(): return ['do some magic?', "or don't"] def get_measure_root(id): return 'got id {} ({}) '.format(id, type(id))
# # PySNMP MIB module CHANNEL-CHANGE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CHANNEL-CHANGE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:31:02 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") ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection") InterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") Counter64, ModuleIdentity, Gauge32, ObjectIdentity, MibIdentifier, Integer32, Counter32, Unsigned32, iso, enterprises, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "ModuleIdentity", "Gauge32", "ObjectIdentity", "MibIdentifier", "Integer32", "Counter32", "Unsigned32", "iso", "enterprises", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "NotificationType", "TimeTicks") DisplayString, RowStatus, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention") channelChangeMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 1, 1, 1)) if mibBuilder.loadTexts: channelChangeMib.setLastUpdated('200205121638Z') if mibBuilder.loadTexts: channelChangeMib.setOrganization('FS VDSL Architecture Experts Group') fsan = MibIdentifier((1, 3, 6, 1, 4, 1, 1)) fsVdsl = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1)) channelChangeMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 1)) channelChangeMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 2)) channelTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1), ) if mibBuilder.loadTexts: channelTable.setStatus('current') channelEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "channelId")) if mibBuilder.loadTexts: channelEntry.setStatus('current') channelId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1), IpAddress()) if mibBuilder.loadTexts: channelId.setStatus('current') entitlementIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095))).setMaxAccess("readcreate") if mibBuilder.loadTexts: entitlementIndex.setStatus('current') networkPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 3), InterfaceIndex()).setMaxAccess("readcreate") if mibBuilder.loadTexts: networkPortId.setStatus('current') vpi = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: vpi.setStatus('current') vci = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(32, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: vci.setStatus('current') channelAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2), ("shuttingDown", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: channelAdminStatus.setStatus('current') channelRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 8), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: channelRowStatus.setStatus('current') customerTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2), ) if mibBuilder.loadTexts: customerTable.setStatus('current') customerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "onuId"), (0, "CHANNEL-CHANGE-MIB", "customerPortId")) if mibBuilder.loadTexts: customerEntry.setStatus('current') onuId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 1), InterfaceIndexOrZero()) if mibBuilder.loadTexts: onuId.setStatus('current') customerPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 2), InterfaceIndex()) if mibBuilder.loadTexts: customerPortId.setStatus('current') maxMulticastTraffic = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 3), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: maxMulticastTraffic.setStatus('current') maxMulticastStreams = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 4), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: maxMulticastStreams.setStatus('current') untimedEntitlements1 = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readcreate") if mibBuilder.loadTexts: untimedEntitlements1.setStatus('current') untimedEntitlements2 = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 256))).setMaxAccess("readcreate") if mibBuilder.loadTexts: untimedEntitlements2.setStatus('current') grantEntitlement = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 7), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: grantEntitlement.setStatus('current') revokeEntitlement = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 8), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: revokeEntitlement.setStatus('current') customerAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2), ("shuttingDown", 3)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: customerAdminStatus.setStatus('current') customerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 10), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: customerRowStatus.setStatus('current') timedEntitlementTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3), ) if mibBuilder.loadTexts: timedEntitlementTable.setStatus('current') timedEntitlementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "timedEntitlementId")) if mibBuilder.loadTexts: timedEntitlementEntry.setStatus('current') timedEntitlementId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: timedEntitlementId.setStatus('current') timedEntitlementChannelId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 2), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: timedEntitlementChannelId.setStatus('current') startTime = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readcreate") if mibBuilder.loadTexts: startTime.setStatus('current') stopTime = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 16))).setMaxAccess("readcreate") if mibBuilder.loadTexts: stopTime.setStatus('current') entitlementRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 5), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: entitlementRowStatus.setStatus('current') customerTimedEntitlementTable = MibTable((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4), ) if mibBuilder.loadTexts: customerTimedEntitlementTable.setStatus('current') customerTimedEntitlementEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1), ).setIndexNames((0, "CHANNEL-CHANGE-MIB", "custOnuId"), (0, "CHANNEL-CHANGE-MIB", "custPortId"), (0, "CHANNEL-CHANGE-MIB", "custTimedEntitlementId")) if mibBuilder.loadTexts: customerTimedEntitlementEntry.setStatus('current') custOnuId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 1), InterfaceIndexOrZero()) if mibBuilder.loadTexts: custOnuId.setStatus('current') custPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 2), InterfaceIndex()) if mibBuilder.loadTexts: custPortId.setStatus('current') custTimedEntitlementId = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate") if mibBuilder.loadTexts: custTimedEntitlementId.setStatus('current') custTimedEntitlementRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 4), RowStatus().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6)))).setMaxAccess("readcreate") if mibBuilder.loadTexts: custTimedEntitlementRowStatus.setStatus('current') channelChangeMibNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 2, 0)) channelChangeCAFailed = NotificationType((1, 3, 6, 1, 4, 1, 1, 1, 1, 2, 0, 1)).setObjects(("CHANNEL-CHANGE-MIB", "rejectedOnuId"), ("CHANNEL-CHANGE-MIB", "rejectedCustomerPortId")) if mibBuilder.loadTexts: channelChangeCAFailed.setStatus('current') rejectedOnuId = MibScalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 5), InterfaceIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rejectedOnuId.setStatus('current') rejectedCustomerPortId = MibScalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 6), InterfaceIndex()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rejectedCustomerPortId.setStatus('current') caFailedNotificationStatus = MibScalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: caFailedNotificationStatus.setStatus('current') channelChangeMibConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3)) channelChangeMibCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 1)) channelChangeMibGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2)) channelChangeMibCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 1, 1)).setObjects(("CHANNEL-CHANGE-MIB", "channelChangeBasicGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCACGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeBasicCAGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCA4095ChannelsGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCATimedEntitlementsGroup"), ("CHANNEL-CHANGE-MIB", "channelChangeCANotificationsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeMibCompliance = channelChangeMibCompliance.setStatus('current') channelChangeBasicGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 1)).setObjects(("CHANNEL-CHANGE-MIB", "channelId"), ("CHANNEL-CHANGE-MIB", "networkPortId"), ("CHANNEL-CHANGE-MIB", "vpi"), ("CHANNEL-CHANGE-MIB", "vci"), ("CHANNEL-CHANGE-MIB", "channelAdminStatus"), ("CHANNEL-CHANGE-MIB", "channelRowStatus"), ("CHANNEL-CHANGE-MIB", "onuId"), ("CHANNEL-CHANGE-MIB", "customerPortId")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeBasicGroup = channelChangeBasicGroup.setStatus('current') channelChangeCACGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 2)).setObjects(("CHANNEL-CHANGE-MIB", "maxMulticastTraffic")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCACGroup = channelChangeCACGroup.setStatus('current') channelChangeBasicCAGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 3)).setObjects(("CHANNEL-CHANGE-MIB", "maxMulticastStreams"), ("CHANNEL-CHANGE-MIB", "entitlementIndex"), ("CHANNEL-CHANGE-MIB", "untimedEntitlements1"), ("CHANNEL-CHANGE-MIB", "grantEntitlement"), ("CHANNEL-CHANGE-MIB", "revokeEntitlement"), ("CHANNEL-CHANGE-MIB", "rejectedOnuId"), ("CHANNEL-CHANGE-MIB", "rejectedCustomerPortId"), ("CHANNEL-CHANGE-MIB", "caFailedNotificationStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeBasicCAGroup = channelChangeBasicCAGroup.setStatus('current') channelChangeCA4095ChannelsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 4)).setObjects(("CHANNEL-CHANGE-MIB", "untimedEntitlements2")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCA4095ChannelsGroup = channelChangeCA4095ChannelsGroup.setStatus('current') channelChangeCATimedEntitlementsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 5)).setObjects(("CHANNEL-CHANGE-MIB", "timedEntitlementId"), ("CHANNEL-CHANGE-MIB", "timedEntitlementChannelId"), ("CHANNEL-CHANGE-MIB", "startTime"), ("CHANNEL-CHANGE-MIB", "stopTime"), ("CHANNEL-CHANGE-MIB", "entitlementRowStatus"), ("CHANNEL-CHANGE-MIB", "custTimedEntitlementId"), ("CHANNEL-CHANGE-MIB", "custTimedEntitlementRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCATimedEntitlementsGroup = channelChangeCATimedEntitlementsGroup.setStatus('current') channelChangeCANotificationsGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 6)).setObjects(("CHANNEL-CHANGE-MIB", "channelChangeCAFailed")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channelChangeCANotificationsGroup = channelChangeCANotificationsGroup.setStatus('current') mibBuilder.exportSymbols("CHANNEL-CHANGE-MIB", networkPortId=networkPortId, timedEntitlementId=timedEntitlementId, customerTable=customerTable, channelChangeBasicCAGroup=channelChangeBasicCAGroup, channelAdminStatus=channelAdminStatus, channelChangeMibCompliance=channelChangeMibCompliance, customerRowStatus=customerRowStatus, customerTimedEntitlementEntry=customerTimedEntitlementEntry, customerPortId=customerPortId, timedEntitlementTable=timedEntitlementTable, channelRowStatus=channelRowStatus, channelEntry=channelEntry, channelChangeMibGroups=channelChangeMibGroups, entitlementIndex=entitlementIndex, customerAdminStatus=customerAdminStatus, untimedEntitlements2=untimedEntitlements2, grantEntitlement=grantEntitlement, channelChangeMibNotificationPrefix=channelChangeMibNotificationPrefix, fsVdsl=fsVdsl, customerTimedEntitlementTable=customerTimedEntitlementTable, channelId=channelId, timedEntitlementEntry=timedEntitlementEntry, channelTable=channelTable, channelChangeMibConformance=channelChangeMibConformance, maxMulticastTraffic=maxMulticastTraffic, channelChangeMibCompliances=channelChangeMibCompliances, channelChangeCA4095ChannelsGroup=channelChangeCA4095ChannelsGroup, stopTime=stopTime, channelChangeBasicGroup=channelChangeBasicGroup, channelChangeCAFailed=channelChangeCAFailed, channelChangeCACGroup=channelChangeCACGroup, custTimedEntitlementId=custTimedEntitlementId, maxMulticastStreams=maxMulticastStreams, channelChangeMib=channelChangeMib, vci=vci, untimedEntitlements1=untimedEntitlements1, channelChangeMibObjects=channelChangeMibObjects, timedEntitlementChannelId=timedEntitlementChannelId, rejectedCustomerPortId=rejectedCustomerPortId, caFailedNotificationStatus=caFailedNotificationStatus, onuId=onuId, custTimedEntitlementRowStatus=custTimedEntitlementRowStatus, startTime=startTime, vpi=vpi, channelChangeCATimedEntitlementsGroup=channelChangeCATimedEntitlementsGroup, PYSNMP_MODULE_ID=channelChangeMib, channelChangeMibNotifications=channelChangeMibNotifications, entitlementRowStatus=entitlementRowStatus, rejectedOnuId=rejectedOnuId, fsan=fsan, custOnuId=custOnuId, customerEntry=customerEntry, channelChangeCANotificationsGroup=channelChangeCANotificationsGroup, custPortId=custPortId, revokeEntitlement=revokeEntitlement)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, value_size_constraint, constraints_union, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection') (interface_index, interface_index_or_zero) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex', 'InterfaceIndexOrZero') (module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup') (counter64, module_identity, gauge32, object_identity, mib_identifier, integer32, counter32, unsigned32, iso, enterprises, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, notification_type, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'ModuleIdentity', 'Gauge32', 'ObjectIdentity', 'MibIdentifier', 'Integer32', 'Counter32', 'Unsigned32', 'iso', 'enterprises', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'NotificationType', 'TimeTicks') (display_string, row_status, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'RowStatus', 'TextualConvention') channel_change_mib = module_identity((1, 3, 6, 1, 4, 1, 1, 1, 1)) if mibBuilder.loadTexts: channelChangeMib.setLastUpdated('200205121638Z') if mibBuilder.loadTexts: channelChangeMib.setOrganization('FS VDSL Architecture Experts Group') fsan = mib_identifier((1, 3, 6, 1, 4, 1, 1)) fs_vdsl = mib_identifier((1, 3, 6, 1, 4, 1, 1, 1)) channel_change_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 1)) channel_change_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 2)) channel_table = mib_table((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1)) if mibBuilder.loadTexts: channelTable.setStatus('current') channel_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1)).setIndexNames((0, 'CHANNEL-CHANGE-MIB', 'channelId')) if mibBuilder.loadTexts: channelEntry.setStatus('current') channel_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1), ip_address()) if mibBuilder.loadTexts: channelId.setStatus('current') entitlement_index = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 4095))).setMaxAccess('readcreate') if mibBuilder.loadTexts: entitlementIndex.setStatus('current') network_port_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 3), interface_index()).setMaxAccess('readcreate') if mibBuilder.loadTexts: networkPortId.setStatus('current') vpi = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readcreate') if mibBuilder.loadTexts: vpi.setStatus('current') vci = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(32, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: vci.setStatus('current') channel_admin_status = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('locked', 1), ('unlocked', 2), ('shuttingDown', 3)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: channelAdminStatus.setStatus('current') channel_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 1, 1, 8), row_status().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('active', 1), ('notInService', 2), ('notReady', 3), ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: channelRowStatus.setStatus('current') customer_table = mib_table((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2)) if mibBuilder.loadTexts: customerTable.setStatus('current') customer_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1)).setIndexNames((0, 'CHANNEL-CHANGE-MIB', 'onuId'), (0, 'CHANNEL-CHANGE-MIB', 'customerPortId')) if mibBuilder.loadTexts: customerEntry.setStatus('current') onu_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 1), interface_index_or_zero()) if mibBuilder.loadTexts: onuId.setStatus('current') customer_port_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 2), interface_index()) if mibBuilder.loadTexts: customerPortId.setStatus('current') max_multicast_traffic = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 3), integer32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: maxMulticastTraffic.setStatus('current') max_multicast_streams = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 4), integer32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: maxMulticastStreams.setStatus('current') untimed_entitlements1 = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 5), octet_string().subtype(subtypeSpec=value_size_constraint(0, 256))).setMaxAccess('readcreate') if mibBuilder.loadTexts: untimedEntitlements1.setStatus('current') untimed_entitlements2 = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(0, 256))).setMaxAccess('readcreate') if mibBuilder.loadTexts: untimedEntitlements2.setStatus('current') grant_entitlement = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 7), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: grantEntitlement.setStatus('current') revoke_entitlement = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 8), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: revokeEntitlement.setStatus('current') customer_admin_status = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('locked', 1), ('unlocked', 2), ('shuttingDown', 3)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: customerAdminStatus.setStatus('current') customer_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 2, 1, 10), row_status().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('active', 1), ('notInService', 2), ('notReady', 3), ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: customerRowStatus.setStatus('current') timed_entitlement_table = mib_table((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3)) if mibBuilder.loadTexts: timedEntitlementTable.setStatus('current') timed_entitlement_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1)).setIndexNames((0, 'CHANNEL-CHANGE-MIB', 'timedEntitlementId')) if mibBuilder.loadTexts: timedEntitlementEntry.setStatus('current') timed_entitlement_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: timedEntitlementId.setStatus('current') timed_entitlement_channel_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 2), ip_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: timedEntitlementChannelId.setStatus('current') start_time = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readcreate') if mibBuilder.loadTexts: startTime.setStatus('current') stop_time = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 4), octet_string().subtype(subtypeSpec=value_size_constraint(0, 16))).setMaxAccess('readcreate') if mibBuilder.loadTexts: stopTime.setStatus('current') entitlement_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 3, 1, 5), row_status().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('active', 1), ('notInService', 2), ('notReady', 3), ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: entitlementRowStatus.setStatus('current') customer_timed_entitlement_table = mib_table((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4)) if mibBuilder.loadTexts: customerTimedEntitlementTable.setStatus('current') customer_timed_entitlement_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1)).setIndexNames((0, 'CHANNEL-CHANGE-MIB', 'custOnuId'), (0, 'CHANNEL-CHANGE-MIB', 'custPortId'), (0, 'CHANNEL-CHANGE-MIB', 'custTimedEntitlementId')) if mibBuilder.loadTexts: customerTimedEntitlementEntry.setStatus('current') cust_onu_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 1), interface_index_or_zero()) if mibBuilder.loadTexts: custOnuId.setStatus('current') cust_port_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 2), interface_index()) if mibBuilder.loadTexts: custPortId.setStatus('current') cust_timed_entitlement_id = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535))).setMaxAccess('readcreate') if mibBuilder.loadTexts: custTimedEntitlementId.setStatus('current') cust_timed_entitlement_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 4, 1, 4), row_status().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('active', 1), ('notInService', 2), ('notReady', 3), ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6)))).setMaxAccess('readcreate') if mibBuilder.loadTexts: custTimedEntitlementRowStatus.setStatus('current') channel_change_mib_notification_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 2, 0)) channel_change_ca_failed = notification_type((1, 3, 6, 1, 4, 1, 1, 1, 1, 2, 0, 1)).setObjects(('CHANNEL-CHANGE-MIB', 'rejectedOnuId'), ('CHANNEL-CHANGE-MIB', 'rejectedCustomerPortId')) if mibBuilder.loadTexts: channelChangeCAFailed.setStatus('current') rejected_onu_id = mib_scalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 5), interface_index_or_zero()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rejectedOnuId.setStatus('current') rejected_customer_port_id = mib_scalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 6), interface_index()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rejectedCustomerPortId.setStatus('current') ca_failed_notification_status = mib_scalar((1, 3, 6, 1, 4, 1, 1, 1, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: caFailedNotificationStatus.setStatus('current') channel_change_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3)) channel_change_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 1)) channel_change_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2)) channel_change_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 1, 1)).setObjects(('CHANNEL-CHANGE-MIB', 'channelChangeBasicGroup'), ('CHANNEL-CHANGE-MIB', 'channelChangeCACGroup'), ('CHANNEL-CHANGE-MIB', 'channelChangeBasicCAGroup'), ('CHANNEL-CHANGE-MIB', 'channelChangeCA4095ChannelsGroup'), ('CHANNEL-CHANGE-MIB', 'channelChangeCATimedEntitlementsGroup'), ('CHANNEL-CHANGE-MIB', 'channelChangeCANotificationsGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channel_change_mib_compliance = channelChangeMibCompliance.setStatus('current') channel_change_basic_group = object_group((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 1)).setObjects(('CHANNEL-CHANGE-MIB', 'channelId'), ('CHANNEL-CHANGE-MIB', 'networkPortId'), ('CHANNEL-CHANGE-MIB', 'vpi'), ('CHANNEL-CHANGE-MIB', 'vci'), ('CHANNEL-CHANGE-MIB', 'channelAdminStatus'), ('CHANNEL-CHANGE-MIB', 'channelRowStatus'), ('CHANNEL-CHANGE-MIB', 'onuId'), ('CHANNEL-CHANGE-MIB', 'customerPortId')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channel_change_basic_group = channelChangeBasicGroup.setStatus('current') channel_change_cac_group = object_group((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 2)).setObjects(('CHANNEL-CHANGE-MIB', 'maxMulticastTraffic')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channel_change_cac_group = channelChangeCACGroup.setStatus('current') channel_change_basic_ca_group = object_group((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 3)).setObjects(('CHANNEL-CHANGE-MIB', 'maxMulticastStreams'), ('CHANNEL-CHANGE-MIB', 'entitlementIndex'), ('CHANNEL-CHANGE-MIB', 'untimedEntitlements1'), ('CHANNEL-CHANGE-MIB', 'grantEntitlement'), ('CHANNEL-CHANGE-MIB', 'revokeEntitlement'), ('CHANNEL-CHANGE-MIB', 'rejectedOnuId'), ('CHANNEL-CHANGE-MIB', 'rejectedCustomerPortId'), ('CHANNEL-CHANGE-MIB', 'caFailedNotificationStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channel_change_basic_ca_group = channelChangeBasicCAGroup.setStatus('current') channel_change_ca4095_channels_group = object_group((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 4)).setObjects(('CHANNEL-CHANGE-MIB', 'untimedEntitlements2')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channel_change_ca4095_channels_group = channelChangeCA4095ChannelsGroup.setStatus('current') channel_change_ca_timed_entitlements_group = object_group((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 5)).setObjects(('CHANNEL-CHANGE-MIB', 'timedEntitlementId'), ('CHANNEL-CHANGE-MIB', 'timedEntitlementChannelId'), ('CHANNEL-CHANGE-MIB', 'startTime'), ('CHANNEL-CHANGE-MIB', 'stopTime'), ('CHANNEL-CHANGE-MIB', 'entitlementRowStatus'), ('CHANNEL-CHANGE-MIB', 'custTimedEntitlementId'), ('CHANNEL-CHANGE-MIB', 'custTimedEntitlementRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channel_change_ca_timed_entitlements_group = channelChangeCATimedEntitlementsGroup.setStatus('current') channel_change_ca_notifications_group = notification_group((1, 3, 6, 1, 4, 1, 1, 1, 1, 3, 2, 6)).setObjects(('CHANNEL-CHANGE-MIB', 'channelChangeCAFailed')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): channel_change_ca_notifications_group = channelChangeCANotificationsGroup.setStatus('current') mibBuilder.exportSymbols('CHANNEL-CHANGE-MIB', networkPortId=networkPortId, timedEntitlementId=timedEntitlementId, customerTable=customerTable, channelChangeBasicCAGroup=channelChangeBasicCAGroup, channelAdminStatus=channelAdminStatus, channelChangeMibCompliance=channelChangeMibCompliance, customerRowStatus=customerRowStatus, customerTimedEntitlementEntry=customerTimedEntitlementEntry, customerPortId=customerPortId, timedEntitlementTable=timedEntitlementTable, channelRowStatus=channelRowStatus, channelEntry=channelEntry, channelChangeMibGroups=channelChangeMibGroups, entitlementIndex=entitlementIndex, customerAdminStatus=customerAdminStatus, untimedEntitlements2=untimedEntitlements2, grantEntitlement=grantEntitlement, channelChangeMibNotificationPrefix=channelChangeMibNotificationPrefix, fsVdsl=fsVdsl, customerTimedEntitlementTable=customerTimedEntitlementTable, channelId=channelId, timedEntitlementEntry=timedEntitlementEntry, channelTable=channelTable, channelChangeMibConformance=channelChangeMibConformance, maxMulticastTraffic=maxMulticastTraffic, channelChangeMibCompliances=channelChangeMibCompliances, channelChangeCA4095ChannelsGroup=channelChangeCA4095ChannelsGroup, stopTime=stopTime, channelChangeBasicGroup=channelChangeBasicGroup, channelChangeCAFailed=channelChangeCAFailed, channelChangeCACGroup=channelChangeCACGroup, custTimedEntitlementId=custTimedEntitlementId, maxMulticastStreams=maxMulticastStreams, channelChangeMib=channelChangeMib, vci=vci, untimedEntitlements1=untimedEntitlements1, channelChangeMibObjects=channelChangeMibObjects, timedEntitlementChannelId=timedEntitlementChannelId, rejectedCustomerPortId=rejectedCustomerPortId, caFailedNotificationStatus=caFailedNotificationStatus, onuId=onuId, custTimedEntitlementRowStatus=custTimedEntitlementRowStatus, startTime=startTime, vpi=vpi, channelChangeCATimedEntitlementsGroup=channelChangeCATimedEntitlementsGroup, PYSNMP_MODULE_ID=channelChangeMib, channelChangeMibNotifications=channelChangeMibNotifications, entitlementRowStatus=entitlementRowStatus, rejectedOnuId=rejectedOnuId, fsan=fsan, custOnuId=custOnuId, customerEntry=customerEntry, channelChangeCANotificationsGroup=channelChangeCANotificationsGroup, custPortId=custPortId, revokeEntitlement=revokeEntitlement)
x1 = 2 y1 = 2 x2 = 6 y2 = 10 m2 = (y2 - y1) / (x2 - x1) print(f'Slope = {m2:.2f}') # 9
x1 = 2 y1 = 2 x2 = 6 y2 = 10 m2 = (y2 - y1) / (x2 - x1) print(f'Slope = {m2:.2f}')
def read_delimited_lines(file_handle, delimiter='|', omit_delimiter=False, read_size=4): delimited_line = "" data = file_handle.read(read_size) while data: delimiter_index = data.find(delimiter) if delimiter_index < 0: delimited_line += data else: delimited_line += data[:delimiter_index if omit_delimiter else delimiter_index + 1] yield delimited_line.strip() delimited_line = data[delimiter_index + 1:] data = file_handle.read(read_size) if len(delimited_line) > 0: yield delimited_line with open("lorem.txt") as colors_file: for line in read_delimited_lines(colors_file, "."): print(line)
def read_delimited_lines(file_handle, delimiter='|', omit_delimiter=False, read_size=4): delimited_line = '' data = file_handle.read(read_size) while data: delimiter_index = data.find(delimiter) if delimiter_index < 0: delimited_line += data else: delimited_line += data[:delimiter_index if omit_delimiter else delimiter_index + 1] yield delimited_line.strip() delimited_line = data[delimiter_index + 1:] data = file_handle.read(read_size) if len(delimited_line) > 0: yield delimited_line with open('lorem.txt') as colors_file: for line in read_delimited_lines(colors_file, '.'): print(line)
""" Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. Thoughts: 1. Initial thought is to traverse the price list 2 times with time complexity O(n^2) 2. Do better? Better solution is use 2 pointers to keep track of the current_buying and current_saling index respectively """ class Solution: """ of course, we ran out of time limit """ def maxProfit(self, prices) -> int: max_profit = 0 for buying_day, buying_price in enumerate(prices): for saling_price in prices[buying_day+1:]: if saling_price-buying_price>max_profit: max_profit = saling_price-buying_price return max_profit class Solution2: def maxProfit(self, prices): buying_index = 0 current_index = 1 days = len(prices) max_profit = 0 while current_index < days: if prices[current_index] - prices[buying_index]>max_profit: max_profit = prices[current_index] - prices[buying_index] elif prices[current_index]<prices[buying_index]: buying_index = current_index current_index += 1 return max_profit if __name__ == "__main__": s = Solution2() test1 = [7,1,5,3,6,4] test2 = [7,6,4,3,1] print(s.maxProfit(test1)) print(s.maxProfit(test2))
""" Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5. Not 7-1 = 6, as selling price needs to be larger than buying price. Input: [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0. Thoughts: 1. Initial thought is to traverse the price list 2 times with time complexity O(n^2) 2. Do better? Better solution is use 2 pointers to keep track of the current_buying and current_saling index respectively """ class Solution: """ of course, we ran out of time limit """ def max_profit(self, prices) -> int: max_profit = 0 for (buying_day, buying_price) in enumerate(prices): for saling_price in prices[buying_day + 1:]: if saling_price - buying_price > max_profit: max_profit = saling_price - buying_price return max_profit class Solution2: def max_profit(self, prices): buying_index = 0 current_index = 1 days = len(prices) max_profit = 0 while current_index < days: if prices[current_index] - prices[buying_index] > max_profit: max_profit = prices[current_index] - prices[buying_index] elif prices[current_index] < prices[buying_index]: buying_index = current_index current_index += 1 return max_profit if __name__ == '__main__': s = solution2() test1 = [7, 1, 5, 3, 6, 4] test2 = [7, 6, 4, 3, 1] print(s.maxProfit(test1)) print(s.maxProfit(test2))
"""Posenet model benchmark case list.""" POSE_ESTIMATION_MODEL_BENCHMARK_CASES = [ # PoseNet { "benchmark_name": "BM_PoseNet_MobileNetV1_075_353_481_WithDecoder", "model_path": "posenet/posenet_mobilenet_v1_075_353_481_16_quant_decoder", }, { "benchmark_name": "BM_PoseNet_MobileNetV1_075_481_641_WithDecoder", "model_path": "posenet/posenet_mobilenet_v1_075_481_641_16_quant_decoder", }, { "benchmark_name": "BM_PoseNet_MobileNetV1_075_721_1281_WithDecoder", "model_path": "posenet/posenet_mobilenet_v1_075_721_1281_16_quant_decoder", }, # MobileNet BodyPix { "benchmark_name": "BM_Bodypix_MobileNetV1_075_512_512_WithDecoder", "model_path": "posenet/bodypix_mobilenet_v1_075_512_512_16_quant_decoder", }, # MoveNet { "benchmark_name": "BM_MovenetLightning", "model_path": "movenet_single_pose_lightning_ptq", }, { "benchmark_name": "BM_MovenetThunder", "model_path": "movenet_single_pose_thunder_ptq", }, ]
"""Posenet model benchmark case list.""" pose_estimation_model_benchmark_cases = [{'benchmark_name': 'BM_PoseNet_MobileNetV1_075_353_481_WithDecoder', 'model_path': 'posenet/posenet_mobilenet_v1_075_353_481_16_quant_decoder'}, {'benchmark_name': 'BM_PoseNet_MobileNetV1_075_481_641_WithDecoder', 'model_path': 'posenet/posenet_mobilenet_v1_075_481_641_16_quant_decoder'}, {'benchmark_name': 'BM_PoseNet_MobileNetV1_075_721_1281_WithDecoder', 'model_path': 'posenet/posenet_mobilenet_v1_075_721_1281_16_quant_decoder'}, {'benchmark_name': 'BM_Bodypix_MobileNetV1_075_512_512_WithDecoder', 'model_path': 'posenet/bodypix_mobilenet_v1_075_512_512_16_quant_decoder'}, {'benchmark_name': 'BM_MovenetLightning', 'model_path': 'movenet_single_pose_lightning_ptq'}, {'benchmark_name': 'BM_MovenetThunder', 'model_path': 'movenet_single_pose_thunder_ptq'}]
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### response.logo = A(B(SPAN('M'),'eta',SPAN('B'),'ase'),XML('&trade;&nbsp;'), _class="navbar-brand",_href=URL('default', 'index'), _id="web2py-logo") response.title = request.application.replace('_',' ').title() response.subtitle = '' ## read more at http://dev.w3.org/html5/markup/meta.name.html response.meta.author = 'Ryan Marquardt <[email protected]>' response.meta.description = 'a cool new app' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' ## your http://google.com/analytics id response.google_analytics_id = None ######################################################################### ## this is the main application menu add/remove items as required ######################################################################### response.menu = [ (T('Home'), False, URL('default', 'index'), []), (T('Setup'), False, URL('setup', 'index'), []), ] DEVELOPMENT_MENU = (auth.user and (auth.user.id == 1)) ######################################################################### ## provide shortcuts for development. remove in production ######################################################################### def PAedit(path): return ('https://www.pythonanywhere.com/user/integralws/files' '/home/integralws/glean/applications/metabase/%s?edit') % path def _(): # shortcuts app = request.application ctr = request.controller # useful links to internal and external resources response.menu += [ (T('This App'), False, '#', [ (T('Design'), False, URL('admin', 'default', 'design/%s' % app)), LI(_class="divider"), (T('Controller'), False, URL( 'admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))), (T('View'), False, URL( 'admin', 'default', 'edit/%s/views/%s' % (app, response.view))), (T('DB Model'), False, URL( 'admin', 'default', 'edit/%s/models/db.py' % app)), (T('Menu Model'), False, URL( 'admin', 'default', 'edit/%s/models/menu.py' % app)), (T('Config.ini'), False, URL( 'admin', 'default', 'edit/%s/private/appconfig.ini' % app)), (T('Layout'), False, URL( 'admin', 'default', 'edit/%s/views/layout.html' % app)), (T('Stylesheet'), False, URL( 'admin', 'default', 'edit/%s/static/css/web2py-bootstrap3.css' % app)), (T('Database'), False, URL(app, 'appadmin', 'index')), (T('Errors'), False, URL( 'admin', 'default', 'errors/' + app)), (T('About'), False, URL( 'admin', 'default', 'about/' + app)), ]), ] if DEVELOPMENT_MENU: _() if "auth" in locals(): auth.wikimenu()
response.logo = a(b(span('M'), 'eta', span('B'), 'ase'), xml('&trade;&nbsp;'), _class='navbar-brand', _href=url('default', 'index'), _id='web2py-logo') response.title = request.application.replace('_', ' ').title() response.subtitle = '' response.meta.author = 'Ryan Marquardt <[email protected]>' response.meta.description = 'a cool new app' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' response.google_analytics_id = None response.menu = [(t('Home'), False, url('default', 'index'), []), (t('Setup'), False, url('setup', 'index'), [])] development_menu = auth.user and auth.user.id == 1 def p_aedit(path): return 'https://www.pythonanywhere.com/user/integralws/files/home/integralws/glean/applications/metabase/%s?edit' % path def _(): app = request.application ctr = request.controller response.menu += [(t('This App'), False, '#', [(t('Design'), False, url('admin', 'default', 'design/%s' % app)), li(_class='divider'), (t('Controller'), False, url('admin', 'default', 'edit/%s/controllers/%s.py' % (app, ctr))), (t('View'), False, url('admin', 'default', 'edit/%s/views/%s' % (app, response.view))), (t('DB Model'), False, url('admin', 'default', 'edit/%s/models/db.py' % app)), (t('Menu Model'), False, url('admin', 'default', 'edit/%s/models/menu.py' % app)), (t('Config.ini'), False, url('admin', 'default', 'edit/%s/private/appconfig.ini' % app)), (t('Layout'), False, url('admin', 'default', 'edit/%s/views/layout.html' % app)), (t('Stylesheet'), False, url('admin', 'default', 'edit/%s/static/css/web2py-bootstrap3.css' % app)), (t('Database'), False, url(app, 'appadmin', 'index')), (t('Errors'), False, url('admin', 'default', 'errors/' + app)), (t('About'), False, url('admin', 'default', 'about/' + app))])] if DEVELOPMENT_MENU: _() if 'auth' in locals(): auth.wikimenu()
def cluster_it(common_pos,no_sup,low_sup): topla=[] for x in common_pos: if x in no_sup+low_sup: continue else: topla.append(x) topla.sort() cluster={} r_cluster={} c_num=1 cluster['c_'+str(c_num)]=[] for i in range (0,len(topla)-1): pos1=topla[i] pos2=topla[i+1] Cd=abs(pos2 - pos1) if Cd <= 9: cluster['c_'+str(c_num)].append((pos1,pos2)) if Cd > 9: c_num = c_num+1 cluster['c_'+str(c_num)]=[] c_num=0 for keys in cluster: if len(cluster[keys]) >= 6: #this 6 actually means 7 cause counting in touples. remember to add +1 c_num=c_num+1 #print(c_num) r_cluster['c_'+str(c_num)]=cluster[keys] #r_cluster['c_'+str(c_num)].append(cluster[keys]) else: continue return cluster,r_cluster def CnandCs(r_cluster,kmer): print('The number of clusters found: {}\nCmsp; is the number of positions that make up a cluster while Cs is the cluster size'.format(len(r_cluster))) for r in r_cluster: Cs=r_cluster[r][-1][-1] - r_cluster[r][0][0] + kmer print ('Cmsp of cluster {} is {} and Cs is'.format(r,len(r_cluster[r])+1),Cs) def hotspots(r_cluster): a=list(r_cluster.keys()) hots={} c_num=1 hots['hotspot_'+str(c_num)]=[] for i in range(0,len(a)-1): pos1=r_cluster[a[i]][-1][-1] pos2=r_cluster[a[i+1]][0][0] Hd=pos2 - pos1 if Hd < 20: hots['hotspot_'+str(c_num)].append((a[i],a[i+1])) if Hd > 20: c_num=c_num+1 hots['hotspot_'+str(c_num)]=[] c_num=0 r_hots={} for keys in hots: if len(hots[keys]) > 0: c_num=c_num+1 #print(c_num) r_hots['hotspot_'+str(c_num)]=hots[keys] #r_cluster['c_'+str(c_num)].append(cluster[keys]) else: continue return hots,r_hots
def cluster_it(common_pos, no_sup, low_sup): topla = [] for x in common_pos: if x in no_sup + low_sup: continue else: topla.append(x) topla.sort() cluster = {} r_cluster = {} c_num = 1 cluster['c_' + str(c_num)] = [] for i in range(0, len(topla) - 1): pos1 = topla[i] pos2 = topla[i + 1] cd = abs(pos2 - pos1) if Cd <= 9: cluster['c_' + str(c_num)].append((pos1, pos2)) if Cd > 9: c_num = c_num + 1 cluster['c_' + str(c_num)] = [] c_num = 0 for keys in cluster: if len(cluster[keys]) >= 6: c_num = c_num + 1 r_cluster['c_' + str(c_num)] = cluster[keys] else: continue return (cluster, r_cluster) def cnand_cs(r_cluster, kmer): print('The number of clusters found: {}\nCmsp; is the number of positions that make up a cluster while Cs is the cluster size'.format(len(r_cluster))) for r in r_cluster: cs = r_cluster[r][-1][-1] - r_cluster[r][0][0] + kmer print('Cmsp of cluster {} is {} and Cs is'.format(r, len(r_cluster[r]) + 1), Cs) def hotspots(r_cluster): a = list(r_cluster.keys()) hots = {} c_num = 1 hots['hotspot_' + str(c_num)] = [] for i in range(0, len(a) - 1): pos1 = r_cluster[a[i]][-1][-1] pos2 = r_cluster[a[i + 1]][0][0] hd = pos2 - pos1 if Hd < 20: hots['hotspot_' + str(c_num)].append((a[i], a[i + 1])) if Hd > 20: c_num = c_num + 1 hots['hotspot_' + str(c_num)] = [] c_num = 0 r_hots = {} for keys in hots: if len(hots[keys]) > 0: c_num = c_num + 1 r_hots['hotspot_' + str(c_num)] = hots[keys] else: continue return (hots, r_hots)
# # PySNMP MIB module HIST-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HIST-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:31:14 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") ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, TimeTicks, Gauge32, enterprises, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, Integer32, Counter32, ObjectIdentity, NotificationType, MibIdentifier, experimental, IpAddress, Counter64, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "TimeTicks", "Gauge32", "enterprises", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "Integer32", "Counter32", "ObjectIdentity", "NotificationType", "MibIdentifier", "experimental", "IpAddress", "Counter64", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") usr = MibIdentifier((1, 3, 6, 1, 4, 1, 429)) nas = MibIdentifier((1, 3, 6, 1, 4, 1, 429, 1)) mdmHist = MibIdentifier((1, 3, 6, 1, 4, 1, 429, 1, 30)) mdmNacHistCurrentTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 1), ) if mibBuilder.loadTexts: mdmNacHistCurrentTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentTable.setDescription('') mdmNacHistCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1), ).setIndexNames((0, "HIST-MIB", "mdmNacHistCurrentIndex")) if mibBuilder.loadTexts: mdmNacHistCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentEntry.setDescription('Objects that define the history stats for NAC current interval.') mdmNacHistCurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentIndex.setDescription('Index in to the Current NAC History table. This index contains a unique value for each card in the chassis.') mdmNacHistCurrentStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentStartTime.setDescription('Specifies current interval start time in GMT.') mdmNacHistCurrentMgmtBusFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentMgmtBusFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentMgmtBusFailures.setDescription('Specifies number of Management Bus Failures occurred in the NAC during current interval so for.') mdmNacHistCurrentWatchdogTimouts = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistCurrentWatchdogTimouts.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentWatchdogTimouts.setDescription('Specifies number of Watchdog Timeouts occurred in the NAC during current interval so for.') mdmNacHistIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 2), ) if mibBuilder.loadTexts: mdmNacHistIntervalTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalTable.setDescription('') mdmNacHistIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1), ).setIndexNames((0, "HIST-MIB", "mdmNacHistIntervalIndex"), (0, "HIST-MIB", "mdmNacHistIntervalNumber")) if mibBuilder.loadTexts: mdmNacHistIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalEntry.setDescription('Objects that define history stats for NAC intervals.') mdmNacHistIntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalIndex.setDescription('Index in to NAC Interval History table. This index contains a unique value for each card in the chassis.') mdmNacHistIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 104))).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalNumber.setDescription('This object is the index for one of 104 possibel history intervals for this NAC.') mdmNacHistIntervalStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalStartTime.setDescription('Specifies interval start time in GMT.') mdmNacHistIntervalMgmtBusFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalMgmtBusFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalMgmtBusFailures.setDescription('Specifies number of Management Bus Failures occurred in the NAC during the interval.') mdmNacHistIntervalWatchdogTimouts = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmNacHistIntervalWatchdogTimouts.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalWatchdogTimouts.setDescription('Specifies number of Watchdog Timeouts occurred in the NAC during the interval.') mdmHistCurrentTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 3), ) if mibBuilder.loadTexts: mdmHistCurrentTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentTable.setDescription('') mdmHistCurrentEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1), ).setIndexNames((0, "HIST-MIB", "mdmHistCurrentIndex")) if mibBuilder.loadTexts: mdmHistCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentEntry.setDescription('Objects that define the history stats for modem current interval.') mdmHistCurrentIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentIndex.setDescription('Index in to the Current modem history table. This index contains the unique value associated with the modem as defined in the chassis MIB entity table.') mdmHistCurrentStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentStartTime.setDescription('Specifies current interval start time in GMT.') mdmHistCurrentInConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectEstabs.setDescription('Specifies number of incoming calls established during current interval so for.') mdmHistCurrentInConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectFailures.setDescription('Specifies number of incoming call failures during current interval so for.') mdmHistCurrentInConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectTerms.setDescription('Specifies number of incoming calls terminated during current interval so for.') mdmHistCurrentInConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectTime.setDescription('Specifies length of all incoming calls during current interval so for.') mdmHistCurrentInTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesRx.setDescription('Specifies number of bytes received through incoming calls during current interval so for.') mdmHistCurrentInTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 8), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesTx.setDescription('Specifies number of bytes sent out through incoming calls during current interval so for.') mdmHistCurrentOutConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 9), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectEstabs.setDescription('Specifies number of outgoing calls established during current interval so for.') mdmHistCurrentOutConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 10), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectFailures.setDescription('Specifies number of outgoing call failures during current interval so for.') mdmHistCurrentOutConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 11), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTerms.setDescription('Specifies number of outgoing calls terminated during current interval so for.') mdmHistCurrentOutConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 12), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTime.setDescription('Specifies length of all outgoing calls during current interval so for.') mdmHistCurrentOutTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 13), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesRx.setDescription('Specifies number of bytes received through outgoing calls during current interval so for.') mdmHistCurrentOutTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 14), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesTx.setDescription('Specifies number of bytes sent out through outgoing calls during current interval so for.') mdmHistCurrentBlers = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 15), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentBlers.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentBlers.setDescription('Specifies number of block errors received during current interval so for.') mdmHistCurrentFallBacks = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 16), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistCurrentFallBacks.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentFallBacks.setDescription('Specifies number of link speed fallbacks occured during current interval so for.') mdmHistIntervalTable = MibTable((1, 3, 6, 1, 4, 1, 429, 1, 30, 4), ) if mibBuilder.loadTexts: mdmHistIntervalTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalTable.setDescription('') mdmHistIntervalEntry = MibTableRow((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1), ).setIndexNames((0, "HIST-MIB", "mdmHistIntervalIndex"), (0, "HIST-MIB", "mdmHistIntervalNumber")) if mibBuilder.loadTexts: mdmHistIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalEntry.setDescription('Objects that define history stats for modem intervals.') mdmHistIntervalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalIndex.setDescription('Index in to the interval History table. This index contains the unique value associated with the modem as defined in the chassis MIB entity table.') mdmHistIntervalNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 104))).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalNumber.setDescription('This object is the index for one of 104 possibel history intervals for this modem.') mdmHistIntervalStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalStartTime.setDescription('Specifies interval start time in GMT.') mdmHistIntervalInConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectEstabs.setDescription('Specifies number of incoming calls established during the interval.') mdmHistIntervalInConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 5), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectFailures.setDescription('Specifies number of incoming call failures during the interval.') mdmHistIntervalInConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 6), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectTerms.setDescription('Specifies number of incoming calls terminated during the interval.') mdmHistIntervalInConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 7), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectTime.setDescription('Specifies length of all incoming calls during the intervals.') mdmHistIntervalInTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 8), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesRx.setDescription('Specifies number of bytes received through incoming calls during the interval.') mdmHistIntervalInTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 9), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesTx.setDescription('Specifies number of bytes sent out through incoming calls during the interval.') mdmHistIntervalOutConnectEstabs = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 10), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectEstabs.setDescription('Specifies number of outgoing calls established during the interval.') mdmHistIntervalOutConnectFailures = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 11), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectFailures.setDescription('Specifies number of outgoing call failures during the interval.') mdmHistIntervalOutConnectTerms = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 12), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTerms.setDescription('Specifies number of outgoing calls terminated during the interval.') mdmHistIntervalOutConnectTime = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 13), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTime.setDescription('Specifies length of all outgoing calls during the interval.') mdmHistIntervalOutTotalBytesRx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 14), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesRx.setDescription('Specifies number of bytes received through outgoing calls during the interval.') mdmHistIntervalOutTotalBytesTx = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 15), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesTx.setDescription('Specifies number of bytes sent out through outgoing calls during the interval.') mdmHistIntervalBlers = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 16), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalBlers.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalBlers.setDescription('Specifies number of block errors received during the interval.') mdmHistIntervalFallBacks = MibTableColumn((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 17), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: mdmHistIntervalFallBacks.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalFallBacks.setDescription('Specifies number of link speed fallbacks occured during the interval.') mibBuilder.exportSymbols("HIST-MIB", mdmHistCurrentOutTotalBytesTx=mdmHistCurrentOutTotalBytesTx, mdmHistCurrentOutConnectEstabs=mdmHistCurrentOutConnectEstabs, mdmHistIntervalInConnectFailures=mdmHistIntervalInConnectFailures, mdmHistIntervalOutTotalBytesRx=mdmHistIntervalOutTotalBytesRx, mdmHistCurrentOutTotalBytesRx=mdmHistCurrentOutTotalBytesRx, mdmNacHistCurrentWatchdogTimouts=mdmNacHistCurrentWatchdogTimouts, mdmHistCurrentBlers=mdmHistCurrentBlers, mdmHistIntervalStartTime=mdmHistIntervalStartTime, mdmHistIntervalTable=mdmHistIntervalTable, mdmHistCurrentInConnectTime=mdmHistCurrentInConnectTime, mdmHistCurrentOutConnectTime=mdmHistCurrentOutConnectTime, mdmHistIntervalInTotalBytesTx=mdmHistIntervalInTotalBytesTx, mdmHistIntervalBlers=mdmHistIntervalBlers, mdmHistCurrentInConnectEstabs=mdmHistCurrentInConnectEstabs, mdmHistIntervalOutTotalBytesTx=mdmHistIntervalOutTotalBytesTx, mdmHistIntervalInConnectTerms=mdmHistIntervalInConnectTerms, mdmHistCurrentTable=mdmHistCurrentTable, mdmHistCurrentEntry=mdmHistCurrentEntry, mdmNacHistIntervalMgmtBusFailures=mdmNacHistIntervalMgmtBusFailures, mdmHistCurrentOutConnectFailures=mdmHistCurrentOutConnectFailures, nas=nas, mdmHistCurrentInTotalBytesRx=mdmHistCurrentInTotalBytesRx, mdmNacHistIntervalWatchdogTimouts=mdmNacHistIntervalWatchdogTimouts, mdmHistCurrentInConnectFailures=mdmHistCurrentInConnectFailures, mdmNacHistCurrentIndex=mdmNacHistCurrentIndex, mdmHistIntervalNumber=mdmHistIntervalNumber, mdmHistCurrentStartTime=mdmHistCurrentStartTime, mdmHistIntervalOutConnectEstabs=mdmHistIntervalOutConnectEstabs, mdmNacHistCurrentEntry=mdmNacHistCurrentEntry, mdmNacHistIntervalTable=mdmNacHistIntervalTable, mdmHistIntervalOutConnectTime=mdmHistIntervalOutConnectTime, mdmNacHistCurrentStartTime=mdmNacHistCurrentStartTime, mdmHistCurrentFallBacks=mdmHistCurrentFallBacks, mdmHistIntervalFallBacks=mdmHistIntervalFallBacks, mdmNacHistCurrentTable=mdmNacHistCurrentTable, mdmHistCurrentOutConnectTerms=mdmHistCurrentOutConnectTerms, mdmHistCurrentIndex=mdmHistCurrentIndex, mdmHistCurrentInConnectTerms=mdmHistCurrentInConnectTerms, mdmHistCurrentInTotalBytesTx=mdmHistCurrentInTotalBytesTx, mdmHistIntervalInConnectTime=mdmHistIntervalInConnectTime, mdmHistIntervalIndex=mdmHistIntervalIndex, mdmNacHistCurrentMgmtBusFailures=mdmNacHistCurrentMgmtBusFailures, usr=usr, mdmNacHistIntervalNumber=mdmNacHistIntervalNumber, mdmNacHistIntervalStartTime=mdmNacHistIntervalStartTime, mdmHistIntervalInConnectEstabs=mdmHistIntervalInConnectEstabs, mdmHistIntervalInTotalBytesRx=mdmHistIntervalInTotalBytesRx, mdmHistIntervalOutConnectFailures=mdmHistIntervalOutConnectFailures, mdmHist=mdmHist, mdmHistIntervalOutConnectTerms=mdmHistIntervalOutConnectTerms, mdmHistIntervalEntry=mdmHistIntervalEntry, mdmNacHistIntervalEntry=mdmNacHistIntervalEntry, mdmNacHistIntervalIndex=mdmNacHistIntervalIndex)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_intersection, constraints_union, single_value_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (iso, time_ticks, gauge32, enterprises, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, unsigned32, integer32, counter32, object_identity, notification_type, mib_identifier, experimental, ip_address, counter64, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'TimeTicks', 'Gauge32', 'enterprises', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Unsigned32', 'Integer32', 'Counter32', 'ObjectIdentity', 'NotificationType', 'MibIdentifier', 'experimental', 'IpAddress', 'Counter64', 'Bits') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') usr = mib_identifier((1, 3, 6, 1, 4, 1, 429)) nas = mib_identifier((1, 3, 6, 1, 4, 1, 429, 1)) mdm_hist = mib_identifier((1, 3, 6, 1, 4, 1, 429, 1, 30)) mdm_nac_hist_current_table = mib_table((1, 3, 6, 1, 4, 1, 429, 1, 30, 1)) if mibBuilder.loadTexts: mdmNacHistCurrentTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentTable.setDescription('') mdm_nac_hist_current_entry = mib_table_row((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1)).setIndexNames((0, 'HIST-MIB', 'mdmNacHistCurrentIndex')) if mibBuilder.loadTexts: mdmNacHistCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentEntry.setDescription('Objects that define the history stats for NAC current interval.') mdm_nac_hist_current_index = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentIndex.setDescription('Index in to the Current NAC History table. This index contains a unique value for each card in the chassis.') mdm_nac_hist_current_start_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistCurrentStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentStartTime.setDescription('Specifies current interval start time in GMT.') mdm_nac_hist_current_mgmt_bus_failures = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistCurrentMgmtBusFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentMgmtBusFailures.setDescription('Specifies number of Management Bus Failures occurred in the NAC during current interval so for.') mdm_nac_hist_current_watchdog_timouts = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 1, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistCurrentWatchdogTimouts.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistCurrentWatchdogTimouts.setDescription('Specifies number of Watchdog Timeouts occurred in the NAC during current interval so for.') mdm_nac_hist_interval_table = mib_table((1, 3, 6, 1, 4, 1, 429, 1, 30, 2)) if mibBuilder.loadTexts: mdmNacHistIntervalTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalTable.setDescription('') mdm_nac_hist_interval_entry = mib_table_row((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1)).setIndexNames((0, 'HIST-MIB', 'mdmNacHistIntervalIndex'), (0, 'HIST-MIB', 'mdmNacHistIntervalNumber')) if mibBuilder.loadTexts: mdmNacHistIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalEntry.setDescription('Objects that define history stats for NAC intervals.') mdm_nac_hist_interval_index = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalIndex.setDescription('Index in to NAC Interval History table. This index contains a unique value for each card in the chassis.') mdm_nac_hist_interval_number = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 104))).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalNumber.setDescription('This object is the index for one of 104 possibel history intervals for this NAC.') mdm_nac_hist_interval_start_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistIntervalStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalStartTime.setDescription('Specifies interval start time in GMT.') mdm_nac_hist_interval_mgmt_bus_failures = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistIntervalMgmtBusFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalMgmtBusFailures.setDescription('Specifies number of Management Bus Failures occurred in the NAC during the interval.') mdm_nac_hist_interval_watchdog_timouts = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 2, 1, 5), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmNacHistIntervalWatchdogTimouts.setStatus('mandatory') if mibBuilder.loadTexts: mdmNacHistIntervalWatchdogTimouts.setDescription('Specifies number of Watchdog Timeouts occurred in the NAC during the interval.') mdm_hist_current_table = mib_table((1, 3, 6, 1, 4, 1, 429, 1, 30, 3)) if mibBuilder.loadTexts: mdmHistCurrentTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentTable.setDescription('') mdm_hist_current_entry = mib_table_row((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1)).setIndexNames((0, 'HIST-MIB', 'mdmHistCurrentIndex')) if mibBuilder.loadTexts: mdmHistCurrentEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentEntry.setDescription('Objects that define the history stats for modem current interval.') mdm_hist_current_index = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentIndex.setDescription('Index in to the Current modem history table. This index contains the unique value associated with the modem as defined in the chassis MIB entity table.') mdm_hist_current_start_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentStartTime.setDescription('Specifies current interval start time in GMT.') mdm_hist_current_in_connect_estabs = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 3), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentInConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectEstabs.setDescription('Specifies number of incoming calls established during current interval so for.') mdm_hist_current_in_connect_failures = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentInConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectFailures.setDescription('Specifies number of incoming call failures during current interval so for.') mdm_hist_current_in_connect_terms = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 5), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentInConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectTerms.setDescription('Specifies number of incoming calls terminated during current interval so for.') mdm_hist_current_in_connect_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 6), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentInConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInConnectTime.setDescription('Specifies length of all incoming calls during current interval so for.') mdm_hist_current_in_total_bytes_rx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 7), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesRx.setDescription('Specifies number of bytes received through incoming calls during current interval so for.') mdm_hist_current_in_total_bytes_tx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 8), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentInTotalBytesTx.setDescription('Specifies number of bytes sent out through incoming calls during current interval so for.') mdm_hist_current_out_connect_estabs = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 9), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentOutConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectEstabs.setDescription('Specifies number of outgoing calls established during current interval so for.') mdm_hist_current_out_connect_failures = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 10), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentOutConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectFailures.setDescription('Specifies number of outgoing call failures during current interval so for.') mdm_hist_current_out_connect_terms = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 11), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTerms.setDescription('Specifies number of outgoing calls terminated during current interval so for.') mdm_hist_current_out_connect_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 12), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutConnectTime.setDescription('Specifies length of all outgoing calls during current interval so for.') mdm_hist_current_out_total_bytes_rx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 13), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesRx.setDescription('Specifies number of bytes received through outgoing calls during current interval so for.') mdm_hist_current_out_total_bytes_tx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 14), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentOutTotalBytesTx.setDescription('Specifies number of bytes sent out through outgoing calls during current interval so for.') mdm_hist_current_blers = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 15), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentBlers.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentBlers.setDescription('Specifies number of block errors received during current interval so for.') mdm_hist_current_fall_backs = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 3, 1, 16), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistCurrentFallBacks.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistCurrentFallBacks.setDescription('Specifies number of link speed fallbacks occured during current interval so for.') mdm_hist_interval_table = mib_table((1, 3, 6, 1, 4, 1, 429, 1, 30, 4)) if mibBuilder.loadTexts: mdmHistIntervalTable.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalTable.setDescription('') mdm_hist_interval_entry = mib_table_row((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1)).setIndexNames((0, 'HIST-MIB', 'mdmHistIntervalIndex'), (0, 'HIST-MIB', 'mdmHistIntervalNumber')) if mibBuilder.loadTexts: mdmHistIntervalEntry.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalEntry.setDescription('Objects that define history stats for modem intervals.') mdm_hist_interval_index = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalIndex.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalIndex.setDescription('Index in to the interval History table. This index contains the unique value associated with the modem as defined in the chassis MIB entity table.') mdm_hist_interval_number = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 104))).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalNumber.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalNumber.setDescription('This object is the index for one of 104 possibel history intervals for this modem.') mdm_hist_interval_start_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalStartTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalStartTime.setDescription('Specifies interval start time in GMT.') mdm_hist_interval_in_connect_estabs = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 4), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalInConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectEstabs.setDescription('Specifies number of incoming calls established during the interval.') mdm_hist_interval_in_connect_failures = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 5), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalInConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectFailures.setDescription('Specifies number of incoming call failures during the interval.') mdm_hist_interval_in_connect_terms = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 6), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalInConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectTerms.setDescription('Specifies number of incoming calls terminated during the interval.') mdm_hist_interval_in_connect_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 7), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalInConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInConnectTime.setDescription('Specifies length of all incoming calls during the intervals.') mdm_hist_interval_in_total_bytes_rx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 8), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesRx.setDescription('Specifies number of bytes received through incoming calls during the interval.') mdm_hist_interval_in_total_bytes_tx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 9), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalInTotalBytesTx.setDescription('Specifies number of bytes sent out through incoming calls during the interval.') mdm_hist_interval_out_connect_estabs = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 10), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalOutConnectEstabs.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectEstabs.setDescription('Specifies number of outgoing calls established during the interval.') mdm_hist_interval_out_connect_failures = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 11), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalOutConnectFailures.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectFailures.setDescription('Specifies number of outgoing call failures during the interval.') mdm_hist_interval_out_connect_terms = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 12), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTerms.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTerms.setDescription('Specifies number of outgoing calls terminated during the interval.') mdm_hist_interval_out_connect_time = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 13), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTime.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutConnectTime.setDescription('Specifies length of all outgoing calls during the interval.') mdm_hist_interval_out_total_bytes_rx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 14), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesRx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesRx.setDescription('Specifies number of bytes received through outgoing calls during the interval.') mdm_hist_interval_out_total_bytes_tx = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 15), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesTx.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalOutTotalBytesTx.setDescription('Specifies number of bytes sent out through outgoing calls during the interval.') mdm_hist_interval_blers = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 16), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalBlers.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalBlers.setDescription('Specifies number of block errors received during the interval.') mdm_hist_interval_fall_backs = mib_table_column((1, 3, 6, 1, 4, 1, 429, 1, 30, 4, 1, 17), gauge32()).setMaxAccess('readonly') if mibBuilder.loadTexts: mdmHistIntervalFallBacks.setStatus('mandatory') if mibBuilder.loadTexts: mdmHistIntervalFallBacks.setDescription('Specifies number of link speed fallbacks occured during the interval.') mibBuilder.exportSymbols('HIST-MIB', mdmHistCurrentOutTotalBytesTx=mdmHistCurrentOutTotalBytesTx, mdmHistCurrentOutConnectEstabs=mdmHistCurrentOutConnectEstabs, mdmHistIntervalInConnectFailures=mdmHistIntervalInConnectFailures, mdmHistIntervalOutTotalBytesRx=mdmHistIntervalOutTotalBytesRx, mdmHistCurrentOutTotalBytesRx=mdmHistCurrentOutTotalBytesRx, mdmNacHistCurrentWatchdogTimouts=mdmNacHistCurrentWatchdogTimouts, mdmHistCurrentBlers=mdmHistCurrentBlers, mdmHistIntervalStartTime=mdmHistIntervalStartTime, mdmHistIntervalTable=mdmHistIntervalTable, mdmHistCurrentInConnectTime=mdmHistCurrentInConnectTime, mdmHistCurrentOutConnectTime=mdmHistCurrentOutConnectTime, mdmHistIntervalInTotalBytesTx=mdmHistIntervalInTotalBytesTx, mdmHistIntervalBlers=mdmHistIntervalBlers, mdmHistCurrentInConnectEstabs=mdmHistCurrentInConnectEstabs, mdmHistIntervalOutTotalBytesTx=mdmHistIntervalOutTotalBytesTx, mdmHistIntervalInConnectTerms=mdmHistIntervalInConnectTerms, mdmHistCurrentTable=mdmHistCurrentTable, mdmHistCurrentEntry=mdmHistCurrentEntry, mdmNacHistIntervalMgmtBusFailures=mdmNacHistIntervalMgmtBusFailures, mdmHistCurrentOutConnectFailures=mdmHistCurrentOutConnectFailures, nas=nas, mdmHistCurrentInTotalBytesRx=mdmHistCurrentInTotalBytesRx, mdmNacHistIntervalWatchdogTimouts=mdmNacHistIntervalWatchdogTimouts, mdmHistCurrentInConnectFailures=mdmHistCurrentInConnectFailures, mdmNacHistCurrentIndex=mdmNacHistCurrentIndex, mdmHistIntervalNumber=mdmHistIntervalNumber, mdmHistCurrentStartTime=mdmHistCurrentStartTime, mdmHistIntervalOutConnectEstabs=mdmHistIntervalOutConnectEstabs, mdmNacHistCurrentEntry=mdmNacHistCurrentEntry, mdmNacHistIntervalTable=mdmNacHistIntervalTable, mdmHistIntervalOutConnectTime=mdmHistIntervalOutConnectTime, mdmNacHistCurrentStartTime=mdmNacHistCurrentStartTime, mdmHistCurrentFallBacks=mdmHistCurrentFallBacks, mdmHistIntervalFallBacks=mdmHistIntervalFallBacks, mdmNacHistCurrentTable=mdmNacHistCurrentTable, mdmHistCurrentOutConnectTerms=mdmHistCurrentOutConnectTerms, mdmHistCurrentIndex=mdmHistCurrentIndex, mdmHistCurrentInConnectTerms=mdmHistCurrentInConnectTerms, mdmHistCurrentInTotalBytesTx=mdmHistCurrentInTotalBytesTx, mdmHistIntervalInConnectTime=mdmHistIntervalInConnectTime, mdmHistIntervalIndex=mdmHistIntervalIndex, mdmNacHistCurrentMgmtBusFailures=mdmNacHistCurrentMgmtBusFailures, usr=usr, mdmNacHistIntervalNumber=mdmNacHistIntervalNumber, mdmNacHistIntervalStartTime=mdmNacHistIntervalStartTime, mdmHistIntervalInConnectEstabs=mdmHistIntervalInConnectEstabs, mdmHistIntervalInTotalBytesRx=mdmHistIntervalInTotalBytesRx, mdmHistIntervalOutConnectFailures=mdmHistIntervalOutConnectFailures, mdmHist=mdmHist, mdmHistIntervalOutConnectTerms=mdmHistIntervalOutConnectTerms, mdmHistIntervalEntry=mdmHistIntervalEntry, mdmNacHistIntervalEntry=mdmNacHistIntervalEntry, mdmNacHistIntervalIndex=mdmNacHistIntervalIndex)
# ** CONTROL FLOW ** # IF, ELIF AND ELSE age = 21 if age >= 21: print("You can drive alone") elif age < 16: print("You are not allow to drive") else: print("You can drive with supervision") # FOR LOOPS # Iterate a List print("\nIterate a List:") my_list = [1, 2, 3, 4, 5] for item in my_list: print(item) # Iterate a Dictionary print("\nIterate a Dictionary:") my_dict = {"One": 1, "Two": 2, "Three": 3} for key in my_dict: print(key) # Print keys of the dictionary print(my_dict[key]) # Print the values # Iterate using Methods print("\nIterate using Methods:") for values in my_dict.values(): # Replace my_dict.keys to iterate keys print(values) # Iterate a Tuple - Tuple unpacking print("\nIterate Tuples:") my_pairs = [(1, 2), (3, 4), (5, 6)] # Tuples inside a list for item1, item2 in my_pairs: print(item1) print(item2) print("---") # WHILE LOOPS print("\nWhile Loops:") i = 1 while i < 5: print("i is: {}".format(i)) i += 1 # FOR AND RANGE print("\nFor and Range:") list_range = list(range(0, 20, 2)) # range(start, stop, step) print(list_range) for i in range(0, 20, 2): print(i) # Note: Range is a generator which save ton of memory # LIST COMPREHENSION print("\nList Comprehension:") x = [1, 2, 3, 4, 5] # Use List Comprehension to return items from x squares x_square = [item**2 for item in x] print(x_square)
age = 21 if age >= 21: print('You can drive alone') elif age < 16: print('You are not allow to drive') else: print('You can drive with supervision') print('\nIterate a List:') my_list = [1, 2, 3, 4, 5] for item in my_list: print(item) print('\nIterate a Dictionary:') my_dict = {'One': 1, 'Two': 2, 'Three': 3} for key in my_dict: print(key) print(my_dict[key]) print('\nIterate using Methods:') for values in my_dict.values(): print(values) print('\nIterate Tuples:') my_pairs = [(1, 2), (3, 4), (5, 6)] for (item1, item2) in my_pairs: print(item1) print(item2) print('---') print('\nWhile Loops:') i = 1 while i < 5: print('i is: {}'.format(i)) i += 1 print('\nFor and Range:') list_range = list(range(0, 20, 2)) print(list_range) for i in range(0, 20, 2): print(i) print('\nList Comprehension:') x = [1, 2, 3, 4, 5] x_square = [item ** 2 for item in x] print(x_square)
################################### # SOLUTION ################################### def no_boring_zeros(n): j = n if j <= 0: j = -j x = list(range(0,100)) z = [] for k in x: if j/(10**k) != int(j/(10**k)): z.append((j/(10**k))*10) if n < 0: return -max(z) if n == 0: return 0 else: return max(z)
def no_boring_zeros(n): j = n if j <= 0: j = -j x = list(range(0, 100)) z = [] for k in x: if j / 10 ** k != int(j / 10 ** k): z.append(j / 10 ** k * 10) if n < 0: return -max(z) if n == 0: return 0 else: return max(z)
x = [ 100, 100, 100, 100, 100 ] y = 100 s = 50 speed = [ 1, 2, 3, 4, 5 ] def setup(): size(640, 360, P2D) def draw(): global x, y, s, speed background(127) for i in range(0, len(x)): ellipse(x[i], y + (i * s), s, s) x[i] += speed[i] if x[i] > width or x[i] < 0: speed[i] *= -1
x = [100, 100, 100, 100, 100] y = 100 s = 50 speed = [1, 2, 3, 4, 5] def setup(): size(640, 360, P2D) def draw(): global x, y, s, speed background(127) for i in range(0, len(x)): ellipse(x[i], y + i * s, s, s) x[i] += speed[i] if x[i] > width or x[i] < 0: speed[i] *= -1
def mph2fps(mph): return mph*5280/3600 def myhello(): print("Konchi_wa")
def mph2fps(mph): return mph * 5280 / 3600 def myhello(): print('Konchi_wa')
aux=0 aux2=0 while True: string=list(map(str,input().split())) if string[0]=="ABEND":break elif string[0]=='SALIDA': aux+=int(string[1]) aux2+=1 else: aux-=int(string[1]) aux2-=1 print(aux) print(aux2)
aux = 0 aux2 = 0 while True: string = list(map(str, input().split())) if string[0] == 'ABEND': break elif string[0] == 'SALIDA': aux += int(string[1]) aux2 += 1 else: aux -= int(string[1]) aux2 -= 1 print(aux) print(aux2)
class Solution: def canMakeArithmeticProgression(self, arr: List[int]) -> bool: arr.sort() l1 = arr[0:(len(arr)-1)] l2 = arr[1:] diffs = [abs(i-j) for i,j in zip(l1, l2)] if len(set(diffs)) == 1: return True return False
class Solution: def can_make_arithmetic_progression(self, arr: List[int]) -> bool: arr.sort() l1 = arr[0:len(arr) - 1] l2 = arr[1:] diffs = [abs(i - j) for (i, j) in zip(l1, l2)] if len(set(diffs)) == 1: return True return False
class Flower: """A flower.""" def __init__(self, name, petals, price): """Create a new flower instance. name the name of the flower (e.g. 'Spanish Oyster') petals the number of petals exists (e.g. 50) price price of each flower (measured in euros) """ self._name = str(name) self.set_petals(petals) self.set_price(price) def set_name(self, name): self._name = str(name) def get_name(self): return self._name def set_petals(self, petals): try: self._petals = int(petals) except (TypeError, ValueError): print('set_petals(): could not parse "%s" to int().' % petals) def get_petals(self): return self._petals def set_price(self, price): try: self._price = float(price) except (TypeError, ValueError): print('set_price(): You should parse "%s" to float().' % price) def get_price(self): return self._price if __name__ == '__main__': rose = Flower('Rose', 60, 1.3) print('%s contains %d petals costs %.2f euros.' % \ (rose.get_name(), rose.get_petals(), rose.get_price())) """Example with error.""" rose.set_petals('error')
class Flower: """A flower.""" def __init__(self, name, petals, price): """Create a new flower instance. name the name of the flower (e.g. 'Spanish Oyster') petals the number of petals exists (e.g. 50) price price of each flower (measured in euros) """ self._name = str(name) self.set_petals(petals) self.set_price(price) def set_name(self, name): self._name = str(name) def get_name(self): return self._name def set_petals(self, petals): try: self._petals = int(petals) except (TypeError, ValueError): print('set_petals(): could not parse "%s" to int().' % petals) def get_petals(self): return self._petals def set_price(self, price): try: self._price = float(price) except (TypeError, ValueError): print('set_price(): You should parse "%s" to float().' % price) def get_price(self): return self._price if __name__ == '__main__': rose = flower('Rose', 60, 1.3) print('%s contains %d petals costs %.2f euros.' % (rose.get_name(), rose.get_petals(), rose.get_price())) 'Example with error.' rose.set_petals('error')
class LanguageUtility: LANGUAGES = { "C": ("h",), "Clojure": ("clj",), "C++": ("cpp", "hpp", "h++",), "Crystal": ("cr",), "C#": ("cs", "csharp",), "CSS": (), "D": (), "Go": ("golang",), "HTML": ("htm",), "Java": (), "JavaScript": ("ecma", "ecmascript", "es", "js"), "Julia": (), "Less": (), "Lua": (), "Nim": (), "PHP": (), "Python": ("py",), "R": (), "Ruby": ("rb",), "Rust": ("rs",), "Sass": ("scss",), "Scala": ("sc",), "SQL": (), "Swift": (), "TypeScript": ("ts",), } @staticmethod async def resolve(language_string): for language, aliases in LanguageUtility.LANGUAGES.items(): if language_string.lower() in map(lambda x: x.lower(), (language, *aliases)): return language
class Languageutility: languages = {'C': ('h',), 'Clojure': ('clj',), 'C++': ('cpp', 'hpp', 'h++'), 'Crystal': ('cr',), 'C#': ('cs', 'csharp'), 'CSS': (), 'D': (), 'Go': ('golang',), 'HTML': ('htm',), 'Java': (), 'JavaScript': ('ecma', 'ecmascript', 'es', 'js'), 'Julia': (), 'Less': (), 'Lua': (), 'Nim': (), 'PHP': (), 'Python': ('py',), 'R': (), 'Ruby': ('rb',), 'Rust': ('rs',), 'Sass': ('scss',), 'Scala': ('sc',), 'SQL': (), 'Swift': (), 'TypeScript': ('ts',)} @staticmethod async def resolve(language_string): for (language, aliases) in LanguageUtility.LANGUAGES.items(): if language_string.lower() in map(lambda x: x.lower(), (language, *aliases)): return language
# Recursion # Base Case: n < 2, return lst # Otherwise: # Divide list into 2, Sort each of them, Merge! def merge(left, right): # Compare first element # Take the smaller of the 2 # Repeat until no more elements results = [] while left and right: if left[0] < right[0]: results.append(left.pop(0)) else: results.append(right.pop(0)) results.extend(right) results.extend(left) return results def merge_sort(lst): if (len(lst) < 2): return lst mid = len(lst) // 2 left = merge_sort(lst[:mid]) # sort left right = merge_sort(lst[mid:]) # sort right return merge(left, right) print(merge_sort([2, 1, 99]))
def merge(left, right): results = [] while left and right: if left[0] < right[0]: results.append(left.pop(0)) else: results.append(right.pop(0)) results.extend(right) results.extend(left) return results def merge_sort(lst): if len(lst) < 2: return lst mid = len(lst) // 2 left = merge_sort(lst[:mid]) right = merge_sort(lst[mid:]) return merge(left, right) print(merge_sort([2, 1, 99]))
__about__ = "Maximum no in a binary tree." class Node: def __init__(self, data): self.data = data self.left = None self.right= None class Tree: @staticmethod def insert(root = None,data = None): if root is None and data is not None: root = Node(data)
__about__ = 'Maximum no in a binary tree.' class Node: def __init__(self, data): self.data = data self.left = None self.right = None class Tree: @staticmethod def insert(root=None, data=None): if root is None and data is not None: root = node(data)
E, F, C = map(int, input().split()) bottles = E + F drank = 0 while bottles >= C: # while he still has enough empty bottles to purchase more bottles -= C - 1 # used F empty bottles to buy 1 drank += 1 print(drank)
(e, f, c) = map(int, input().split()) bottles = E + F drank = 0 while bottles >= C: bottles -= C - 1 drank += 1 print(drank)
NOTES = { 'C3': 130.8, 'CS3': 138.6, 'DF3': 138.6, 'D3': 146.8, 'DS3': 155.6, 'EF3': 155.6, 'E3': 164.8, 'F3': 174.6, 'FS3': 185.0, 'GF3': 185.0, 'G3': 196.0, 'GS3': 207.7, 'AF3': 207.7, 'A3': 220.0, 'AS3': 233.1, 'BF3': 233.1, 'B3': 246.9, 'C4': 261.6, 'CS4': 277.2, 'DF4': 277.2, 'D4': 293.7, 'DS4': 311.1, 'EF4': 311.1, 'E4': 329.6, 'F4': 349.2, 'FS4': 370.0, 'GF4': 370.0, 'G4': 392.0, 'GS4': 415.3, 'AF4': 415.3, 'A4': 440.0, 'AS4': 466.2, 'BF4': 466.2, 'B4': 493.9, 'C5': 523.3, 'CS5': 554.4, 'DF5': 554.4, 'D5': 587.3, 'DS5': 622.3, 'EF5': 622.3, 'E5': 659.3, 'F5': 698.5, 'FS5': 740.0, 'GF5': 740.0, 'G5': 784.0, 'GS5': 830.6, 'AF5': 830.6, 'A5': 880.0, 'AS5': 932.3, 'BF5': 932.3, 'B5': 987.8, }
notes = {'C3': 130.8, 'CS3': 138.6, 'DF3': 138.6, 'D3': 146.8, 'DS3': 155.6, 'EF3': 155.6, 'E3': 164.8, 'F3': 174.6, 'FS3': 185.0, 'GF3': 185.0, 'G3': 196.0, 'GS3': 207.7, 'AF3': 207.7, 'A3': 220.0, 'AS3': 233.1, 'BF3': 233.1, 'B3': 246.9, 'C4': 261.6, 'CS4': 277.2, 'DF4': 277.2, 'D4': 293.7, 'DS4': 311.1, 'EF4': 311.1, 'E4': 329.6, 'F4': 349.2, 'FS4': 370.0, 'GF4': 370.0, 'G4': 392.0, 'GS4': 415.3, 'AF4': 415.3, 'A4': 440.0, 'AS4': 466.2, 'BF4': 466.2, 'B4': 493.9, 'C5': 523.3, 'CS5': 554.4, 'DF5': 554.4, 'D5': 587.3, 'DS5': 622.3, 'EF5': 622.3, 'E5': 659.3, 'F5': 698.5, 'FS5': 740.0, 'GF5': 740.0, 'G5': 784.0, 'GS5': 830.6, 'AF5': 830.6, 'A5': 880.0, 'AS5': 932.3, 'BF5': 932.3, 'B5': 987.8}
# -*- coding: utf-8 -*- class HelloWorldController: __defaultName = None def __init__(self): self.__defaultName = "Pip User" def configure(self, config): self.__defaultName = config.get_as_string_with_default("default_name", self.__defaultName) def greeting(self, name): return f"Hello, {name if name else self.__defaultName} !"
class Helloworldcontroller: __default_name = None def __init__(self): self.__defaultName = 'Pip User' def configure(self, config): self.__defaultName = config.get_as_string_with_default('default_name', self.__defaultName) def greeting(self, name): return f'Hello, {(name if name else self.__defaultName)} !'
edge_array = [0,100,-1,-30,130,-150,-1,-1,-1,10,10,-120,-10,160,-180,0,10,-180,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,120,-120,-100,30,-200,30,30,-200,20,30,-200,30,220,-230,40,20,-220,0,50,-30,-200,30,-30,30,30,-200,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,60,-160,-10,130,-190,0,40,-200,-1,0,-200,-50,30,-250,5,-50,-250,-1,80,-30,-50,30,-100,0,30,-200,-1,100,-130,-1,30,-50,-30,50,0,-1,30,-200,10,250,-250,0,-50,-250,-1,30,-30,-200,-250,-130,0,-30,250,-1,70,-150,-1,100,-130,-70,30,-200,-1,-30,-200,-1,30,30,0,30,-70,-1,30,-200,-250,0,-120,0,-30,-250,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,200,0,-1,230,-30,-1,220,-30,-1,150,-20,-1,250,-80,-1,100,-100,-1,220,30,-1,220,50,-1,200,-80,-1,-1,-30,-1,30,-30,-1,50,-50,-1,30,-50,-1,180,0,-1,30,0,-1,100,0,-1,30,0,-1,0,-30,-1,-1,0,-1,180,0,-1,180,0,-1,-1,0,-1,100,10,-1,0,0,-1,180,0,-1,120,10,-1,120,-100,-1,-1,30,-1,200,0,-1,180,0,-1,-1,0,-1,120,0,-1,100,0,-1,-1,50,-1,120,0,-1,120,-30,-1,-1,0,-1,-1,50,-1,120,30,-1,-1,100,-1,300,150,-1,200,80,-1,-1,50,-1,200,50,-1,140,0,-1,-1,80,-1,-1,0,-1,120,0,-1,-1,0,-1,-1,50,-1,140,0,-1,-1,0,-1,120,0,-1,100,-60,-1,-1,30,-1,-1,0,-1,220,10,-1,-1,0,-1,-1,0,-1,0,0,-1,-1,30,-1,-1,0,-1,50,30,-1,-1,-30,-1,-1,0,-1,-1,-10,-1,-1,-30,-1,-1,50,-1,120,0,-1,-1,0,-1,-1,0,-1,100,-60,-1,-1,50,-1,-1,0,-1,-1,0,-1,-1,-10,-1,-1,0,-1,-1,-50,-1,-1,10,-1,-1,-50,-1,0,-100,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-300] par =[0,0,0,0,0,0] i = 0 par2 =[0,0,0,0,0,0] for par[0] in range(0,3): for par[1] in range(0,3): for par[2] in range(0,3): for par[3] in range(0,3): for par[4] in range(0,3): for par[5] in range(0,3): index = par[0]+par[1]*3+par[2]*9+par[3]*27+par[4]*81+par[5]*243 if (index > i and index < 728): try: edge_array[index] = edge_array[i] except ValueError: pass j = 0 for par_each in par: if (par_each == 1): par2[j] = 2 elif (par_each == 2): par2[j] = 1 else: par2[j] = 0 j += 1 index2 = par2[0]*243+par2[1]*81+par2[2]*27+par2[3]*9+par2[4]*3+par2[5] if (index2 > i and index2 < 728): try: edge_array[index2] = -1 * edge_array[i] except ValueError: pass i += 1 print(edge_array) print(len(edge_array))
edge_array = [0, 100, -1, -30, 130, -150, -1, -1, -1, 10, 10, -120, -10, 160, -180, 0, 10, -180, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 120, -120, -100, 30, -200, 30, 30, -200, 20, 30, -200, 30, 220, -230, 40, 20, -220, 0, 50, -30, -200, 30, -30, 30, 30, -200, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 60, -160, -10, 130, -190, 0, 40, -200, -1, 0, -200, -50, 30, -250, 5, -50, -250, -1, 80, -30, -50, 30, -100, 0, 30, -200, -1, 100, -130, -1, 30, -50, -30, 50, 0, -1, 30, -200, 10, 250, -250, 0, -50, -250, -1, 30, -30, -200, -250, -130, 0, -30, 250, -1, 70, -150, -1, 100, -130, -70, 30, -200, -1, -30, -200, -1, 30, 30, 0, 30, -70, -1, 30, -200, -250, 0, -120, 0, -30, -250, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 200, 0, -1, 230, -30, -1, 220, -30, -1, 150, -20, -1, 250, -80, -1, 100, -100, -1, 220, 30, -1, 220, 50, -1, 200, -80, -1, -1, -30, -1, 30, -30, -1, 50, -50, -1, 30, -50, -1, 180, 0, -1, 30, 0, -1, 100, 0, -1, 30, 0, -1, 0, -30, -1, -1, 0, -1, 180, 0, -1, 180, 0, -1, -1, 0, -1, 100, 10, -1, 0, 0, -1, 180, 0, -1, 120, 10, -1, 120, -100, -1, -1, 30, -1, 200, 0, -1, 180, 0, -1, -1, 0, -1, 120, 0, -1, 100, 0, -1, -1, 50, -1, 120, 0, -1, 120, -30, -1, -1, 0, -1, -1, 50, -1, 120, 30, -1, -1, 100, -1, 300, 150, -1, 200, 80, -1, -1, 50, -1, 200, 50, -1, 140, 0, -1, -1, 80, -1, -1, 0, -1, 120, 0, -1, -1, 0, -1, -1, 50, -1, 140, 0, -1, -1, 0, -1, 120, 0, -1, 100, -60, -1, -1, 30, -1, -1, 0, -1, 220, 10, -1, -1, 0, -1, -1, 0, -1, 0, 0, -1, -1, 30, -1, -1, 0, -1, 50, 30, -1, -1, -30, -1, -1, 0, -1, -1, -10, -1, -1, -30, -1, -1, 50, -1, 120, 0, -1, -1, 0, -1, -1, 0, -1, 100, -60, -1, -1, 50, -1, -1, 0, -1, -1, 0, -1, -1, -10, -1, -1, 0, -1, -1, -50, -1, -1, 10, -1, -1, -50, -1, 0, -100, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -300] par = [0, 0, 0, 0, 0, 0] i = 0 par2 = [0, 0, 0, 0, 0, 0] for par[0] in range(0, 3): for par[1] in range(0, 3): for par[2] in range(0, 3): for par[3] in range(0, 3): for par[4] in range(0, 3): for par[5] in range(0, 3): index = par[0] + par[1] * 3 + par[2] * 9 + par[3] * 27 + par[4] * 81 + par[5] * 243 if index > i and index < 728: try: edge_array[index] = edge_array[i] except ValueError: pass j = 0 for par_each in par: if par_each == 1: par2[j] = 2 elif par_each == 2: par2[j] = 1 else: par2[j] = 0 j += 1 index2 = par2[0] * 243 + par2[1] * 81 + par2[2] * 27 + par2[3] * 9 + par2[4] * 3 + par2[5] if index2 > i and index2 < 728: try: edge_array[index2] = -1 * edge_array[i] except ValueError: pass i += 1 print(edge_array) print(len(edge_array))
class LoginResponse: def __init__( self, access_token: str, fresh_token: str, token_type: str = "bearer" ): self.access_token = access_token self.fresh_token = fresh_token self.token_type = token_type def json(self): return dict( access_token=self.access_token, fresh_token=self.fresh_token, token_type=self.token_type )
class Loginresponse: def __init__(self, access_token: str, fresh_token: str, token_type: str='bearer'): self.access_token = access_token self.fresh_token = fresh_token self.token_type = token_type def json(self): return dict(access_token=self.access_token, fresh_token=self.fresh_token, token_type=self.token_type)
# Iterating Through Dictionaries contacts = {"Daisy Johnson": "2468 Park Ave", "Leo Fitz": "1258 Monkey Dr"} # iterate through each key for name in contacts: print(name) # or, use keys() method for name in contacts.keys(): print(name) # using each key to print each value for name in contacts: # prints each address associated with each name print(contacts[name]) # iterate through each value using values() for address in contacts.values(): print(address) # iterate through keys and values using items() for name, address in contacts.items(): print(name + ", " + address)
contacts = {'Daisy Johnson': '2468 Park Ave', 'Leo Fitz': '1258 Monkey Dr'} for name in contacts: print(name) for name in contacts.keys(): print(name) for name in contacts: print(contacts[name]) for address in contacts.values(): print(address) for (name, address) in contacts.items(): print(name + ', ' + address)
to_do_list = ["0"] * 10 while True: command = input().split("-", maxsplit=1) if "End" in command: break to_do_list.insert(int(command[0]), command[1]) while "0" in to_do_list: to_do_list.remove("0") print(to_do_list)
to_do_list = ['0'] * 10 while True: command = input().split('-', maxsplit=1) if 'End' in command: break to_do_list.insert(int(command[0]), command[1]) while '0' in to_do_list: to_do_list.remove('0') print(to_do_list)
N = int(input()) data = open("{}.txt".format(N), 'r') data = data.readline() data = [int(i) for i in data.split()] def parr(array): for i in array: print('{:4d}'.format(i), end=" ") def insertionsort(x): for i in range(1, len(x)): j = i - 1; key = x[i] while(x[j] > key and j>= 0): x[j+1] = x[j] j = j-1 x[j+1] = key parr(x); print() parr(data); print() insertionsort(data) parr(data); print()
n = int(input()) data = open('{}.txt'.format(N), 'r') data = data.readline() data = [int(i) for i in data.split()] def parr(array): for i in array: print('{:4d}'.format(i), end=' ') def insertionsort(x): for i in range(1, len(x)): j = i - 1 key = x[i] while x[j] > key and j >= 0: x[j + 1] = x[j] j = j - 1 x[j + 1] = key parr(x) print() parr(data) print() insertionsort(data) parr(data) print()
def resolve(): n = int(input()) for i in range(1, n + 1): if i % 3 == 0 or "3" in str(i): print(" {}".format(i), end="") print()
def resolve(): n = int(input()) for i in range(1, n + 1): if i % 3 == 0 or '3' in str(i): print(' {}'.format(i), end='') print()
''' Make a 3x3 matrix and fill with numbers at the end show the matrix in a right format ''' cr = [[],[],[]] for c in range(0,3): cr[0].append(int(input(f'First line [1, {c+1}]: '))) for c in range(0,3): cr[1].append(int(input(f'Second line [2, {c+1}]: '))) for c in range(0,3): cr[2].append(int(input(f'Third line [3, {c+1}]: '))) print(f'''The matrix is:\n{cr[0]}\n{cr[1]}\n{cr[2]}''')
""" Make a 3x3 matrix and fill with numbers at the end show the matrix in a right format """ cr = [[], [], []] for c in range(0, 3): cr[0].append(int(input(f'First line [1, {c + 1}]: '))) for c in range(0, 3): cr[1].append(int(input(f'Second line [2, {c + 1}]: '))) for c in range(0, 3): cr[2].append(int(input(f'Third line [3, {c + 1}]: '))) print(f'The matrix is:\n{cr[0]}\n{cr[1]}\n{cr[2]}')
load( "@io_bazel_rules_dotnet//dotnet/private:context.bzl", "dotnet_context", ) load( "@io_bazel_rules_dotnet//dotnet/private:providers.bzl", "DotnetLibrary", ) load( "@io_bazel_rules_dotnet//dotnet/private:common.bzl", "paths", ) def _dotnet_nuget_impl(ctx, build_file = None, build_file_content = None): """dotnet_nuget_impl emits actions for exposing nunit assmebly.""" package = ctx.attr.package output_dir = ctx.path("") url = ctx.attr.source + "/" + ctx.attr.package + "/" + ctx.attr.version ctx.download_and_extract(url, output_dir, ctx.attr.sha256, type="zip") if build_file_content: ctx.file("BUILD", build_file_content) elif build_file: ctx.symlink(ctx.path(build_file), "BUILD") else: ctx.template("BUILD.bazel", Label("@io_bazel_rules_dotnet//dotnet/private:BUILD.nuget.bazel"), executable = False, ) dotnet_nuget = repository_rule( _dotnet_nuget_impl, attrs = { # Sources to download the nuget packages from "source":attr.string(default = "https://www.nuget.org/api/v2/package"), # The name of the nuget package "package":attr.string(mandatory=True), # The version of the nuget package "version":attr.string(mandatory=True), "sha256":attr.string(mandatory=True), }, ) def _dotnet_nuget_new_impl(repository_ctx): build_file = repository_ctx.attr.build_file build_file_content = repository_ctx.attr.build_file_content if not (build_file_content or build_file): fail("build_file or build_file_content is required") _dotnet_nuget_impl(repository_ctx, build_file, build_file_content) dotnet_nuget_new = repository_rule( _dotnet_nuget_new_impl, attrs = { # Sources to download the nuget packages from "source":attr.string(default = "https://www.nuget.org/api/v2/package"), # The name of the nuget package "package":attr.string(mandatory=True), # The version of the nuget package "version":attr.string(mandatory=True), "sha256":attr.string(mandatory=True), "build_file": attr.label( allow_files = True, ), "build_file_content": attr.string(), }, )
load('@io_bazel_rules_dotnet//dotnet/private:context.bzl', 'dotnet_context') load('@io_bazel_rules_dotnet//dotnet/private:providers.bzl', 'DotnetLibrary') load('@io_bazel_rules_dotnet//dotnet/private:common.bzl', 'paths') def _dotnet_nuget_impl(ctx, build_file=None, build_file_content=None): """dotnet_nuget_impl emits actions for exposing nunit assmebly.""" package = ctx.attr.package output_dir = ctx.path('') url = ctx.attr.source + '/' + ctx.attr.package + '/' + ctx.attr.version ctx.download_and_extract(url, output_dir, ctx.attr.sha256, type='zip') if build_file_content: ctx.file('BUILD', build_file_content) elif build_file: ctx.symlink(ctx.path(build_file), 'BUILD') else: ctx.template('BUILD.bazel', label('@io_bazel_rules_dotnet//dotnet/private:BUILD.nuget.bazel'), executable=False) dotnet_nuget = repository_rule(_dotnet_nuget_impl, attrs={'source': attr.string(default='https://www.nuget.org/api/v2/package'), 'package': attr.string(mandatory=True), 'version': attr.string(mandatory=True), 'sha256': attr.string(mandatory=True)}) def _dotnet_nuget_new_impl(repository_ctx): build_file = repository_ctx.attr.build_file build_file_content = repository_ctx.attr.build_file_content if not (build_file_content or build_file): fail('build_file or build_file_content is required') _dotnet_nuget_impl(repository_ctx, build_file, build_file_content) dotnet_nuget_new = repository_rule(_dotnet_nuget_new_impl, attrs={'source': attr.string(default='https://www.nuget.org/api/v2/package'), 'package': attr.string(mandatory=True), 'version': attr.string(mandatory=True), 'sha256': attr.string(mandatory=True), 'build_file': attr.label(allow_files=True), 'build_file_content': attr.string()})
n = int(input()) for i in range(n): x = int(input()) print(len(bin(x)) - 2)
n = int(input()) for i in range(n): x = int(input()) print(len(bin(x)) - 2)
"""NA (Non-Available) values in R.""" NA_Character = None NA_Integer = None NA_Logical = None NA_Real = None NA_Complex = None
"""NA (Non-Available) values in R.""" na__character = None na__integer = None na__logical = None na__real = None na__complex = None
''' The class derived from more than 1 base called as a Multiple Inheritence. Programmer_name : BALAVIGNESH.M Implemented_Date : 11-11-2018 ''' class OS: SecurityOS = "Linux" DeveloperlikeOS = "Mac OS" Most_Personal_usage_OS = "Windows" class KernerlType: SecurityOS_Kernel = "MonoLithic Kernel" DeveloperlikeOS_Kernel = "XNU Kernel" Most_Personal_usage_OS_Kernel = "Hybrid Kernel" class OSINFO(OS,KernerlType): def __init__(self): self.SecurityOS_Owner = "Linus Tarvolds & maintained By Linux Foundation" self.DeveloperlikeOS_Owner = "Steve Jobs & Apple Inc." self.Most_Personal_usage_OS_Owner = "Bill Gates & Microsoft" def GetOSInfo(self): print("Most powerful Security OS is: {x}.\n Using Kernel Type: {y} .\n Developer & Owned Company is: {z}".format( x= self.SecurityOS , y = self.SecurityOS_Kernel , z = self.SecurityOS_Owner )) print() print("Most Developer and Trending OS is: {x}. \n Using Kernel Type: {y}.\n Developer & Owned Company is: {z}".format( x = self.DeveloperlikeOS , y = self.DeveloperlikeOS_Kernel , z = self.DeveloperlikeOS_Owner )) print() print("Favourite & number 1 Most user personal usage OS: {x}.\n Using Kernel Type: {y}.\n Developer & Owned Company is:{z} ".format( x = self.Most_Personal_usage_OS , y = self.Most_Personal_usage_OS_Kernel , z = self.Most_Personal_usage_OS_Owner )) osinfo = OSINFO() osinfo.GetOSInfo()
""" The class derived from more than 1 base called as a Multiple Inheritence. Programmer_name : BALAVIGNESH.M Implemented_Date : 11-11-2018 """ class Os: security_os = 'Linux' developerlike_os = 'Mac OS' most__personal_usage_os = 'Windows' class Kernerltype: security_os__kernel = 'MonoLithic Kernel' developerlike_os__kernel = 'XNU Kernel' most__personal_usage_os__kernel = 'Hybrid Kernel' class Osinfo(OS, KernerlType): def __init__(self): self.SecurityOS_Owner = 'Linus Tarvolds & maintained By Linux Foundation' self.DeveloperlikeOS_Owner = 'Steve Jobs & Apple Inc.' self.Most_Personal_usage_OS_Owner = 'Bill Gates & Microsoft' def get_os_info(self): print('Most powerful Security OS is: {x}.\n Using Kernel Type: {y} .\n Developer & Owned Company is: {z}'.format(x=self.SecurityOS, y=self.SecurityOS_Kernel, z=self.SecurityOS_Owner)) print() print('Most Developer and Trending OS is: {x}. \n Using Kernel Type: {y}.\n Developer & Owned Company is: {z}'.format(x=self.DeveloperlikeOS, y=self.DeveloperlikeOS_Kernel, z=self.DeveloperlikeOS_Owner)) print() print('Favourite & number 1 Most user personal usage OS: {x}.\n Using Kernel Type: {y}.\n Developer & Owned Company is:{z} '.format(x=self.Most_Personal_usage_OS, y=self.Most_Personal_usage_OS_Kernel, z=self.Most_Personal_usage_OS_Owner)) osinfo = osinfo() osinfo.GetOSInfo()
class RecentCounter: def __init__(self): self.queue = [] def ping(self, t: int) -> int: self.queue.append(t) if len(self.queue) > 3001: self.queue.pop(0) start = 0 for idx, item in enumerate(self.queue): if item >= t-3000: start = idx break return len(self.queue[start:]) # Your RecentCounter object will be instantiated and called as such: # obj = RecentCounter() # param_1 = obj.ping(t)
class Recentcounter: def __init__(self): self.queue = [] def ping(self, t: int) -> int: self.queue.append(t) if len(self.queue) > 3001: self.queue.pop(0) start = 0 for (idx, item) in enumerate(self.queue): if item >= t - 3000: start = idx break return len(self.queue[start:])
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ # sort the list in descending order quicksort(input_list) # fill max with digits at the odd indices of sorted list number_1 = 0 for i in range(0, len(input_list), 2): number_1 = number_1 * 10 + input_list[i] # fill y with digits at the even indices of sorted list number_2 = 0 for i in range(1, len(input_list), 2): number_2 = number_2 * 10 + input_list[i] # print x and y print("The two numbers with maximum sum are", number_1, "and", number_2) return [number_1, number_2] def sort_a_little_bit(items, begin_index, end_index): left_index = begin_index pivot_index = end_index pivot_value = items[pivot_index] while pivot_index != left_index: item = items[left_index] if item >= pivot_value: left_index += 1 continue items[left_index] = items[pivot_index - 1] items[pivot_index - 1] = pivot_value items[pivot_index] = item pivot_index -= 1 return pivot_index def sort_all(items, begin_index, end_index): if end_index <= begin_index: return pivot_index = sort_a_little_bit(items, begin_index, end_index) sort_all(items, begin_index, pivot_index - 1) sort_all(items, pivot_index + 1, end_index) def quicksort(items): return sort_all(items, 0, len(items) - 1) def test_function(test_case): output = rearrange_digits(test_case[0]) solution = test_case[1] if sum(output) == sum(solution): print("Pass") else: print("Fail") test_function([[1, 2, 3, 4, 5], [542, 31]]) # pass test_case = [[4, 6, 2, 5, 9, 8], [964, 852]] test_function(test_case) # pass test_case = [[4, 1], [4, 1]] test_function(test_case) # pass test_case = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], [97531, 86420]] test_function(test_case) # pass test_case = [[0, 0], [0, 0]] test_function(test_case) # pass
def rearrange_digits(input_list): """ Rearrange Array Elements so as to form two number such that their sum is maximum. Args: input_list(list): Input List Returns: (int),(int): Two maximum sums """ quicksort(input_list) number_1 = 0 for i in range(0, len(input_list), 2): number_1 = number_1 * 10 + input_list[i] number_2 = 0 for i in range(1, len(input_list), 2): number_2 = number_2 * 10 + input_list[i] print('The two numbers with maximum sum are', number_1, 'and', number_2) return [number_1, number_2] def sort_a_little_bit(items, begin_index, end_index): left_index = begin_index pivot_index = end_index pivot_value = items[pivot_index] while pivot_index != left_index: item = items[left_index] if item >= pivot_value: left_index += 1 continue items[left_index] = items[pivot_index - 1] items[pivot_index - 1] = pivot_value items[pivot_index] = item pivot_index -= 1 return pivot_index def sort_all(items, begin_index, end_index): if end_index <= begin_index: return pivot_index = sort_a_little_bit(items, begin_index, end_index) sort_all(items, begin_index, pivot_index - 1) sort_all(items, pivot_index + 1, end_index) def quicksort(items): return sort_all(items, 0, len(items) - 1) def test_function(test_case): output = rearrange_digits(test_case[0]) solution = test_case[1] if sum(output) == sum(solution): print('Pass') else: print('Fail') test_function([[1, 2, 3, 4, 5], [542, 31]]) test_case = [[4, 6, 2, 5, 9, 8], [964, 852]] test_function(test_case) test_case = [[4, 1], [4, 1]] test_function(test_case) test_case = [[1, 2, 3, 4, 5, 6, 7, 8, 9, 0], [97531, 86420]] test_function(test_case) test_case = [[0, 0], [0, 0]] test_function(test_case)
#!/bin/python3 n,k = input().strip().split(' ') n,k = [int(n),int(k)] height = list(map(int, input().strip().split(' '))) max_height = max(height) if max_height - k >= 1: print (max_height-k) else: print (0)
(n, k) = input().strip().split(' ') (n, k) = [int(n), int(k)] height = list(map(int, input().strip().split(' '))) max_height = max(height) if max_height - k >= 1: print(max_height - k) else: print(0)
#!/usr/local/bin/python3 s1 = "floor" s2 = "brake" print(s1) for i in range(len(s1)): if s1[i] != s2[i]: print(s2[:i+1] + s1[i+1:])
s1 = 'floor' s2 = 'brake' print(s1) for i in range(len(s1)): if s1[i] != s2[i]: print(s2[:i + 1] + s1[i + 1:])
def solve() -> None: # person whose strength is i can only carry parcels whose weight is less than or equal to i. # check in descending order of degree of freedom of remained parcels. a = [0] + list(map(int, input().split())) b = [0] + list(map(int, input().split())) # for i in range(1, 6): # strength # 5 -> 4 -> 3 -> 2 -> 1 if a[5] > b[5]: print("No") return b[5] -= a[5] a[5] = 0 if a[4] <= b[4]: b[4] -= a[4] a[4] = 0 else: a[4] -= b[4] b[4] = 0 if a[4] > b[5]: print("No") return b[5] -= a[4] b[1] += a[4] a[4] = 0 b[3] += b[5] b[2] += b[5] b[5] = 0 if a[3] <= b[3]: b[3] -= a[3] a[3] = 0 else: a[3] -= b[3] b[3] = 0 if a[3] > b[4]: print("No") return b[4] -= a[3] b[1] += a[3] a[3] = 0 b[2] += b[4] * 2 b[4] = 0 if a[2] <= b[2]: b[2] -= a[2] a[2] = 0 else: a[2] -= b[2] b[2] = 0 if a[2] > b[3]: print("No") return b[3] -= a[2] b[1] += a[2] a[2] = 0 b[1] += b[3] * 3 b[3] = 0 b[1] += b[2] * 2 b[2] = 0 if a[1] <= b[1]: print("Yes") else: print("No") def main() -> None: t = int(input()) for _ in range(t): solve() if __name__ == "__main__": main()
def solve() -> None: a = [0] + list(map(int, input().split())) b = [0] + list(map(int, input().split())) if a[5] > b[5]: print('No') return b[5] -= a[5] a[5] = 0 if a[4] <= b[4]: b[4] -= a[4] a[4] = 0 else: a[4] -= b[4] b[4] = 0 if a[4] > b[5]: print('No') return b[5] -= a[4] b[1] += a[4] a[4] = 0 b[3] += b[5] b[2] += b[5] b[5] = 0 if a[3] <= b[3]: b[3] -= a[3] a[3] = 0 else: a[3] -= b[3] b[3] = 0 if a[3] > b[4]: print('No') return b[4] -= a[3] b[1] += a[3] a[3] = 0 b[2] += b[4] * 2 b[4] = 0 if a[2] <= b[2]: b[2] -= a[2] a[2] = 0 else: a[2] -= b[2] b[2] = 0 if a[2] > b[3]: print('No') return b[3] -= a[2] b[1] += a[2] a[2] = 0 b[1] += b[3] * 3 b[3] = 0 b[1] += b[2] * 2 b[2] = 0 if a[1] <= b[1]: print('Yes') else: print('No') def main() -> None: t = int(input()) for _ in range(t): solve() if __name__ == '__main__': main()
class WayPoint: code = None state = None location = None coordinate = None def __init__(self, code=None, state=None, location=None, coordinate=None): self.code = code self.state = state self.location = location self.coordinate = coordinate if self.code is None and self.coordinate is None: raise ValueError("Either code or coordinate must be set.") def __str__(self): return "Code: %s,\tState: %s, \tCoordinate: %s\tLocation: %s" % \ (self.code, self.state, self.coordinate, self.location) def get_waypoint(self): if self.code: return self.code return str(self.coordinate)
class Waypoint: code = None state = None location = None coordinate = None def __init__(self, code=None, state=None, location=None, coordinate=None): self.code = code self.state = state self.location = location self.coordinate = coordinate if self.code is None and self.coordinate is None: raise value_error('Either code or coordinate must be set.') def __str__(self): return 'Code: %s,\tState: %s, \tCoordinate: %s\tLocation: %s' % (self.code, self.state, self.coordinate, self.location) def get_waypoint(self): if self.code: return self.code return str(self.coordinate)
class Solution: def constructFromPrePost(self, pre: List[int], post: List[int]) -> TreeNode: if not pre: return None if len(pre) == 1: return TreeNode(pre[0]) lroot = post.index(pre[1]) l = self.constructFromPrePost(pre[1:lroot+2], post[:lroot+1]) r = self.constructFromPrePost(pre[lroot+2:], post[lroot+1:-1]) return TreeNode(pre[0], l, r)
class Solution: def construct_from_pre_post(self, pre: List[int], post: List[int]) -> TreeNode: if not pre: return None if len(pre) == 1: return tree_node(pre[0]) lroot = post.index(pre[1]) l = self.constructFromPrePost(pre[1:lroot + 2], post[:lroot + 1]) r = self.constructFromPrePost(pre[lroot + 2:], post[lroot + 1:-1]) return tree_node(pre[0], l, r)
BIGINT = "BIGINT" NUMERIC = "NUMERIC" NUMBER = "NUMBER" BIT = "BIT" SMALLINT = "SMALLINT" DECIMAL = "DECIMAL" SMALLMONEY = "SMALLMONEY" INT = "INT" TINYINT = "TINYINT" MONEY = "MONEY" FLOAT = "FLOAT" REAL = "REAL" DATE = "DATE" DATETIMEOFFSET = "DATETIMEOFFSET" DATETIME2 = "DATETIME2" SMALLDATETIME = "SMALLDATETIME" DATETIME = "DATETIME" TIME = "TIME" CHAR = "CHAR" VARCHAR = "VARCHAR" TEXT = "TEXT" NCHAR = "NCHAR" NVARCHAR = "NVARCHAR" NTEXT = "NTEXT" BINARY = "BINARY" VARBINARY = "VARBINARY" IMAGE = "IMAGE" CURSOR = "CURSOR" TIMESTAMP = "TIMESTAMP" HIERARCHYID = "HIERARCHYID" UNIQUEIDENTIFIER = "UNIQUEIDENTIFIER" SQL_VARIANT = "SQL_VARIANT" XML = "XML" TABLE = "TABLE" SPATIAL_TYPES = "SPATIAL TYPES" CHARACTER = "CHARACTER" BOOLEAN = "BOOLEAN" INTEGER = "INTEGER" DOUBLE_PRECISION = "DOUBLE PRECISION" INTERVAL = "INTERVAL" ARRAY = "ARRAY" MULTISET = "MULTISET" CLOB = "CLOB" BLOB = "BLOB" SERIAL = "SERIAL" IDENTITY = "IDENTITY" DOUBLE = "DOUBLE" OTHER = "OTHER" UUID = "UUID" GEOMETRY = "GEOMETRY" STRING = "STRING" UNKNOWN = "UNKNOWN"
bigint = 'BIGINT' numeric = 'NUMERIC' number = 'NUMBER' bit = 'BIT' smallint = 'SMALLINT' decimal = 'DECIMAL' smallmoney = 'SMALLMONEY' int = 'INT' tinyint = 'TINYINT' money = 'MONEY' float = 'FLOAT' real = 'REAL' date = 'DATE' datetimeoffset = 'DATETIMEOFFSET' datetime2 = 'DATETIME2' smalldatetime = 'SMALLDATETIME' datetime = 'DATETIME' time = 'TIME' char = 'CHAR' varchar = 'VARCHAR' text = 'TEXT' nchar = 'NCHAR' nvarchar = 'NVARCHAR' ntext = 'NTEXT' binary = 'BINARY' varbinary = 'VARBINARY' image = 'IMAGE' cursor = 'CURSOR' timestamp = 'TIMESTAMP' hierarchyid = 'HIERARCHYID' uniqueidentifier = 'UNIQUEIDENTIFIER' sql_variant = 'SQL_VARIANT' xml = 'XML' table = 'TABLE' spatial_types = 'SPATIAL TYPES' character = 'CHARACTER' boolean = 'BOOLEAN' integer = 'INTEGER' double_precision = 'DOUBLE PRECISION' interval = 'INTERVAL' array = 'ARRAY' multiset = 'MULTISET' clob = 'CLOB' blob = 'BLOB' serial = 'SERIAL' identity = 'IDENTITY' double = 'DOUBLE' other = 'OTHER' uuid = 'UUID' geometry = 'GEOMETRY' string = 'STRING' unknown = 'UNKNOWN'
class Solution(object): def uniquePathsIII(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 R = len(grid) C = len(grid[0]) ans = 0 zero_count = 0 extra_count = 0 points = [(-1, 0), (0, -1), (0, 1), (1, 0)] def is_valid(x, y): return 0 <= x < R and 0 <= y < C and grid[x][y] != -1 def dfs(x, y, ans, temp_zero): for i, j in points: r, c = x+i, y+j if is_valid(r,c) and grid[r][c] == 0: temp_zero += 1 grid[r][c] = -2 ans = dfs(r, c, ans, temp_zero) grid[r][c] = 0 if grid[r][c] == -2 else grid[r][c] temp_zero -= 1 elif is_valid(r,c) and grid[r][c] == 2: if temp_zero == zero_count: ans += 1 return ans for x in xrange(R): for y in xrange(C): if grid[x][y] == 1: start_point = (x, y) elif grid[x][y] == 0: zero_count += 1 else: extra_count += 1 ans = dfs(start_point[0], start_point[1], ans, 0) return (ans) abc = Solution() abc.uniquePathsIII([[0,1],[2,0]])
class Solution(object): def unique_paths_iii(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid or not grid[0]: return 0 r = len(grid) c = len(grid[0]) ans = 0 zero_count = 0 extra_count = 0 points = [(-1, 0), (0, -1), (0, 1), (1, 0)] def is_valid(x, y): return 0 <= x < R and 0 <= y < C and (grid[x][y] != -1) def dfs(x, y, ans, temp_zero): for (i, j) in points: (r, c) = (x + i, y + j) if is_valid(r, c) and grid[r][c] == 0: temp_zero += 1 grid[r][c] = -2 ans = dfs(r, c, ans, temp_zero) grid[r][c] = 0 if grid[r][c] == -2 else grid[r][c] temp_zero -= 1 elif is_valid(r, c) and grid[r][c] == 2: if temp_zero == zero_count: ans += 1 return ans for x in xrange(R): for y in xrange(C): if grid[x][y] == 1: start_point = (x, y) elif grid[x][y] == 0: zero_count += 1 else: extra_count += 1 ans = dfs(start_point[0], start_point[1], ans, 0) return ans abc = solution() abc.uniquePathsIII([[0, 1], [2, 0]])
xCoordinate = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30] def setup(): size(500,500) smooth() noStroke() myInit() def myInit(): println ("New coordinates : ") for i in range(len(xCoordinate)): xCoordinate [i] = 250 + random ( -100 ,100) println ( xCoordinate [i]) def draw(): background(30) for i in range(len(xCoordinate)): fill(20) ellipse(xCoordinate[i], 250, 5, 5) fill(250,40) ellipse(xCoordinate[i], 250, 10*i,10*i) if (mouseX>250): myInit() def keyPressed(): if (key == 's'): saveFrame("Photo")
x_coordinate = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30] def setup(): size(500, 500) smooth() no_stroke() my_init() def my_init(): println('New coordinates : ') for i in range(len(xCoordinate)): xCoordinate[i] = 250 + random(-100, 100) println(xCoordinate[i]) def draw(): background(30) for i in range(len(xCoordinate)): fill(20) ellipse(xCoordinate[i], 250, 5, 5) fill(250, 40) ellipse(xCoordinate[i], 250, 10 * i, 10 * i) if mouseX > 250: my_init() def key_pressed(): if key == 's': save_frame('Photo')