content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Contact: def __init__(self, first_name, last_name, nickname, address, mobile, email): self.first_name = first_name self.last_name = last_name self.nickname = nickname self.address = address self.mobile = mobile self.email = email
class Contact: def __init__(self, first_name, last_name, nickname, address, mobile, email): self.first_name = first_name self.last_name = last_name self.nickname = nickname self.address = address self.mobile = mobile self.email = email
count = int(input()) title = 0 while count > 0: title += 1 if '666' in str(title): count -= 1 print(title)
count = int(input()) title = 0 while count > 0: title += 1 if '666' in str(title): count -= 1 print(title)
#!/usr/bin/env python3 USER = r'server\user' PASSWORD = 'server_password' HOSTNAME = 'hostname.goes.here.com' DOMAIN = 'domain.goes.here.com' FROM_ADDR = 'emailyouwanttosendmessagesfrom@something.com'
user = 'server\\user' password = 'server_password' hostname = 'hostname.goes.here.com' domain = 'domain.goes.here.com' from_addr = 'emailyouwanttosendmessagesfrom@something.com'
def createKafkaSecurityGroup(ec2, vpc): sec_group_kafka = ec2.create_security_group( GroupName='kafka', Description='kafka sec group', VpcId=vpc.id) sec_group_kafka.authorize_ingress( IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 9092, 'ToPort': 9092, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}] ) print(sec_group_kafka.id) return sec_group_kafka def createZookeeperSecurityGroup(ec2, vpc): sec_group_zookeeper = ec2.create_security_group( GroupName='zookeeper', Description='zookeeper', VpcId=vpc.id) sec_group_zookeeper.authorize_ingress( IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 2181, 'ToPort': 2181, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 2888, 'ToPort': 2888, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 3888, 'ToPort': 3888, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}] ) print(sec_group_zookeeper.id) return sec_group_zookeeper def create_redis_security_group(ec2, vpc): sec_group_redis = ec2.create_security_group( GroupName='redis', Description='redis', VpcId=vpc.id) sec_group_redis.authorize_ingress( IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 6379, 'ToPort': 6379, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}] ) print(sec_group_redis.id) return sec_group_redis
def create_kafka_security_group(ec2, vpc): sec_group_kafka = ec2.create_security_group(GroupName='kafka', Description='kafka sec group', VpcId=vpc.id) sec_group_kafka.authorize_ingress(IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 9092, 'ToPort': 9092, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}]) print(sec_group_kafka.id) return sec_group_kafka def create_zookeeper_security_group(ec2, vpc): sec_group_zookeeper = ec2.create_security_group(GroupName='zookeeper', Description='zookeeper', VpcId=vpc.id) sec_group_zookeeper.authorize_ingress(IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 2181, 'ToPort': 2181, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 2888, 'ToPort': 2888, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 3888, 'ToPort': 3888, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}]) print(sec_group_zookeeper.id) return sec_group_zookeeper def create_redis_security_group(ec2, vpc): sec_group_redis = ec2.create_security_group(GroupName='redis', Description='redis', VpcId=vpc.id) sec_group_redis.authorize_ingress(IpPermissions=[{'IpProtocol': 'icmp', 'FromPort': -1, 'ToPort': -1, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 22, 'ToPort': 22, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}, {'IpProtocol': 'tcp', 'FromPort': 6379, 'ToPort': 6379, 'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}]) print(sec_group_redis.id) return sec_group_redis
# STRAND SORT # It is a recursive comparison based sorting technique which sorts in increasing order. # It works by repeatedly pulling sorted sub-lists out of the list to be sorted and merging them # with a result array. # Algorithm: # Create a empty strand (list) and append the first element to it popping it from the input array # Compare this element with the rest of elements of the input array # if a greater element is found then pop and append it to strand otherwise skip # Now merge this array to the final output array # Recur for remaining items in strand and input array. # Utility Function to merge two arrays def merge(arr1, arr2): # list to store merged output merged_list = [] # while there are elements in both arrays while len(arr1) and len(arr2): # the array having smaller first elements gets appended as the resultant array must be sorted if arr1[0] < arr2[0]: merged_list.append(arr1.pop(0)) else: merged_list.append(arr2.pop(0)) # if the length of either of array is exhausted , merge the remaining part to # the merge sublist merged_list += arr1 merged_list += arr2 # return the merged list return merged_list # Function to return the strand (sorted sub-list) def strand(arr): # append the first element to the strand s = [arr.pop(0)] # initialise a pointer i = 0 # while it is less then length while i > len(arr): # compare the input array elements to the last element of the strand if arr[i] > s[-1]: # if we found a greater element than s[-1] then pop it and append to the strand s.append(arr.pop(i)) else: # else increment i += 1 # return the strand return s # Strand Sort Function def strand_sort(arr): # initialise the output array with the strand output = strand(arr) # while there are elements in the array while len(arr): # merge the strand and previous output list to create a new list output = merge(output, strand(arr)) # return the sorted output return output # Driver Code arr = [1, 6, 3, 8, 2, 0, 9] print(strand_sort(arr)) # Time Complexity : O(n^2) [Worst] # O(n*log(n)) [Average] # Space Complexity : O(n) # Stable : Yes # Inplace : No
def merge(arr1, arr2): merged_list = [] while len(arr1) and len(arr2): if arr1[0] < arr2[0]: merged_list.append(arr1.pop(0)) else: merged_list.append(arr2.pop(0)) merged_list += arr1 merged_list += arr2 return merged_list def strand(arr): s = [arr.pop(0)] i = 0 while i > len(arr): if arr[i] > s[-1]: s.append(arr.pop(i)) else: i += 1 return s def strand_sort(arr): output = strand(arr) while len(arr): output = merge(output, strand(arr)) return output arr = [1, 6, 3, 8, 2, 0, 9] print(strand_sort(arr))
class Proceso: def __init__(self,tiempo_de_llegada,t,id): self.t=t self.tiempo_de_llegada=tiempo_de_llegada self.id=id self.inicio=0 self.fin=0 self.T=0 self.E=0 self.P=0 self.tRestantes = t
class Proceso: def __init__(self, tiempo_de_llegada, t, id): self.t = t self.tiempo_de_llegada = tiempo_de_llegada self.id = id self.inicio = 0 self.fin = 0 self.T = 0 self.E = 0 self.P = 0 self.tRestantes = t
# Time: sum(O(l * 2^l) for l in range(1, 11)) = O(20 * 2^10) = O(1) # Space: O(1) class Solution(object): def findInteger(self, k, digit1, digit2): """ :type k: int :type digit1: int :type digit2: int :rtype: int """ MAX_NUM_OF_DIGITS = 10 INT_MAX = 2**31-1 if digit1 < digit2: digit1, digit2 = digit2, digit1 total = 2 for l in xrange(1, MAX_NUM_OF_DIGITS+1): for mask in xrange(total): curr, bit = 0, total>>1 while bit: curr = curr*10 + (digit1 if mask&bit else digit2) bit >>= 1 if k < curr <= INT_MAX and curr%k == 0: return curr total <<= 1 return -1
class Solution(object): def find_integer(self, k, digit1, digit2): """ :type k: int :type digit1: int :type digit2: int :rtype: int """ max_num_of_digits = 10 int_max = 2 ** 31 - 1 if digit1 < digit2: (digit1, digit2) = (digit2, digit1) total = 2 for l in xrange(1, MAX_NUM_OF_DIGITS + 1): for mask in xrange(total): (curr, bit) = (0, total >> 1) while bit: curr = curr * 10 + (digit1 if mask & bit else digit2) bit >>= 1 if k < curr <= INT_MAX and curr % k == 0: return curr total <<= 1 return -1
def test_add_contact(app, db, json_contacts, check_ui): contact = json_contacts list_before = db.get_contact_list() contact.id_contact = app.contact.get_next_id(list_before) app.contact.create(contact) assert len(list_before) + 1 == len(db.get_contact_list()) list_after = db.get_contact_list() list_before.append(contact) assert sorted(list_before) == sorted(list_after) if check_ui: assert sorted(list_after) == sorted(app.contact.get_list())
def test_add_contact(app, db, json_contacts, check_ui): contact = json_contacts list_before = db.get_contact_list() contact.id_contact = app.contact.get_next_id(list_before) app.contact.create(contact) assert len(list_before) + 1 == len(db.get_contact_list()) list_after = db.get_contact_list() list_before.append(contact) assert sorted(list_before) == sorted(list_after) if check_ui: assert sorted(list_after) == sorted(app.contact.get_list())
# solution 1: Brute Force # time complexity: O(n^2) # space complexity: O(1) def twoNumberSum(arr, n): for i in range(len(arr) - 1): firstNum = arr[i] for j in range(i + 1, len(arr)): secondNum = arr[j] if firstNum + secondNum == n: return [firstNum, secondNum] return [] print(twoNumberSum([3,5,-4,8,11,1,-1,6], 10))
def two_number_sum(arr, n): for i in range(len(arr) - 1): first_num = arr[i] for j in range(i + 1, len(arr)): second_num = arr[j] if firstNum + secondNum == n: return [firstNum, secondNum] return [] print(two_number_sum([3, 5, -4, 8, 11, 1, -1, 6], 10))
class InvalidMovementException(Exception): pass class InvalidMovementTargetException(InvalidMovementException): pass class InvalidMovimentOriginException(InvalidMovementException): pass
class Invalidmovementexception(Exception): pass class Invalidmovementtargetexception(InvalidMovementException): pass class Invalidmovimentoriginexception(InvalidMovementException): pass
FORM_CONTENT_TYPES = [ 'application/x-www-form-urlencoded', 'multipart/form-data' ]
form_content_types = ['application/x-www-form-urlencoded', 'multipart/form-data']
""" Simulation parameters. """ SIMULATION_TIME_STEPS = 300
""" Simulation parameters. """ simulation_time_steps = 300
def numb_of_char(a): d = {} for char in set(a): d[char] = a.count(char) return d a = numb_of_char(str(input("Input the word please: "))) print(a)
def numb_of_char(a): d = {} for char in set(a): d[char] = a.count(char) return d a = numb_of_char(str(input('Input the word please: '))) print(a)
class Vector2D: def __init__(self, v: List[List[int]]): def getIt(): for row in v: for val in row: yield val self.it = iter(getIt()) self.val = next(self.it, None) def next(self) -> int: result = self.val self.val = next(self.it, None) return result def hasNext(self) -> bool: return self.val is not None # Your Vector2D object will be instantiated and called as such: # obj = Vector2D(v) # param_1 = obj.next() # param_2 = obj.hasNext()
class Vector2D: def __init__(self, v: List[List[int]]): def get_it(): for row in v: for val in row: yield val self.it = iter(get_it()) self.val = next(self.it, None) def next(self) -> int: result = self.val self.val = next(self.it, None) return result def has_next(self) -> bool: return self.val is not None
def plot_3D_Data( self, *arg_list, is_norm=False, unit="SI", component_list=None, save_path=None, x_min=None, x_max=None, y_min=None, y_max=None, z_min=None, z_max=None, z_range=None, is_auto_ticks=True, is_auto_range=False, is_2D_view=False, is_same_size=False, N_stem=100, fig=None, ax=None, is_show_fig=None, is_logscale_x=False, is_logscale_y=False, is_logscale_z=False, thresh=0.02, is_switch_axes=False, colormap="RdBu_r", win_title=None, font_name="arial", font_size_title=12, font_size_label=10, font_size_legend=8, ): """Plots a field as a function of time Parameters ---------- self : Output an Output object Data_str : str name of the Data Object to plot (e.g. "mag.Br") *arg_list : list of str arguments to specify which axes to plot is_norm : bool boolean indicating if the field must be normalized unit : str unit in which to plot the field save_path : str full path including folder, name and extension of the file to save if save_path is not None x_min : float minimum value for the x-axis x_max : float maximum value for the x-axis y_min : float minimum value for the y-axis y_max : float maximum value for the y-axis z_min : float minimum value for the z-axis z_max : float maximum value for the z-axis is_auto_ticks : bool in fft, adjust ticks to freqs (deactivate if too close) is_auto_range : bool in fft, display up to 1% of max is_2D_view : bool True to plot Data in xy plane and put z as colormap is_same_size : bool True to have all color blocks with same size in 2D view N_stem : int number of harmonics to plot (only for stem plots) fig : Matplotlib.figure.Figure existing figure to use if None create a new one ax : Matplotlib.axes.Axes object ax on which to plot the data is_show_fig : bool True to show figure after plot is_logscale_x : bool boolean indicating if the x-axis must be set in logarithmic scale is_logscale_y : bool boolean indicating if the y-axis must be set in logarithmic scale is_logscale_z : bool boolean indicating if the z-axis must be set in logarithmic scale thresh : float threshold for automatic fft ticks is_switch_axes : bool to switch x and y axes """ # Call the plot on each component if component_list is None: # default: extract all components component_list = self.components.keys() for i, comp in enumerate(component_list): if save_path is not None and len(component_list) > 1: save_path_comp = ( save_path.split(".")[0] + "_" + comp + "." + save_path.split(".")[1] ) else: save_path_comp = save_path self.components[comp].plot_3D_Data( arg_list, is_norm=is_norm, unit=unit, save_path=save_path_comp, x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, z_min=z_min, z_max=z_max, colormap=colormap, is_auto_ticks=is_auto_ticks, is_auto_range=is_auto_range, is_2D_view=is_2D_view, is_same_size=is_same_size, N_stem=N_stem, fig=fig, ax=ax, is_show_fig=is_show_fig, is_logscale_x=is_logscale_x, is_logscale_y=is_logscale_y, is_logscale_z=is_logscale_z, thresh=thresh, is_switch_axes=is_switch_axes, win_title=win_title, font_name=font_name, font_size_title=font_size_title, font_size_label=font_size_label, font_size_legend=font_size_legend, )
def plot_3_d__data(self, *arg_list, is_norm=False, unit='SI', component_list=None, save_path=None, x_min=None, x_max=None, y_min=None, y_max=None, z_min=None, z_max=None, z_range=None, is_auto_ticks=True, is_auto_range=False, is_2D_view=False, is_same_size=False, N_stem=100, fig=None, ax=None, is_show_fig=None, is_logscale_x=False, is_logscale_y=False, is_logscale_z=False, thresh=0.02, is_switch_axes=False, colormap='RdBu_r', win_title=None, font_name='arial', font_size_title=12, font_size_label=10, font_size_legend=8): """Plots a field as a function of time Parameters ---------- self : Output an Output object Data_str : str name of the Data Object to plot (e.g. "mag.Br") *arg_list : list of str arguments to specify which axes to plot is_norm : bool boolean indicating if the field must be normalized unit : str unit in which to plot the field save_path : str full path including folder, name and extension of the file to save if save_path is not None x_min : float minimum value for the x-axis x_max : float maximum value for the x-axis y_min : float minimum value for the y-axis y_max : float maximum value for the y-axis z_min : float minimum value for the z-axis z_max : float maximum value for the z-axis is_auto_ticks : bool in fft, adjust ticks to freqs (deactivate if too close) is_auto_range : bool in fft, display up to 1% of max is_2D_view : bool True to plot Data in xy plane and put z as colormap is_same_size : bool True to have all color blocks with same size in 2D view N_stem : int number of harmonics to plot (only for stem plots) fig : Matplotlib.figure.Figure existing figure to use if None create a new one ax : Matplotlib.axes.Axes object ax on which to plot the data is_show_fig : bool True to show figure after plot is_logscale_x : bool boolean indicating if the x-axis must be set in logarithmic scale is_logscale_y : bool boolean indicating if the y-axis must be set in logarithmic scale is_logscale_z : bool boolean indicating if the z-axis must be set in logarithmic scale thresh : float threshold for automatic fft ticks is_switch_axes : bool to switch x and y axes """ if component_list is None: component_list = self.components.keys() for (i, comp) in enumerate(component_list): if save_path is not None and len(component_list) > 1: save_path_comp = save_path.split('.')[0] + '_' + comp + '.' + save_path.split('.')[1] else: save_path_comp = save_path self.components[comp].plot_3D_Data(arg_list, is_norm=is_norm, unit=unit, save_path=save_path_comp, x_min=x_min, x_max=x_max, y_min=y_min, y_max=y_max, z_min=z_min, z_max=z_max, colormap=colormap, is_auto_ticks=is_auto_ticks, is_auto_range=is_auto_range, is_2D_view=is_2D_view, is_same_size=is_same_size, N_stem=N_stem, fig=fig, ax=ax, is_show_fig=is_show_fig, is_logscale_x=is_logscale_x, is_logscale_y=is_logscale_y, is_logscale_z=is_logscale_z, thresh=thresh, is_switch_axes=is_switch_axes, win_title=win_title, font_name=font_name, font_size_title=font_size_title, font_size_label=font_size_label, font_size_legend=font_size_legend)
def elo(winner_rank, loser_rank, weighting): """ :param winner: The Player that won the match. :param loser: The Player that lost the match. :param weighting: The weighting factor to suit your comp. :return: (winner_new_rank, loser_new_rank) Tuple. This follows the ELO ranking method. """ winner_rank_transformed = 10 ** (winner_rank / 400) opponent_rank_transformed = 10 ** (loser_rank / 400) transformed_sum = winner_rank_transformed + opponent_rank_transformed winner_score = winner_rank_transformed / transformed_sum loser_score = opponent_rank_transformed / transformed_sum winner_rank = winner_rank + weighting * ( 1 - winner_score) loser_rank = loser_rank - weighting * loser_score # Set a floor of 100 for the rankings. winner_rank = 100 if winner_rank < 100 else winner_rank loser_rank = 100 if loser_rank < 100 else loser_rank winner_rank = float('{result:.2f}'.format(result=winner_rank)) loser_rank = float('{result:.2f}'.format(result=loser_rank)) return winner_rank, loser_rank
def elo(winner_rank, loser_rank, weighting): """ :param winner: The Player that won the match. :param loser: The Player that lost the match. :param weighting: The weighting factor to suit your comp. :return: (winner_new_rank, loser_new_rank) Tuple. This follows the ELO ranking method. """ winner_rank_transformed = 10 ** (winner_rank / 400) opponent_rank_transformed = 10 ** (loser_rank / 400) transformed_sum = winner_rank_transformed + opponent_rank_transformed winner_score = winner_rank_transformed / transformed_sum loser_score = opponent_rank_transformed / transformed_sum winner_rank = winner_rank + weighting * (1 - winner_score) loser_rank = loser_rank - weighting * loser_score winner_rank = 100 if winner_rank < 100 else winner_rank loser_rank = 100 if loser_rank < 100 else loser_rank winner_rank = float('{result:.2f}'.format(result=winner_rank)) loser_rank = float('{result:.2f}'.format(result=loser_rank)) return (winner_rank, loser_rank)
n = int(input()) line = list(map(int, input().split())) l = {} res = "" for i, j in enumerate(line): l[j] = i+1 for k in range(n): res += str(l[k+1]) + " " print(res.rstrip())
n = int(input()) line = list(map(int, input().split())) l = {} res = '' for (i, j) in enumerate(line): l[j] = i + 1 for k in range(n): res += str(l[k + 1]) + ' ' print(res.rstrip())
valor = int(input()) for i in range(valor+1): if(i%2 != 0): print(i)
valor = int(input()) for i in range(valor + 1): if i % 2 != 0: print(i)
# https://leetcode.com/problems/delete-and-earn/ class Solution: def deleteAndEarn(self, nums: list[int]) -> int: num_profits = dict() for num in nums: num_profits[num] = num_profits.get(num, 0) + num sorted_nums = sorted(num_profits.keys()) second_last_profit = 0 last_profit = num_profits[sorted_nums[0]] for idx in range(1, len(sorted_nums)): profit_with_curr_num = num_profits[sorted_nums[idx]] if sorted_nums[idx - 1] == sorted_nums[idx] - 1: curr_profit = max(last_profit, second_last_profit + profit_with_curr_num) else: curr_profit = last_profit + profit_with_curr_num second_last_profit, last_profit = last_profit, curr_profit return last_profit
class Solution: def delete_and_earn(self, nums: list[int]) -> int: num_profits = dict() for num in nums: num_profits[num] = num_profits.get(num, 0) + num sorted_nums = sorted(num_profits.keys()) second_last_profit = 0 last_profit = num_profits[sorted_nums[0]] for idx in range(1, len(sorted_nums)): profit_with_curr_num = num_profits[sorted_nums[idx]] if sorted_nums[idx - 1] == sorted_nums[idx] - 1: curr_profit = max(last_profit, second_last_profit + profit_with_curr_num) else: curr_profit = last_profit + profit_with_curr_num (second_last_profit, last_profit) = (last_profit, curr_profit) return last_profit
class BaseStorage(object): def get_rule(self, name): raise NotImplementedError() def get_ruleset(self, name): raise NotImplementedError()
class Basestorage(object): def get_rule(self, name): raise not_implemented_error() def get_ruleset(self, name): raise not_implemented_error()
class Solution: # dictionary keys are tuples, storing results # structure of the tuple: # (level, prev_sum, val_to_include) # value is number of successful tuples def fourSumCount(self, A, B, C, D, prev_sum=0, level=0, sums={}): """ :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int """ # handle clearing dictionary between tests sums = {} if level == 3 else sums # base case: if level == 3: total = 0 for num in D: if prev_sum + num == 0: print("At level 3, 0 total found using entry w/ value {0}". format(num)) total += 1 return total total = 0 lists = [A, B, C] for num in lists[level]: if level == 0: print(str(sums)) if (level, prev_sum, num) in sums: total += sums[(level, prev_sum, num)] print("Used dictionary entry {0}, making total {1}". format((level, prev_sum, num), total)) else: print("Call from level {0} to level {1}; current sum is {2}". format(level, level + 1, prev_sum + num)) result = self.fourSumCount(A, B, C, D, prev_sum + num, level + 1, sums) sums[(level, prev_sum, num)] = result total += result if level == 0: sums = {} print(sums) return total sol = Solution() A = [1] B = [-1] C = [0] D = [1] result = sol.fourSumCount(A, B, C, D) print("Test 1: {0}".format(result)) A = [1, 2] B = [-2, -1] C = [-1, 2] D = [0, 2] result = sol.fourSumCount(A, B, C, D) print("Test 2: {0}".format(result))
class Solution: def four_sum_count(self, A, B, C, D, prev_sum=0, level=0, sums={}): """ :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int """ sums = {} if level == 3 else sums if level == 3: total = 0 for num in D: if prev_sum + num == 0: print('At level 3, 0 total found using entry w/ value {0}'.format(num)) total += 1 return total total = 0 lists = [A, B, C] for num in lists[level]: if level == 0: print(str(sums)) if (level, prev_sum, num) in sums: total += sums[level, prev_sum, num] print('Used dictionary entry {0}, making total {1}'.format((level, prev_sum, num), total)) else: print('Call from level {0} to level {1}; current sum is {2}'.format(level, level + 1, prev_sum + num)) result = self.fourSumCount(A, B, C, D, prev_sum + num, level + 1, sums) sums[level, prev_sum, num] = result total += result if level == 0: sums = {} print(sums) return total sol = solution() a = [1] b = [-1] c = [0] d = [1] result = sol.fourSumCount(A, B, C, D) print('Test 1: {0}'.format(result)) a = [1, 2] b = [-2, -1] c = [-1, 2] d = [0, 2] result = sol.fourSumCount(A, B, C, D) print('Test 2: {0}'.format(result))
# https://projecteuler.net/problem=19 def is_leap(year): if year%4 != 0: return False if year%100 == 0 and year%400 != 0: return False return True def year_days(year): if is_leap(year): return 366 return 365 def month_days(month, year): if month == 4 or month == 6 or month == 9 or month == 11: return 30 if month == 2: if is_leap(year): return 29 return 28 return 31 day_19000101 = 1 days_1900 = year_days(1900) day_next_day1 = (day_19000101 + days_1900)%7 print(day_19000101, days_1900, day_next_day1) sum = 0 for i in range(1901, 2001): for j in range(1, 13): if day_next_day1 == 0: print(i, j) sum = sum + 1 days = month_days(j, i) day_next_day1 = (day_next_day1 + days)%7 #print(i, j, days, day_next_day1) print(sum)
def is_leap(year): if year % 4 != 0: return False if year % 100 == 0 and year % 400 != 0: return False return True def year_days(year): if is_leap(year): return 366 return 365 def month_days(month, year): if month == 4 or month == 6 or month == 9 or (month == 11): return 30 if month == 2: if is_leap(year): return 29 return 28 return 31 day_19000101 = 1 days_1900 = year_days(1900) day_next_day1 = (day_19000101 + days_1900) % 7 print(day_19000101, days_1900, day_next_day1) sum = 0 for i in range(1901, 2001): for j in range(1, 13): if day_next_day1 == 0: print(i, j) sum = sum + 1 days = month_days(j, i) day_next_day1 = (day_next_day1 + days) % 7 print(sum)
class Config: ngram = 2 train_set = "data/rmrb.txt" modified_train_set = "data/rmrb_modified.txt" test_set = "" model_file = "" param_file = "" word_max_len = 10 proposals_keep_ratio = 1.0 use_re = 1 subseq_num = 15
class Config: ngram = 2 train_set = 'data/rmrb.txt' modified_train_set = 'data/rmrb_modified.txt' test_set = '' model_file = '' param_file = '' word_max_len = 10 proposals_keep_ratio = 1.0 use_re = 1 subseq_num = 15
def execucoes(): return int(input()) def entradas(): return input().split(' ') def imprimir(v): print(v) def tamanho_a(a): return len(a) def tamanho_b(b): return len(b) def diferenca_tamanhos(a, b): return (len(a) <= len(b)) def analisar(e, i, s): a, b = e if(diferenca_tamanhos(a, b)): for i in range(tamanho_a(a)): s += a[i] s += b[i] s += b[tamanho_a(a):] else: for i in range(tamanho_b(b)): s += a[i] s += b[i] s += a[tamanho_b(b):] return s def combinador(): n = execucoes() for i in range(n): imprimir(analisar(entradas(), i, '')) combinador()
def execucoes(): return int(input()) def entradas(): return input().split(' ') def imprimir(v): print(v) def tamanho_a(a): return len(a) def tamanho_b(b): return len(b) def diferenca_tamanhos(a, b): return len(a) <= len(b) def analisar(e, i, s): (a, b) = e if diferenca_tamanhos(a, b): for i in range(tamanho_a(a)): s += a[i] s += b[i] s += b[tamanho_a(a):] else: for i in range(tamanho_b(b)): s += a[i] s += b[i] s += a[tamanho_b(b):] return s def combinador(): n = execucoes() for i in range(n): imprimir(analisar(entradas(), i, '')) combinador()
class Solution: def allPossibleFBT(self, N): def constr(N): if N == 1: yield TreeNode(0) for i in range(1, N, 2): for l in constr(i): for r in constr(N - i - 1): m = TreeNode(0) m.left = l m.right = r yield m return list(constr(N))
class Solution: def all_possible_fbt(self, N): def constr(N): if N == 1: yield tree_node(0) for i in range(1, N, 2): for l in constr(i): for r in constr(N - i - 1): m = tree_node(0) m.left = l m.right = r yield m return list(constr(N))
""" How to set up virtual environment pip install virtualenv pip install virtualenvwrapper # export WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh # To activate virtualenv and set up flask 1. mkvirtualenv my-venv ###2. workon my-venv 3. pip install Flask 4. pip freeze 5. # To put all dependencies in a file pip freeze > requirements.txt 6. run.py: entry point of the application 7. relational database management system SQLite, MYSQL, PostgreSQL SQLAlchemy is an Object Relational Mapper (ORM), which means that it connects the objects of an application to tables in a relational database management system. """
""" How to set up virtual environment pip install virtualenv pip install virtualenvwrapper # export WORKON_HOME=~/Envs source /usr/local/bin/virtualenvwrapper.sh # To activate virtualenv and set up flask 1. mkvirtualenv my-venv ###2. workon my-venv 3. pip install Flask 4. pip freeze 5. # To put all dependencies in a file pip freeze > requirements.txt 6. run.py: entry point of the application 7. relational database management system SQLite, MYSQL, PostgreSQL SQLAlchemy is an Object Relational Mapper (ORM), which means that it connects the objects of an application to tables in a relational database management system. """
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direction_same, obj[16]: Distance # {"feature": "Maritalstatus", "instances": 34, "metric_value": 0.99, "depth": 1} if obj[7]>0: # {"feature": "Age", "instances": 25, "metric_value": 0.9896, "depth": 2} if obj[6]<=5: # {"feature": "Time", "instances": 21, "metric_value": 0.9984, "depth": 3} if obj[2]<=1: # {"feature": "Occupation", "instances": 13, "metric_value": 0.8905, "depth": 4} if obj[10]<=13: # {"feature": "Coupon", "instances": 11, "metric_value": 0.684, "depth": 5} if obj[3]>0: # {"feature": "Distance", "instances": 10, "metric_value": 0.469, "depth": 6} if obj[16]<=2: return 'False' elif obj[16]>2: # {"feature": "Coupon_validity", "instances": 2, "metric_value": 1.0, "depth": 7} if obj[4]<=0: return 'True' elif obj[4]>0: return 'False' else: return 'False' else: return 'True' elif obj[3]<=0: return 'True' else: return 'True' elif obj[10]>13: return 'True' else: return 'True' elif obj[2]>1: # {"feature": "Occupation", "instances": 8, "metric_value": 0.8113, "depth": 4} if obj[10]<=7: return 'True' elif obj[10]>7: # {"feature": "Weather", "instances": 3, "metric_value": 0.9183, "depth": 5} if obj[1]<=0: return 'False' elif obj[1]>0: return 'True' else: return 'True' else: return 'False' else: return 'True' elif obj[6]>5: return 'True' else: return 'True' elif obj[7]<=0: # {"feature": "Age", "instances": 9, "metric_value": 0.5033, "depth": 2} if obj[6]>0: return 'False' elif obj[6]<=0: return 'True' else: return 'True' else: return 'False'
def find_decision(obj): if obj[7] > 0: if obj[6] <= 5: if obj[2] <= 1: if obj[10] <= 13: if obj[3] > 0: if obj[16] <= 2: return 'False' elif obj[16] > 2: if obj[4] <= 0: return 'True' elif obj[4] > 0: return 'False' else: return 'False' else: return 'True' elif obj[3] <= 0: return 'True' else: return 'True' elif obj[10] > 13: return 'True' else: return 'True' elif obj[2] > 1: if obj[10] <= 7: return 'True' elif obj[10] > 7: if obj[1] <= 0: return 'False' elif obj[1] > 0: return 'True' else: return 'True' else: return 'False' else: return 'True' elif obj[6] > 5: return 'True' else: return 'True' elif obj[7] <= 0: if obj[6] > 0: return 'False' elif obj[6] <= 0: return 'True' else: return 'True' else: return 'False'
macs_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetHostMacAddressesResponse</wsa:Action><wsa:RelatesTo>dt:1348742659504</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:111efb9a-f7d8-4977-8472-bcad40212a71</wsa:MessageID></s:Header><s:Body><GetHostMacAddressesResponse><HostMACaddress><HostMaddr><Description>Host Ethernet MAC Address 1</Description><Address>6E:F3:DD:E5:96:40</Address></HostMaddr><HostMaddr><Description>Host Ethernet MAC Address 2</Description><Address>6E:F3:DD:E5:96:42</Address></HostMaddr></HostMACaddress></GetHostMacAddressesResponse></s:Body></s:Envelope> ''' memory_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetMemoryInfoResponse</wsa:Action><wsa:RelatesTo>dt:1348742659500</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:dc560696-2ba4-4917-b7e7-1aac1983b727</wsa:MessageID></s:Header><s:Body><GetMemoryInfoResponse><Memory><MemoryInfo><Description>DIMM 2</Description><PartNumber>HMT351R7BFR4A-H9</PartNumber><SerialNumber>33b8a62f</SerialNumber><ManufactureDate>4511</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo><MemoryInfo><Description>DIMM 3</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>b38aa385</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 6</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>a78aa385</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 9</Description><PartNumber>EBJ40RF4ECFA-DJ-F</PartNumber><SerialNumber>b524042b</SerialNumber><ManufactureDate>4711</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo><MemoryInfo><Description>DIMM 11</Description><PartNumber>EBJ40RF4ECFA-DJ-F</PartNumber><SerialNumber>ba24042b</SerialNumber><ManufactureDate>4711</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo><MemoryInfo><Description>DIMM 12</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>8e8aa385</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 15</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>7feda482</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 18</Description><PartNumber>EBJ40RF4ECFA-DJ-F</PartNumber><SerialNumber>d924042b</SerialNumber><ManufactureDate>4711</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo></Memory></GetMemoryInfoResponse></s:Body></s:Envelope> ''' generic_data_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetVitalProductDataResponse</wsa:Action><wsa:RelatesTo>dt:1348742659499</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:e6829941-2510-4b3d-b9f3-61c7be372dfd</wsa:MessageID></s:Header><s:Body><GetVitalProductDataResponse><GetVitalProductDataResponse><MachineLevelVPD><ProductName>System x3550 M3</ProductName><MachineTypeAndModel>794452G</MachineTypeAndModel><SerialNumber>KD55ARA</SerialNumber><UUID>99A4E4A303023961B8E1561E33328996</UUID></MachineLevelVPD><ComponentLevelVPD><FRUNumber>59Y3915</FRUNumber><FRUName>DASD Backplane 1</FRUName><SerialNumber>Y010RW1AR1Y0</SerialNumber><MfgID>USIS</MfgID></ComponentLevelVPD><ComponentLevelVPD><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 1</FRUName><SerialNumber>K1411183222</SerialNumber><MfgID>ACBE</MfgID></ComponentLevelVPD><ComponentLevelVPD><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 2</FRUName><SerialNumber>K141115Y2BK</SerialNumber><MfgID>ACBE</MfgID></ComponentLevelVPD><ComponentActivityLog><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 1</FRUName><SerialNumber>K1411183222</SerialNumber><MfgID>ACBE</MfgID><Action>Added</Action><TimeStamp>11/25/2011:13:53:13</TimeStamp></ComponentActivityLog><ComponentActivityLog><FRUNumber>59Y3915</FRUNumber><FRUName>DASD Backplane 1</FRUName><SerialNumber>Y010RW1AR1Y0</SerialNumber><MfgID>USIS</MfgID><Action>Added</Action><TimeStamp>11/25/2011:13:53:13</TimeStamp></ComponentActivityLog><ComponentActivityLog><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 2</FRUName><SerialNumber>K141115Y2BK</SerialNumber><MfgID>ACBE</MfgID><Action>Added</Action><TimeStamp>01/27/2012:10:28:39</TimeStamp></ComponentActivityLog><VPD><FirmwareName>IMM</FirmwareName><VersionString>YUOOC7E</VersionString><ReleaseDate>09/30/2011</ReleaseDate></VPD><VPD><FirmwareName>UEFI</FirmwareName><VersionString>D6E154A</VersionString><ReleaseDate>09/23/2011</ReleaseDate></VPD><VPD><FirmwareName>DSA</FirmwareName><VersionString>DSYT89P </VersionString><ReleaseDate>10/28/2011</ReleaseDate></VPD></GetVitalProductDataResponse></GetVitalProductDataResponse></s:Body></s:Envelope> ''' sn_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/iBMCControl/GetSPNameSettingsResponse</wsa:Action><wsa:RelatesTo>dt:1348742647137</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:d2ac4b59-9f60-456e-a182-6a077557e4c1</wsa:MessageID></s:Header><s:Body><GetSPNameSettingsResponse><SPName>SN# KD55ARA</SPName></GetSPNameSettingsResponse></s:Body></s:Envelope> ''' processors_response = '''<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetProcessorInfoResponse</wsa:Action><wsa:RelatesTo>dt:1348757382511</wsa:RelatesTo><wsa:From><wsa:Address>http://rack-605-12-mgmt.dc2/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:9e5ec08d-0fac-449a-80fa-37cc78290a21</wsa:MessageID></s:Header><s:Body><GetProcessorInfoResponse><Processor><ProcessorInfo><Description>Processor 1</Description><Speed>2666</Speed><Identifier>3030363735304141</Identifier><Type>Central</Type><Family>Intel Xeon</Family><Cores>8</Cores><Threads>1</Threads><Voltage>1.087000</Voltage><Datawidth>64</Datawidth></ProcessorInfo><ProcessorInfo><Description>Processor 2</Description><Speed>2666</Speed><Identifier>3030363735304141</Identifier><Type>Central</Type><Family>Intel Xeon</Family><Cores>8</Cores><Threads>1</Threads><Voltage>1.087000</Voltage><Datawidth>64</Datawidth></ProcessorInfo></Processor></GetProcessorInfoResponse></s:Body></s:Envelope> '''
macs_response = '<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetHostMacAddressesResponse</wsa:Action><wsa:RelatesTo>dt:1348742659504</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:111efb9a-f7d8-4977-8472-bcad40212a71</wsa:MessageID></s:Header><s:Body><GetHostMacAddressesResponse><HostMACaddress><HostMaddr><Description>Host Ethernet MAC Address 1</Description><Address>6E:F3:DD:E5:96:40</Address></HostMaddr><HostMaddr><Description>Host Ethernet MAC Address 2</Description><Address>6E:F3:DD:E5:96:42</Address></HostMaddr></HostMACaddress></GetHostMacAddressesResponse></s:Body></s:Envelope>\n' memory_response = '<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetMemoryInfoResponse</wsa:Action><wsa:RelatesTo>dt:1348742659500</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:dc560696-2ba4-4917-b7e7-1aac1983b727</wsa:MessageID></s:Header><s:Body><GetMemoryInfoResponse><Memory><MemoryInfo><Description>DIMM 2</Description><PartNumber>HMT351R7BFR4A-H9</PartNumber><SerialNumber>33b8a62f</SerialNumber><ManufactureDate>4511</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo><MemoryInfo><Description>DIMM 3</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>b38aa385</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 6</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>a78aa385</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 9</Description><PartNumber>EBJ40RF4ECFA-DJ-F</PartNumber><SerialNumber>b524042b</SerialNumber><ManufactureDate>4711</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo><MemoryInfo><Description>DIMM 11</Description><PartNumber>EBJ40RF4ECFA-DJ-F</PartNumber><SerialNumber>ba24042b</SerialNumber><ManufactureDate>4711</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo><MemoryInfo><Description>DIMM 12</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>8e8aa385</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 15</Description><PartNumber>M393B1K70CH0-YH9</PartNumber><SerialNumber>7feda482</SerialNumber><ManufactureDate>2211</ManufactureDate><Type>DDR3</Type><Size>8</Size></MemoryInfo><MemoryInfo><Description>DIMM 18</Description><PartNumber>EBJ40RF4ECFA-DJ-F</PartNumber><SerialNumber>d924042b</SerialNumber><ManufactureDate>4711</ManufactureDate><Type>DDR3</Type><Size>4</Size></MemoryInfo></Memory></GetMemoryInfoResponse></s:Body></s:Envelope>\n' generic_data_response = '<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetVitalProductDataResponse</wsa:Action><wsa:RelatesTo>dt:1348742659499</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:e6829941-2510-4b3d-b9f3-61c7be372dfd</wsa:MessageID></s:Header><s:Body><GetVitalProductDataResponse><GetVitalProductDataResponse><MachineLevelVPD><ProductName>System x3550 M3</ProductName><MachineTypeAndModel>794452G</MachineTypeAndModel><SerialNumber>KD55ARA</SerialNumber><UUID>99A4E4A303023961B8E1561E33328996</UUID></MachineLevelVPD><ComponentLevelVPD><FRUNumber>59Y3915</FRUNumber><FRUName>DASD Backplane 1</FRUName><SerialNumber>Y010RW1AR1Y0</SerialNumber><MfgID>USIS</MfgID></ComponentLevelVPD><ComponentLevelVPD><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 1</FRUName><SerialNumber>K1411183222</SerialNumber><MfgID>ACBE</MfgID></ComponentLevelVPD><ComponentLevelVPD><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 2</FRUName><SerialNumber>K141115Y2BK</SerialNumber><MfgID>ACBE</MfgID></ComponentLevelVPD><ComponentActivityLog><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 1</FRUName><SerialNumber>K1411183222</SerialNumber><MfgID>ACBE</MfgID><Action>Added</Action><TimeStamp>11/25/2011:13:53:13</TimeStamp></ComponentActivityLog><ComponentActivityLog><FRUNumber>59Y3915</FRUNumber><FRUName>DASD Backplane 1</FRUName><SerialNumber>Y010RW1AR1Y0</SerialNumber><MfgID>USIS</MfgID><Action>Added</Action><TimeStamp>11/25/2011:13:53:13</TimeStamp></ComponentActivityLog><ComponentActivityLog><FRUNumber>39Y7229</FRUNumber><FRUName>Power Supply 2</FRUName><SerialNumber>K141115Y2BK</SerialNumber><MfgID>ACBE</MfgID><Action>Added</Action><TimeStamp>01/27/2012:10:28:39</TimeStamp></ComponentActivityLog><VPD><FirmwareName>IMM</FirmwareName><VersionString>YUOOC7E</VersionString><ReleaseDate>09/30/2011</ReleaseDate></VPD><VPD><FirmwareName>UEFI</FirmwareName><VersionString>D6E154A</VersionString><ReleaseDate>09/23/2011</ReleaseDate></VPD><VPD><FirmwareName>DSA</FirmwareName><VersionString>DSYT89P </VersionString><ReleaseDate>10/28/2011</ReleaseDate></VPD></GetVitalProductDataResponse></GetVitalProductDataResponse></s:Body></s:Envelope>\n' sn_response = '<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/iBMCControl/GetSPNameSettingsResponse</wsa:Action><wsa:RelatesTo>dt:1348742647137</wsa:RelatesTo><wsa:From><wsa:Address>http://10.10.10.10/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:d2ac4b59-9f60-456e-a182-6a077557e4c1</wsa:MessageID></s:Header><s:Body><GetSPNameSettingsResponse><SPName>SN# KD55ARA</SPName></GetSPNameSettingsResponse></s:Body></s:Envelope>\n' processors_response = '<?xml version="1.0"?><s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:wsa="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:wxf="http://schemas.xmlsoap.org/ws/2004/09/transfer"><s:Header><wsa:To>http://schemas.xmlsoap.org/ws/2004/08/addressing/role/anonymous</wsa:To><wsa:Action>http://www.ibm.com/iBMC/sp/Monitors/GetProcessorInfoResponse</wsa:Action><wsa:RelatesTo>dt:1348757382511</wsa:RelatesTo><wsa:From><wsa:Address>http://rack-605-12-mgmt.dc2/wsman</wsa:Address></wsa:From><wsa:MessageID>uuid:9e5ec08d-0fac-449a-80fa-37cc78290a21</wsa:MessageID></s:Header><s:Body><GetProcessorInfoResponse><Processor><ProcessorInfo><Description>Processor 1</Description><Speed>2666</Speed><Identifier>3030363735304141</Identifier><Type>Central</Type><Family>Intel Xeon</Family><Cores>8</Cores><Threads>1</Threads><Voltage>1.087000</Voltage><Datawidth>64</Datawidth></ProcessorInfo><ProcessorInfo><Description>Processor 2</Description><Speed>2666</Speed><Identifier>3030363735304141</Identifier><Type>Central</Type><Family>Intel Xeon</Family><Cores>8</Cores><Threads>1</Threads><Voltage>1.087000</Voltage><Datawidth>64</Datawidth></ProcessorInfo></Processor></GetProcessorInfoResponse></s:Body></s:Envelope>\n'
# Copyright (C) 2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 VERIFIED_OP_REFERENCES = [ 'Abs-1', 'Acos-1', 'Add-1', 'Asin-1', 'Asinh-3', 'Assign-6', 'AvgPool-1', 'BatchNormInference-5', 'BatchToSpace-2', 'BinaryConvolution-1', 'Broadcast-1', 'Broadcast-3', 'Bucketize-3', 'Ceiling-1', 'CTCGreedyDecoder-1', 'CTCGreedyDecoderSeqLen-6', 'Concat-1', 'Convert-1', 'ConvertLike-1', 'Convolution-1', 'Constant-1', 'Cos-1', 'Cosh-1', 'DeformableConvolution-1', 'DeformablePSROIPooling-1', 'DepthToSpace-1', 'DetectionOutput-1', 'Divide-1', 'ExperimentalDetectronDetectionOutput-6', 'ExperimentalDetectronGenerateProposalsSingleImage-6', 'ExperimentalDetectronPriorGridGenerator-6', 'ExperimentalDetectronROIFeatureExtractor-6', 'ExperimentalDetectronTopKROIs-6', 'FakeQuantize-1', 'Floor-1' 'FloorMod-1' 'GRUSequence-5', 'Gather-1', 'GatherElements-6', 'GatherND-5', 'Gelu-7', 'GRN-1', 'GroupConvolution-1', 'GroupConvolutionBackpropData-1', 'GRUSequence-5', 'HSigmoid-5', 'HSwish-4', 'HardSigmoid-1', 'Interpolate-4', 'LRN-1', 'LSTMCell-4', 'LSTMSequence-5', 'LogSoftmax-5', 'Loop-5', 'MVN-6', 'Maximum-1', 'MaxPool-1', 'Mish-4', 'Multiply-1', 'Negative-1', 'NonMaxSuppression-4', 'NonMaxSuppression-5', 'NonZero-3', 'NormalizeL2-1', 'PriorBox-1', 'PriorBoxClustered-1', 'Proposal-1', 'Proposal-4', 'PSROIPooling-1', 'RNNSequence-5', 'ROIAlign-3', 'ROIPooling-2', 'Range-1', 'Range-4', 'ReadValue-6', 'ReduceL1-4', 'ReduceL2-4', 'ReduceLogicalAnd-1', 'ReduceLogicalOr-1', 'ReduceMax-1', 'ReduceMean-1', 'ReduceMin-1', 'ReduceProd-1', 'ReduceSum-1', 'RegionYOLO-1', 'Relu-1', 'ReorgYOLO-2', 'Result-1' 'Round-5', 'SpaceToDepth-1', 'ScatterNDUpdate-4', 'Select-1', 'ShapeOf-1', 'ShapeOf-3', 'ShuffleChannels-1', 'Sigmoid-1', 'Sign-1', 'Sin-1', 'Sinh-1' 'SoftPlus-4', 'Softmax-1', 'Split-1', 'Squeeze-1', 'StridedSlice-1', 'Subtract-1', 'Swish-4', 'Tile-1', 'TopK-1', 'TopK-3', 'Transpose-1', 'Unsqueeze-1', 'VariadicSplit-1', ]
verified_op_references = ['Abs-1', 'Acos-1', 'Add-1', 'Asin-1', 'Asinh-3', 'Assign-6', 'AvgPool-1', 'BatchNormInference-5', 'BatchToSpace-2', 'BinaryConvolution-1', 'Broadcast-1', 'Broadcast-3', 'Bucketize-3', 'Ceiling-1', 'CTCGreedyDecoder-1', 'CTCGreedyDecoderSeqLen-6', 'Concat-1', 'Convert-1', 'ConvertLike-1', 'Convolution-1', 'Constant-1', 'Cos-1', 'Cosh-1', 'DeformableConvolution-1', 'DeformablePSROIPooling-1', 'DepthToSpace-1', 'DetectionOutput-1', 'Divide-1', 'ExperimentalDetectronDetectionOutput-6', 'ExperimentalDetectronGenerateProposalsSingleImage-6', 'ExperimentalDetectronPriorGridGenerator-6', 'ExperimentalDetectronROIFeatureExtractor-6', 'ExperimentalDetectronTopKROIs-6', 'FakeQuantize-1', 'Floor-1FloorMod-1GRUSequence-5', 'Gather-1', 'GatherElements-6', 'GatherND-5', 'Gelu-7', 'GRN-1', 'GroupConvolution-1', 'GroupConvolutionBackpropData-1', 'GRUSequence-5', 'HSigmoid-5', 'HSwish-4', 'HardSigmoid-1', 'Interpolate-4', 'LRN-1', 'LSTMCell-4', 'LSTMSequence-5', 'LogSoftmax-5', 'Loop-5', 'MVN-6', 'Maximum-1', 'MaxPool-1', 'Mish-4', 'Multiply-1', 'Negative-1', 'NonMaxSuppression-4', 'NonMaxSuppression-5', 'NonZero-3', 'NormalizeL2-1', 'PriorBox-1', 'PriorBoxClustered-1', 'Proposal-1', 'Proposal-4', 'PSROIPooling-1', 'RNNSequence-5', 'ROIAlign-3', 'ROIPooling-2', 'Range-1', 'Range-4', 'ReadValue-6', 'ReduceL1-4', 'ReduceL2-4', 'ReduceLogicalAnd-1', 'ReduceLogicalOr-1', 'ReduceMax-1', 'ReduceMean-1', 'ReduceMin-1', 'ReduceProd-1', 'ReduceSum-1', 'RegionYOLO-1', 'Relu-1', 'ReorgYOLO-2', 'Result-1Round-5', 'SpaceToDepth-1', 'ScatterNDUpdate-4', 'Select-1', 'ShapeOf-1', 'ShapeOf-3', 'ShuffleChannels-1', 'Sigmoid-1', 'Sign-1', 'Sin-1', 'Sinh-1SoftPlus-4', 'Softmax-1', 'Split-1', 'Squeeze-1', 'StridedSlice-1', 'Subtract-1', 'Swish-4', 'Tile-1', 'TopK-1', 'TopK-3', 'Transpose-1', 'Unsqueeze-1', 'VariadicSplit-1']
# Copyright 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # This dictionary of GPU information was captured from a run of # Telemetry on a Linux workstation with NVIDIA GPU. It helps test # telemetry.internal.platform's GPUInfo class, and specifically the # attributes it expects to find in the dictionary; if the code changes # in an incompatible way, tests using this fake GPU info will begin # failing, indicating this fake data must be updated. # # To regenerate it, import pdb in # telemetry/internal/platform/gpu_info.py and add a call to # pdb.set_trace() in GPUInfo.FromDict before the return statement. # Print the attrs dictionary in the debugger and copy/paste the result # on the right-hand side of this assignment. Then run: # # pyformat [this file name] | sed -e "s/'/'/g" # # and put the output into this file. FAKE_GPU_INFO = { 'feature_status': { 'flash_stage3d': 'enabled', 'gpu_compositing': 'enabled', 'video_decode': 'unavailable_software', 'flash_3d': 'enabled', 'webgl': 'enabled', 'video_encode': 'enabled', 'multiple_raster_threads': 'enabled_on', '2d_canvas': 'unavailable_software', 'rasterization': 'disabled_software', 'flash_stage3d_baseline': 'enabled' }, 'aux_attributes': { 'optimus': False, 'sandboxed': True, 'basic_info_state': 1, 'adapter_luid': 0.0, 'driver_version': '331.79', 'direct_rendering': True, 'amd_switchable': False, 'context_info_state': 1, 'process_crash_count': 0, 'pixel_shader_version': '4.40', 'gl_ws_version': '1.4', 'can_lose_context': False, 'driver_vendor': 'NVIDIA', 'max_msaa_samples': '64', 'software_rendering': False, 'gl_version': '4.4.0 NVIDIA 331.79', 'gl_ws_vendor': 'NVIDIA Corporation', 'vertex_shader_version': '4.40', 'initialization_time': 1.284043, 'gl_reset_notification_strategy': 33362, 'gl_ws_extensions': 'GLX_EXT_visual_info GLX_EXT_visual_rating GLX_SGIX_fbconfig ' 'GLX_SGIX_pbuffer GLX_SGI_video_sync GLX_SGI_swap_control ' 'GLX_EXT_swap_control GLX_EXT_swap_control_tear ' 'GLX_EXT_texture_from_pixmap GLX_EXT_buffer_age ' 'GLX_ARB_create_context GLX_ARB_create_context_profile ' 'GLX_EXT_create_context_es_profile ' 'GLX_EXT_create_context_es2_profile ' 'GLX_ARB_create_context_robustness GLX_ARB_multisample ' 'GLX_NV_float_buffer GLX_ARB_fbconfig_float GLX_NV_swap_group' ' GLX_EXT_framebuffer_sRGB GLX_NV_multisample_coverage ' 'GLX_NV_copy_image GLX_NV_video_capture ', 'gl_renderer': 'Quadro 600/PCIe/SSE2', 'driver_date': '', 'gl_vendor': 'NVIDIA Corporation', 'gl_extensions': 'GL_AMD_multi_draw_indirect GL_ARB_arrays_of_arrays ' 'GL_ARB_base_instance GL_ARB_blend_func_extended ' 'GL_ARB_buffer_storage GL_ARB_clear_buffer_object ' 'GL_ARB_clear_texture GL_ARB_color_buffer_float ' 'GL_ARB_compatibility GL_ARB_compressed_texture_pixel_storage' ' GL_ARB_conservative_depth GL_ARB_compute_shader ' 'GL_ARB_compute_variable_group_size GL_ARB_copy_buffer ' 'GL_ARB_copy_image GL_ARB_debug_output ' 'GL_ARB_depth_buffer_float GL_ARB_depth_clamp ' 'GL_ARB_depth_texture GL_ARB_draw_buffers ' 'GL_ARB_draw_buffers_blend GL_ARB_draw_indirect ' 'GL_ARB_draw_elements_base_vertex GL_ARB_draw_instanced ' 'GL_ARB_enhanced_layouts GL_ARB_ES2_compatibility ' 'GL_ARB_ES3_compatibility GL_ARB_explicit_attrib_location ' 'GL_ARB_explicit_uniform_location ' 'GL_ARB_fragment_coord_conventions ' 'GL_ARB_fragment_layer_viewport GL_ARB_fragment_program ' 'GL_ARB_fragment_program_shadow GL_ARB_fragment_shader ' 'GL_ARB_framebuffer_no_attachments GL_ARB_framebuffer_object ' 'GL_ARB_framebuffer_sRGB GL_ARB_geometry_shader4 ' 'GL_ARB_get_program_binary GL_ARB_gpu_shader5 ' 'GL_ARB_gpu_shader_fp64 GL_ARB_half_float_pixel ' 'GL_ARB_half_float_vertex GL_ARB_imaging ' 'GL_ARB_indirect_parameters GL_ARB_instanced_arrays ' 'GL_ARB_internalformat_query GL_ARB_internalformat_query2 ' 'GL_ARB_invalidate_subdata GL_ARB_map_buffer_alignment ' 'GL_ARB_map_buffer_range GL_ARB_multi_bind ' 'GL_ARB_multi_draw_indirect GL_ARB_multisample ' 'GL_ARB_multitexture GL_ARB_occlusion_query ' 'GL_ARB_occlusion_query2 GL_ARB_pixel_buffer_object ' 'GL_ARB_point_parameters GL_ARB_point_sprite ' 'GL_ARB_program_interface_query GL_ARB_provoking_vertex ' 'GL_ARB_robust_buffer_access_behavior GL_ARB_robustness ' 'GL_ARB_sample_shading GL_ARB_sampler_objects ' 'GL_ARB_seamless_cube_map GL_ARB_separate_shader_objects ' 'GL_ARB_shader_atomic_counters GL_ARB_shader_bit_encoding ' 'GL_ARB_shader_draw_parameters GL_ARB_shader_group_vote ' 'GL_ARB_shader_image_load_store GL_ARB_shader_image_size ' 'GL_ARB_shader_objects GL_ARB_shader_precision ' 'GL_ARB_query_buffer_object ' 'GL_ARB_shader_storage_buffer_object GL_ARB_shader_subroutine' ' GL_ARB_shader_texture_lod GL_ARB_shading_language_100 ' 'GL_ARB_shading_language_420pack ' 'GL_ARB_shading_language_include ' 'GL_ARB_shading_language_packing GL_ARB_shadow ' 'GL_ARB_stencil_texturing GL_ARB_sync ' 'GL_ARB_tessellation_shader GL_ARB_texture_border_clamp ' 'GL_ARB_texture_buffer_object ' 'GL_ARB_texture_buffer_object_rgb32 ' 'GL_ARB_texture_buffer_range GL_ARB_texture_compression ' 'GL_ARB_texture_compression_bptc ' 'GL_ARB_texture_compression_rgtc GL_ARB_texture_cube_map ' 'GL_ARB_texture_cube_map_array GL_ARB_texture_env_add ' 'GL_ARB_texture_env_combine GL_ARB_texture_env_crossbar ' 'GL_ARB_texture_env_dot3 GL_ARB_texture_float ' 'GL_ARB_texture_gather GL_ARB_texture_mirror_clamp_to_edge ' 'GL_ARB_texture_mirrored_repeat GL_ARB_texture_multisample ' 'GL_ARB_texture_non_power_of_two GL_ARB_texture_query_levels ' 'GL_ARB_texture_query_lod GL_ARB_texture_rectangle ' 'GL_ARB_texture_rg GL_ARB_texture_rgb10_a2ui ' 'GL_ARB_texture_stencil8 GL_ARB_texture_storage ' 'GL_ARB_texture_storage_multisample GL_ARB_texture_swizzle ' 'GL_ARB_texture_view GL_ARB_timer_query ' 'GL_ARB_transform_feedback2 GL_ARB_transform_feedback3 ' 'GL_ARB_transform_feedback_instanced GL_ARB_transpose_matrix ' 'GL_ARB_uniform_buffer_object GL_ARB_vertex_array_bgra ' 'GL_ARB_vertex_array_object GL_ARB_vertex_attrib_64bit ' 'GL_ARB_vertex_attrib_binding GL_ARB_vertex_buffer_object ' 'GL_ARB_vertex_program GL_ARB_vertex_shader ' 'GL_ARB_vertex_type_10f_11f_11f_rev ' 'GL_ARB_vertex_type_2_10_10_10_rev GL_ARB_viewport_array ' 'GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_texture_float ' 'GL_ATI_texture_mirror_once GL_S3_s3tc GL_EXT_texture_env_add' ' GL_EXT_abgr GL_EXT_bgra GL_EXT_bindable_uniform ' 'GL_EXT_blend_color GL_EXT_blend_equation_separate ' 'GL_EXT_blend_func_separate GL_EXT_blend_minmax ' 'GL_EXT_blend_subtract GL_EXT_compiled_vertex_array ' 'GL_EXT_Cg_shader GL_EXT_depth_bounds_test ' 'GL_EXT_direct_state_access GL_EXT_draw_buffers2 ' 'GL_EXT_draw_instanced GL_EXT_draw_range_elements ' 'GL_EXT_fog_coord GL_EXT_framebuffer_blit ' 'GL_EXT_framebuffer_multisample ' 'GL_EXTX_framebuffer_mixed_formats ' 'GL_EXT_framebuffer_multisample_blit_scaled ' 'GL_EXT_framebuffer_object GL_EXT_framebuffer_sRGB ' 'GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters ' 'GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays ' 'GL_EXT_packed_depth_stencil GL_EXT_packed_float ' 'GL_EXT_packed_pixels GL_EXT_pixel_buffer_object ' 'GL_EXT_point_parameters GL_EXT_provoking_vertex ' 'GL_EXT_rescale_normal GL_EXT_secondary_color ' 'GL_EXT_separate_shader_objects ' 'GL_EXT_separate_specular_color ' 'GL_EXT_shader_image_load_store GL_EXT_shadow_funcs ' 'GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture3D' ' GL_EXT_texture_array GL_EXT_texture_buffer_object ' 'GL_EXT_texture_compression_dxt1 ' 'GL_EXT_texture_compression_latc ' 'GL_EXT_texture_compression_rgtc ' 'GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map ' 'GL_EXT_texture_edge_clamp GL_EXT_texture_env_combine ' 'GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic ' 'GL_EXT_texture_integer GL_EXT_texture_lod ' 'GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp ' 'GL_EXT_texture_object GL_EXT_texture_shared_exponent ' 'GL_EXT_texture_sRGB GL_EXT_texture_sRGB_decode ' 'GL_EXT_texture_storage GL_EXT_texture_swizzle ' 'GL_EXT_timer_query GL_EXT_transform_feedback2 ' 'GL_EXT_vertex_array GL_EXT_vertex_array_bgra ' 'GL_EXT_vertex_attrib_64bit GL_EXT_x11_sync_object ' 'GL_EXT_import_sync_object GL_IBM_rasterpos_clip ' 'GL_IBM_texture_mirrored_repeat GL_KHR_debug ' 'GL_KTX_buffer_region GL_NV_bindless_multi_draw_indirect ' 'GL_NV_blend_equation_advanced GL_NV_blend_square ' 'GL_NV_compute_program5 GL_NV_conditional_render ' 'GL_NV_copy_depth_to_color GL_NV_copy_image ' 'GL_NV_depth_buffer_float GL_NV_depth_clamp ' 'GL_NV_draw_texture GL_NV_ES1_1_compatibility ' 'GL_NV_explicit_multisample GL_NV_fence GL_NV_float_buffer ' 'GL_NV_fog_distance GL_NV_fragment_program ' 'GL_NV_fragment_program_option GL_NV_fragment_program2 ' 'GL_NV_framebuffer_multisample_coverage ' 'GL_NV_geometry_shader4 GL_NV_gpu_program4 ' 'GL_NV_gpu_program4_1 GL_NV_gpu_program5 ' 'GL_NV_gpu_program5_mem_extended GL_NV_gpu_program_fp64 ' 'GL_NV_gpu_shader5 GL_NV_half_float GL_NV_light_max_exponent ' 'GL_NV_multisample_coverage GL_NV_multisample_filter_hint ' 'GL_NV_occlusion_query GL_NV_packed_depth_stencil ' 'GL_NV_parameter_buffer_object GL_NV_parameter_buffer_object2' ' GL_NV_path_rendering GL_NV_pixel_data_range ' 'GL_NV_point_sprite GL_NV_primitive_restart ' 'GL_NV_register_combiners GL_NV_register_combiners2 ' 'GL_NV_shader_atomic_counters GL_NV_shader_atomic_float ' 'GL_NV_shader_buffer_load GL_NV_shader_storage_buffer_object ' 'GL_ARB_sparse_texture GL_NV_texgen_reflection ' 'GL_NV_texture_barrier GL_NV_texture_compression_vtc ' 'GL_NV_texture_env_combine4 GL_NV_texture_expand_normal ' 'GL_NV_texture_multisample GL_NV_texture_rectangle ' 'GL_NV_texture_shader GL_NV_texture_shader2 ' 'GL_NV_texture_shader3 GL_NV_transform_feedback ' 'GL_NV_transform_feedback2 GL_NV_vdpau_interop ' 'GL_NV_vertex_array_range GL_NV_vertex_array_range2 ' 'GL_NV_vertex_attrib_integer_64bit ' 'GL_NV_vertex_buffer_unified_memory GL_NV_vertex_program ' 'GL_NV_vertex_program1_1 GL_NV_vertex_program2 ' 'GL_NV_vertex_program2_option GL_NV_vertex_program3 ' 'GL_NVX_conditional_render GL_NVX_gpu_memory_info ' 'GL_SGIS_generate_mipmap GL_SGIS_texture_lod ' 'GL_SGIX_depth_texture GL_SGIX_shadow GL_SUN_slice_accum ' }, 'devices': [ { 'device_string': '', 'vendor_id': 4318.0, 'device_id': 3576.0, 'vendor_string': '' }], 'driver_bug_workarounds': ['clear_uniforms_before_first_program_use', 'disable_gl_path_rendering', 'init_gl_position_in_vertex_shader', 'init_vertex_attributes', 'remove_pow_with_constant_exponent', 'scalarize_vec_and_mat_constructor_args', 'use_current_program_after_successful_link', 'use_virtualized_gl_contexts'] }
fake_gpu_info = {'feature_status': {'flash_stage3d': 'enabled', 'gpu_compositing': 'enabled', 'video_decode': 'unavailable_software', 'flash_3d': 'enabled', 'webgl': 'enabled', 'video_encode': 'enabled', 'multiple_raster_threads': 'enabled_on', '2d_canvas': 'unavailable_software', 'rasterization': 'disabled_software', 'flash_stage3d_baseline': 'enabled'}, 'aux_attributes': {'optimus': False, 'sandboxed': True, 'basic_info_state': 1, 'adapter_luid': 0.0, 'driver_version': '331.79', 'direct_rendering': True, 'amd_switchable': False, 'context_info_state': 1, 'process_crash_count': 0, 'pixel_shader_version': '4.40', 'gl_ws_version': '1.4', 'can_lose_context': False, 'driver_vendor': 'NVIDIA', 'max_msaa_samples': '64', 'software_rendering': False, 'gl_version': '4.4.0 NVIDIA 331.79', 'gl_ws_vendor': 'NVIDIA Corporation', 'vertex_shader_version': '4.40', 'initialization_time': 1.284043, 'gl_reset_notification_strategy': 33362, 'gl_ws_extensions': 'GLX_EXT_visual_info GLX_EXT_visual_rating GLX_SGIX_fbconfig GLX_SGIX_pbuffer GLX_SGI_video_sync GLX_SGI_swap_control GLX_EXT_swap_control GLX_EXT_swap_control_tear GLX_EXT_texture_from_pixmap GLX_EXT_buffer_age GLX_ARB_create_context GLX_ARB_create_context_profile GLX_EXT_create_context_es_profile GLX_EXT_create_context_es2_profile GLX_ARB_create_context_robustness GLX_ARB_multisample GLX_NV_float_buffer GLX_ARB_fbconfig_float GLX_NV_swap_group GLX_EXT_framebuffer_sRGB GLX_NV_multisample_coverage GLX_NV_copy_image GLX_NV_video_capture ', 'gl_renderer': 'Quadro 600/PCIe/SSE2', 'driver_date': '', 'gl_vendor': 'NVIDIA Corporation', 'gl_extensions': 'GL_AMD_multi_draw_indirect GL_ARB_arrays_of_arrays GL_ARB_base_instance GL_ARB_blend_func_extended GL_ARB_buffer_storage GL_ARB_clear_buffer_object GL_ARB_clear_texture GL_ARB_color_buffer_float GL_ARB_compatibility GL_ARB_compressed_texture_pixel_storage GL_ARB_conservative_depth GL_ARB_compute_shader GL_ARB_compute_variable_group_size GL_ARB_copy_buffer GL_ARB_copy_image GL_ARB_debug_output GL_ARB_depth_buffer_float GL_ARB_depth_clamp GL_ARB_depth_texture GL_ARB_draw_buffers GL_ARB_draw_buffers_blend GL_ARB_draw_indirect GL_ARB_draw_elements_base_vertex GL_ARB_draw_instanced GL_ARB_enhanced_layouts GL_ARB_ES2_compatibility GL_ARB_ES3_compatibility GL_ARB_explicit_attrib_location GL_ARB_explicit_uniform_location GL_ARB_fragment_coord_conventions GL_ARB_fragment_layer_viewport GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_framebuffer_no_attachments GL_ARB_framebuffer_object GL_ARB_framebuffer_sRGB GL_ARB_geometry_shader4 GL_ARB_get_program_binary GL_ARB_gpu_shader5 GL_ARB_gpu_shader_fp64 GL_ARB_half_float_pixel GL_ARB_half_float_vertex GL_ARB_imaging GL_ARB_indirect_parameters GL_ARB_instanced_arrays GL_ARB_internalformat_query GL_ARB_internalformat_query2 GL_ARB_invalidate_subdata GL_ARB_map_buffer_alignment GL_ARB_map_buffer_range GL_ARB_multi_bind GL_ARB_multi_draw_indirect GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_occlusion_query2 GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_program_interface_query GL_ARB_provoking_vertex GL_ARB_robust_buffer_access_behavior GL_ARB_robustness GL_ARB_sample_shading GL_ARB_sampler_objects GL_ARB_seamless_cube_map GL_ARB_separate_shader_objects GL_ARB_shader_atomic_counters GL_ARB_shader_bit_encoding GL_ARB_shader_draw_parameters GL_ARB_shader_group_vote GL_ARB_shader_image_load_store GL_ARB_shader_image_size GL_ARB_shader_objects GL_ARB_shader_precision GL_ARB_query_buffer_object GL_ARB_shader_storage_buffer_object GL_ARB_shader_subroutine GL_ARB_shader_texture_lod GL_ARB_shading_language_100 GL_ARB_shading_language_420pack GL_ARB_shading_language_include GL_ARB_shading_language_packing GL_ARB_shadow GL_ARB_stencil_texturing GL_ARB_sync GL_ARB_tessellation_shader GL_ARB_texture_border_clamp GL_ARB_texture_buffer_object GL_ARB_texture_buffer_object_rgb32 GL_ARB_texture_buffer_range GL_ARB_texture_compression GL_ARB_texture_compression_bptc GL_ARB_texture_compression_rgtc GL_ARB_texture_cube_map GL_ARB_texture_cube_map_array GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_crossbar GL_ARB_texture_env_dot3 GL_ARB_texture_float GL_ARB_texture_gather GL_ARB_texture_mirror_clamp_to_edge GL_ARB_texture_mirrored_repeat GL_ARB_texture_multisample GL_ARB_texture_non_power_of_two GL_ARB_texture_query_levels GL_ARB_texture_query_lod GL_ARB_texture_rectangle GL_ARB_texture_rg GL_ARB_texture_rgb10_a2ui GL_ARB_texture_stencil8 GL_ARB_texture_storage GL_ARB_texture_storage_multisample GL_ARB_texture_swizzle GL_ARB_texture_view GL_ARB_timer_query GL_ARB_transform_feedback2 GL_ARB_transform_feedback3 GL_ARB_transform_feedback_instanced GL_ARB_transpose_matrix GL_ARB_uniform_buffer_object GL_ARB_vertex_array_bgra GL_ARB_vertex_array_object GL_ARB_vertex_attrib_64bit GL_ARB_vertex_attrib_binding GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_vertex_type_10f_11f_11f_rev GL_ARB_vertex_type_2_10_10_10_rev GL_ARB_viewport_array GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_texture_float GL_ATI_texture_mirror_once GL_S3_s3tc GL_EXT_texture_env_add GL_EXT_abgr GL_EXT_bgra GL_EXT_bindable_uniform GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_compiled_vertex_array GL_EXT_Cg_shader GL_EXT_depth_bounds_test GL_EXT_direct_state_access GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXTX_framebuffer_mixed_formats GL_EXT_framebuffer_multisample_blit_scaled GL_EXT_framebuffer_object GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_packed_pixels GL_EXT_pixel_buffer_object GL_EXT_point_parameters GL_EXT_provoking_vertex GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_shader_objects GL_EXT_separate_specular_color GL_EXT_shader_image_load_store GL_EXT_shadow_funcs GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture3D GL_EXT_texture_array GL_EXT_texture_buffer_object GL_EXT_texture_compression_dxt1 GL_EXT_texture_compression_latc GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map GL_EXT_texture_edge_clamp GL_EXT_texture_env_combine GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_object GL_EXT_texture_shared_exponent GL_EXT_texture_sRGB GL_EXT_texture_sRGB_decode GL_EXT_texture_storage GL_EXT_texture_swizzle GL_EXT_timer_query GL_EXT_transform_feedback2 GL_EXT_vertex_array GL_EXT_vertex_array_bgra GL_EXT_vertex_attrib_64bit GL_EXT_x11_sync_object GL_EXT_import_sync_object GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat GL_KHR_debug GL_KTX_buffer_region GL_NV_bindless_multi_draw_indirect GL_NV_blend_equation_advanced GL_NV_blend_square GL_NV_compute_program5 GL_NV_conditional_render GL_NV_copy_depth_to_color GL_NV_copy_image GL_NV_depth_buffer_float GL_NV_depth_clamp GL_NV_draw_texture GL_NV_ES1_1_compatibility GL_NV_explicit_multisample GL_NV_fence GL_NV_float_buffer GL_NV_fog_distance GL_NV_fragment_program GL_NV_fragment_program_option GL_NV_fragment_program2 GL_NV_framebuffer_multisample_coverage GL_NV_geometry_shader4 GL_NV_gpu_program4 GL_NV_gpu_program4_1 GL_NV_gpu_program5 GL_NV_gpu_program5_mem_extended GL_NV_gpu_program_fp64 GL_NV_gpu_shader5 GL_NV_half_float GL_NV_light_max_exponent GL_NV_multisample_coverage GL_NV_multisample_filter_hint GL_NV_occlusion_query GL_NV_packed_depth_stencil GL_NV_parameter_buffer_object GL_NV_parameter_buffer_object2 GL_NV_path_rendering GL_NV_pixel_data_range GL_NV_point_sprite GL_NV_primitive_restart GL_NV_register_combiners GL_NV_register_combiners2 GL_NV_shader_atomic_counters GL_NV_shader_atomic_float GL_NV_shader_buffer_load GL_NV_shader_storage_buffer_object GL_ARB_sparse_texture GL_NV_texgen_reflection GL_NV_texture_barrier GL_NV_texture_compression_vtc GL_NV_texture_env_combine4 GL_NV_texture_expand_normal GL_NV_texture_multisample GL_NV_texture_rectangle GL_NV_texture_shader GL_NV_texture_shader2 GL_NV_texture_shader3 GL_NV_transform_feedback GL_NV_transform_feedback2 GL_NV_vdpau_interop GL_NV_vertex_array_range GL_NV_vertex_array_range2 GL_NV_vertex_attrib_integer_64bit GL_NV_vertex_buffer_unified_memory GL_NV_vertex_program GL_NV_vertex_program1_1 GL_NV_vertex_program2 GL_NV_vertex_program2_option GL_NV_vertex_program3 GL_NVX_conditional_render GL_NVX_gpu_memory_info GL_SGIS_generate_mipmap GL_SGIS_texture_lod GL_SGIX_depth_texture GL_SGIX_shadow GL_SUN_slice_accum '}, 'devices': [{'device_string': '', 'vendor_id': 4318.0, 'device_id': 3576.0, 'vendor_string': ''}], 'driver_bug_workarounds': ['clear_uniforms_before_first_program_use', 'disable_gl_path_rendering', 'init_gl_position_in_vertex_shader', 'init_vertex_attributes', 'remove_pow_with_constant_exponent', 'scalarize_vec_and_mat_constructor_args', 'use_current_program_after_successful_link', 'use_virtualized_gl_contexts']}
for i in range(int(input())): number_of_candies = int(input()) candies_weights = list(map(int, input().split())) bob_pos = number_of_candies - 1 alice_pos = 0 bob_current_weight = 0 alice_current_weight = 0 last_equal_candies_total_number = 0 while alice_pos <= bob_pos: if alice_current_weight <= bob_current_weight: alice_current_weight += candies_weights[alice_pos] alice_pos += 1 else: bob_current_weight += candies_weights[bob_pos] bob_pos -= 1 if alice_current_weight == bob_current_weight: last_equal_candies_total_number = alice_pos + (number_of_candies - bob_pos - 1) print(last_equal_candies_total_number)
for i in range(int(input())): number_of_candies = int(input()) candies_weights = list(map(int, input().split())) bob_pos = number_of_candies - 1 alice_pos = 0 bob_current_weight = 0 alice_current_weight = 0 last_equal_candies_total_number = 0 while alice_pos <= bob_pos: if alice_current_weight <= bob_current_weight: alice_current_weight += candies_weights[alice_pos] alice_pos += 1 else: bob_current_weight += candies_weights[bob_pos] bob_pos -= 1 if alice_current_weight == bob_current_weight: last_equal_candies_total_number = alice_pos + (number_of_candies - bob_pos - 1) print(last_equal_candies_total_number)
# -------------- # Code starts here # Create the lists class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio'] class_2 = ['hilary mason', 'carla gentry', 'corinna cortes'] # Concatenate both the strings new_class = class_1+class_2 print(new_class) # Append the list new_class.append('peter warden') # Print updated list print(new_class) # Remove the element from the list new_class.remove('carla gentry') # Print the list print(new_class) # Create the Dictionary courses = {"math": 65, "english": 70, "history": 80, "french": 70, "science":60} # Slice the dict and stores the all subjects marks in variable total = 65+70+80+70+60 print(total) # Store the all the subject in one variable `Total` # Print the total # Insert percentage formula percentage =float(total)*(100/500) # Print the percentage print(percentage) # Create the Dictionary mathematics = {"geoffery hinton" :78, "andrew ng" :95, "sebastian raschka" :65, "yoshua benjio" :50, "hilary mason" :70, "corinna cortes" :66, "peter warden" :75} topper = max(mathematics,key = mathematics.get) print(topper) # Given string print(topper.split()) # Create variable first_name first_name = 'andrew' # Create variable Last_name and store last two element in the list Last_name ='ng' # Concatenate the string full_name = Last_name+' '+first_name # print the full_name print(full_name) # print the name in upper case certificate_name = full_name.upper() print(certificate_name) # Code ends here
class_1 = ['geoffrey hinton', 'andrew ng', 'sebastian raschka', 'yoshu bengio'] class_2 = ['hilary mason', 'carla gentry', 'corinna cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('peter warden') print(new_class) new_class.remove('carla gentry') print(new_class) courses = {'math': 65, 'english': 70, 'history': 80, 'french': 70, 'science': 60} total = 65 + 70 + 80 + 70 + 60 print(total) percentage = float(total) * (100 / 500) print(percentage) mathematics = {'geoffery hinton': 78, 'andrew ng': 95, 'sebastian raschka': 65, 'yoshua benjio': 50, 'hilary mason': 70, 'corinna cortes': 66, 'peter warden': 75} topper = max(mathematics, key=mathematics.get) print(topper) print(topper.split()) first_name = 'andrew' last_name = 'ng' full_name = Last_name + ' ' + first_name print(full_name) certificate_name = full_name.upper() print(certificate_name)
# # PySNMP MIB module Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB # Produced by pysmi-0.3.4 at Wed May 1 14:31:21 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint") mscMod, mscModIndex = mibBuilder.importSymbols("Nortel-MsCarrier-MscPassport-BaseShelfMIB", "mscMod", "mscModIndex") DisplayString, RowStatus, StorageType, Unsigned32, Integer32 = mibBuilder.importSymbols("Nortel-MsCarrier-MscPassport-StandardTextualConventionsMIB", "DisplayString", "RowStatus", "StorageType", "Unsigned32", "Integer32") DigitString, NonReplicated = mibBuilder.importSymbols("Nortel-MsCarrier-MscPassport-TextualConventionsMIB", "DigitString", "NonReplicated") mscPassportMIBs, = mibBuilder.importSymbols("Nortel-MsCarrier-MscPassport-UsefulDefinitionsMIB", "mscPassportMIBs") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, Counter64, IpAddress, ObjectIdentity, Bits, iso, Unsigned32, Gauge32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Integer32, TimeTicks, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Counter64", "IpAddress", "ObjectIdentity", "Bits", "iso", "Unsigned32", "Gauge32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Integer32", "TimeTicks", "ModuleIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") subnetInterfaceMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45)) mscModVcs = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2)) mscModVcsRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1), ) if mibBuilder.loadTexts: mscModVcsRowStatusTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsRowStatusTable.setDescription('This entry controls the addition and deletion of mscModVcs components.') mscModVcsRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1), ).setIndexNames((0, "Nortel-MsCarrier-MscPassport-BaseShelfMIB", "mscModIndex"), (0, "Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", "mscModVcsIndex")) if mibBuilder.loadTexts: mscModVcsRowStatusEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsRowStatusEntry.setDescription('A single entry in the table represents a single mscModVcs component.') mscModVcsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 1), RowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsRowStatus.setDescription('This variable is used as the basis for SNMP naming of mscModVcs components. These components can be added and deleted.') mscModVcsComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: mscModVcsComponentName.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface") mscModVcsStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 4), StorageType()).setMaxAccess("readonly") if mibBuilder.loadTexts: mscModVcsStorageType.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsStorageType.setDescription('This variable represents the storage type value for the mscModVcs tables.') mscModVcsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 10), NonReplicated()) if mibBuilder.loadTexts: mscModVcsIndex.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsIndex.setDescription('This variable represents the index for the mscModVcs tables.') mscModVcsAccOptTable = MibTable((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10), ) if mibBuilder.loadTexts: mscModVcsAccOptTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAccOptTable.setDescription("Accounting information is owned by the Vc System; it is stored in the Vc Accounting component, which itself is considered to be a component on the switch. The Accounting Component contains a bit map indicating which of the accounting facilities are to be spooled in the accounting record - for example, bit '0' if set indicates that the accounting facility with facility code H.00 should be spooled if present in the Vc for accounting purposes. The data contained in the Vc Accounting must be identical network wide even though the component can be changed and upgraded on a module by module basis.") mscModVcsAccOptEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1), ).setIndexNames((0, "Nortel-MsCarrier-MscPassport-BaseShelfMIB", "mscModIndex"), (0, "Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", "mscModVcsIndex")) if mibBuilder.loadTexts: mscModVcsAccOptEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAccOptEntry.setDescription('An entry in the mscModVcsAccOptTable.') mscModVcsSegmentSize = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("n1", 0), ("n2", 1), ("n4", 2), ("n8", 3), ("n16", 4), ("n32", 5), ("n64", 6), ("n128", 7), ("n256", 8), ("n512", 9), ("n1024", 10), ("n2048", 11), ("n4096", 12))).clone('n128')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsSegmentSize.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsSegmentSize.setDescription('This attribute specifies the segment size for accounting of national calls. Minimum allowed segment size is 1. If data segment is sent which is less than segmentSize it is still counted as one segment.') mscModVcsUnitsCounted = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("segments", 0), ("frames", 1))).clone('segments')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsUnitsCounted.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsUnitsCounted.setDescription('This attribute specifies what is counted by frame services. If set to frames, frames are counted, else segments are counted.') mscModVcsAccountingFax = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1).clone(hexValue="20")).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsAccountingFax.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAccountingFax.setDescription('Each value corresponds to an accounting facility code, of which there are currently 10 facility codes defined with codes H.00 to H.09, and corresponding to the above 10 facilities. Each of the above facilities may or may not be present and stored in the Vc for accounting purposes, depending on the nature of the call. For example, only those Vcs where a NUI (Network User Identifier) is used for charging or identification purposes will have a NUI stored in the Vc. Description of bits: notused0(0) notused1(1) originalCalledAddressFax(2)') mscModVcsGenerationMode = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("bothEnds", 0), ("singleEnd", 1))).clone('singleEnd')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsGenerationMode.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsGenerationMode.setDescription('This attribute specifies part of the rules by which the network generates accounting records. If set to bothEnds, then both ends of the Vc generate accounting records. If set to singleEnd, then the charged end of the Vc generates accounting records. In single end generation mode, if the call does not clear gracefully, both ends of the Vc will generate accounting record.') mscModVcsAddOptTable = MibTable((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12), ) if mibBuilder.loadTexts: mscModVcsAddOptTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAddOptTable.setDescription('The Vc AddressingOptions group describes the addressing parameters. It is currently owned by the Vc. Most of the data contained in the Vc AddressingOptions group is identical network wide even though the group can be changed and upgraded on a module by module basis.') mscModVcsAddOptEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1), ).setIndexNames((0, "Nortel-MsCarrier-MscPassport-BaseShelfMIB", "mscModIndex"), (0, "Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", "mscModVcsIndex")) if mibBuilder.loadTexts: mscModVcsAddOptEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAddOptEntry.setDescription('An entry in the mscModVcsAddOptTable.') mscModVcsDefaultNumberingPlan = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("x121", 0), ("e164", 1))).clone('x121')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsDefaultNumberingPlan.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsDefaultNumberingPlan.setDescription('This attribute specifies the numbering plan used which determines the address format: X.121-- the international numbering plan for public packet switched data networks or E.164-- the international numbering plan for ISDN and PSTN. The default numbering plan does not need to be consistent across all of the nodes in the network.') mscModVcsNetworkIdType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("dnic", 0), ("inic", 1))).clone('dnic')).setMaxAccess("readonly") if mibBuilder.loadTexts: mscModVcsNetworkIdType.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsNetworkIdType.setDescription('This attribute specifies whether the network uses a DNIC or INIC. It is used by X.75 Gateways to indicate whether in network the DNIC or INIC is used in various utilities. If it is DNIC it can be DNIC or DCC type. If it is INIC it can be 4 digits only.') mscModVcsX121Type = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("dnic", 0), ("dcc", 1))).clone('dnic')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsX121Type.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121Type.setDescription('This attribute specifies whether DNIC mode or DCC mode is used in X.121 address of international calls. If DCC is specified, then the first 3 digits of each DNA must be the Network ID Code. If this attribute is changed all Dnas in the network must start with this code. Numbering plan is affected by the change.') mscModVcsNetworkIdCode = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 6), DigitString().subtype(subtypeSpec=ValueSizeConstraint(3, 4))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsNetworkIdCode.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsNetworkIdCode.setDescription('This attribute specifies the DNIC (Data Network ID Code) of the network or DCC code.') mscModVcsX121IntlAddresses = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disallowed", 0), ("allowed", 1))).clone('allowed')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsX121IntlAddresses.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121IntlAddresses.setDescription('This attribute indicates if any DTE is allowed to signal international addresses.') mscModVcsX121IntllPrefixDigit = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 8), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 9)).clone(9)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsX121IntllPrefixDigit.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121IntllPrefixDigit.setDescription('This attribute indicates the prefix digit to be used for X.121 international calls. When this digit is provided the call will have full international address.') mscModVcsX121MinAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 11), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsX121MinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121MinAddressLength.setDescription('This attribute indicates minimum length of x121 address.') mscModVcsX121MaxAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 12), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(15)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsX121MaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121MaxAddressLength.setDescription('This attribute indicates maximum length of x121 address.') mscModVcsX121ToE164EscapeSignificance = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no", 0), ("yes", 1))).clone('no')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsX121ToE164EscapeSignificance.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121ToE164EscapeSignificance.setDescription('This attribute specifies whether an X.121 to E.164 escape digit has significance in selecting an X.32 (analog) or an ISDN switched path. If two values are significant (the value 0 or the value 9) then yes is set to this attribute. If the value of the originally entered escape digit is not significant in routing the call then value of no is assigned to this attribute.') mscModVcsE164IntlFormatAllowed = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disallowed", 0), ("allowed", 1))).clone('allowed')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164IntlFormatAllowed.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlFormatAllowed.setDescription("This attribute indicates whether or not to allow national format E.164 addresses. If this attribute is set to a value of Yes (=1) then national format E.164 addresses are not allowed and international format addresses only are allowed. If this attribute is set to a value of No (=0), then national format E.164 addresses are allowed. If only international format E.164 addresses are allowed, then the 'e164NatlPrefixDigit' attribute is not required, nor is the 'e164IntlPrefixDigits' required.") mscModVcsE164IntlPrefixDigits = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 15), DigitString().subtype(subtypeSpec=ValueSizeConstraint(0, 3)).clone(hexValue="30")).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164IntlPrefixDigits.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlPrefixDigits.setDescription("This attribute specifies the E.164 international prefix digits. If applicable, it is specified as 1 to 3 BCD digits. The 3 BCD digits are stored with the length of the international prefix in the low order nibble, nibble [0] followed by the most significant digit of the international prefix in the next low order nibble, nibble [1], etc. This attribute is not required if the corresponding attribute, 'e164IntlFormatOnly' is set to a value of Yes (=1).") mscModVcsE164NatlPrefixDigit = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 16), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 9)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164NatlPrefixDigit.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164NatlPrefixDigit.setDescription('This attribute contains the E.164 national prefix which may be added in front of E.164 local or national call. If e164IntlFormatOnly is set to 1, this attribute is not needed.') mscModVcsE164LocalAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 17), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(4, 15)).clone(7)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164LocalAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164LocalAddressLength.setDescription('This attribute indicates the length of a local E.164 DNA on this module. This attribute is not required if the corresponding attribute, e164IntlFormatOnly is set to a value of yes. This attribute does not need to be consistent across all of the nodes in the network.') mscModVcsE164TeleCountryCode = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 18), DigitString().subtype(subtypeSpec=ValueSizeConstraint(1, 4)).clone(hexValue="31")).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164TeleCountryCode.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164TeleCountryCode.setDescription('This attribute specifies the E.164 Telephone Country Code (TCC) for the country in which the network resides. If applicable, it is specified as 1 to 3 BCD digits. The 3 BCD digits are stored with the length of the TCC in the low order nibble, nibble [0] followed by the most significant digit of the TCC in the next low order nibble, nibble [1], etc.') mscModVcsE164NatlMinAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 20), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164NatlMinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164NatlMinAddressLength.setDescription('This attribute indicates minimum length of e164 national address.') mscModVcsE164NatlMaxAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 21), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(15)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164NatlMaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164NatlMaxAddressLength.setDescription('This attribute indicates maximum length of e164 national address.') mscModVcsE164IntlMinAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 22), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164IntlMinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlMinAddressLength.setDescription('This attribute indicates minimum length of e164 international address.') mscModVcsE164IntlMaxAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 23), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(15)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164IntlMaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlMaxAddressLength.setDescription('This attribute indicates maximum length of e164 international address.') mscModVcsE164LocalMinAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 24), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164LocalMinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164LocalMinAddressLength.setDescription('This attribute indicates minimum length of e164 local address.') mscModVcsE164LocalMaxAddressLength = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 25), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16)).clone(15)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsE164LocalMaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164LocalMaxAddressLength.setDescription('This attribute indicates maximum length of e164 local address.') mscModVcsIntOptTable = MibTable((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13), ) if mibBuilder.loadTexts: mscModVcsIntOptTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsIntOptTable.setDescription('The Vc InterfaceOptions group defines Vc system parameters common in the network. It is owned by the Vc and is considered to be a module wide component on the switch. The data contained in the Vc InterfaceOptions group must be identical network wide even though this group can be changed and upgraded on a module by module basis.') mscModVcsIntOptEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1), ).setIndexNames((0, "Nortel-MsCarrier-MscPassport-BaseShelfMIB", "mscModIndex"), (0, "Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", "mscModVcsIndex")) if mibBuilder.loadTexts: mscModVcsIntOptEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsIntOptEntry.setDescription('An entry in the mscModVcsIntOptTable.') mscModVcsHighPriorityPacketSizes = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2).clone(hexValue="ff80")).setMaxAccess("readonly") if mibBuilder.loadTexts: mscModVcsHighPriorityPacketSizes.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsHighPriorityPacketSizes.setDescription('This attribute indicates which packet sizes are supported for high priority calls within the network. Description of bits: n16(0) n32(1) n64(2) n128(3) n256(4) n512(5) n1024(6) n2048(7) n4096(8)') mscModVcsMaxSubnetPacketSize = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=NamedValues(("n16", 4), ("n32", 5), ("n64", 6), ("n128", 7), ("n256", 8), ("n512", 9), ("n1024", 10), ("n2048", 11), ("n4096", 12))).clone('n512')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsMaxSubnetPacketSize.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsMaxSubnetPacketSize.setDescription('This attribute specifies the maximum subnet packet size used for the connections originating or terminating on this module. All modules in the same network should have the same maxSubnetPacketSize. If this value is not identical throughout the network, the following points need to be considered: a) When Passport and DPN switches are connected in the same network, the maxSubnetPacketSize on a DPN switch can be at most 2048 and the DPN part of the network must be configured with hardware which supports this size: - Dedicated PE386 Network link/Trunk - Minimum measured link speed of 256Kbits/sec This hardware has to be present on every potential data path between connecting end points! b) The calling end of the connection signals the maxSubnetPacketSize value to the called end. The called end then compares this value to its own provisioned value and selects the smaller value. Note that this smaller value is not signalled back to the calling end. The calling and called ends can therefore have different maxSubnetPacketSize values.') mscModVcsCallSetupTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(5, 100)).clone(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsCallSetupTimer.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsCallSetupTimer.setDescription('This attribute specifies the Vc callSetupTimer in units of 1 second ticks. This timer specifies how long the Vc will wait, after sending a subnet Call Request packet into the network, for a response from the remote end of the Vc (in the form of a subnet Raccept packet). If, after sending a subnet Call packet into the network, a response is not received within this time period, the Vc will time out, clearing the call in the assumption that the remote end is unreachable. This timer must be long enough to take into account the time required for routing the subnet Call Request through the Source Call Routing and the Destination Call Routing systems in order to be delivered to the final destination.') mscModVcsCallRetryTimer = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(30, 300)).clone(60)).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsCallRetryTimer.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsCallRetryTimer.setDescription('This attribute specifies, for Vc implementing Direct Calls with the auto-call retry feature (including PVCs), the Vc callRetryTimer in units of 1 second ticks. This timer specifies how long the Vc will wait between unsuccessful call attempts.') mscModVcsDelaySubnetAcks = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no", 0), ("yes", 1))).clone('no')).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsDelaySubnetAcks.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsDelaySubnetAcks.setDescription('This attribute specifies delay acknowledgment timer mechanism. If this attribute is set to no, then the Vc will automatically return acknowledgment packets without delay. If this attribute is set to yes, then the Vc will wait for one second in an attempt to piggyback the acknowledgment packet on another credit or data packet. If the Vc cannot piggyback the acknowledgment packet within this time, then the packet is returned without piggybacking.') mscModVcsWinsTable = MibTable((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213), ) if mibBuilder.loadTexts: mscModVcsWinsTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsTable.setDescription('This is the windowSize corresponding to the given packet size and throughput class. All Vcs using the windowSize matrix support large Vc windows on both ends of the Vc, and support the signalling of the chosen Vc window size from the destination (called) end to the source (calling) end. This is the only matrix supported. The windowSize should be configured in the same way network wide, though it can be upgraded on a module by module basis. Vcs using the windowSize matrix will run properly if the matrices on different nodes differ since the Vc window is selected by the destination (called) side of the Vc.') mscModVcsWinsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1), ).setIndexNames((0, "Nortel-MsCarrier-MscPassport-BaseShelfMIB", "mscModIndex"), (0, "Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", "mscModVcsIndex"), (0, "Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", "mscModVcsWinsPktIndex"), (0, "Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", "mscModVcsWinsTptIndex")) if mibBuilder.loadTexts: mscModVcsWinsEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsEntry.setDescription('An entry in the mscModVcsWinsTable.') mscModVcsWinsPktIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=NamedValues(("n16", 0), ("n32", 1), ("n64", 2), ("n128", 3), ("n256", 4), ("n512", 5), ("n1024", 6), ("n2048", 7), ("n4096", 8), ("n8192", 9), ("n32768", 10), ("n65535", 11)))) if mibBuilder.loadTexts: mscModVcsWinsPktIndex.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsPktIndex.setDescription('This variable represents the next to last index for the mscModVcsWinsTable.') mscModVcsWinsTptIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15))) if mibBuilder.loadTexts: mscModVcsWinsTptIndex.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsTptIndex.setDescription('This variable represents the final index for the mscModVcsWinsTable.') mscModVcsWinsValue = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 63))).setMaxAccess("readwrite") if mibBuilder.loadTexts: mscModVcsWinsValue.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsValue.setDescription('This variable represents an individual value for the mscModVcsWinsTable.') subnetInterfaceGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1)) subnetInterfaceGroupCA = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1, 1)) subnetInterfaceGroupCA02 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1, 1, 3)) subnetInterfaceGroupCA02A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1, 1, 3, 2)) subnetInterfaceCapabilities = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3)) subnetInterfaceCapabilitiesCA = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3, 1)) subnetInterfaceCapabilitiesCA02 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3, 1, 3)) subnetInterfaceCapabilitiesCA02A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3, 1, 3, 2)) mibBuilder.exportSymbols("Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB", mscModVcsStorageType=mscModVcsStorageType, mscModVcs=mscModVcs, mscModVcsRowStatusEntry=mscModVcsRowStatusEntry, mscModVcsX121MinAddressLength=mscModVcsX121MinAddressLength, mscModVcsRowStatus=mscModVcsRowStatus, mscModVcsE164NatlMinAddressLength=mscModVcsE164NatlMinAddressLength, mscModVcsAccOptTable=mscModVcsAccOptTable, mscModVcsE164LocalAddressLength=mscModVcsE164LocalAddressLength, mscModVcsE164IntlMinAddressLength=mscModVcsE164IntlMinAddressLength, mscModVcsE164IntlMaxAddressLength=mscModVcsE164IntlMaxAddressLength, mscModVcsE164LocalMaxAddressLength=mscModVcsE164LocalMaxAddressLength, mscModVcsWinsTptIndex=mscModVcsWinsTptIndex, mscModVcsE164IntlPrefixDigits=mscModVcsE164IntlPrefixDigits, mscModVcsComponentName=mscModVcsComponentName, mscModVcsIndex=mscModVcsIndex, subnetInterfaceGroupCA=subnetInterfaceGroupCA, mscModVcsX121IntllPrefixDigit=mscModVcsX121IntllPrefixDigit, mscModVcsDelaySubnetAcks=mscModVcsDelaySubnetAcks, mscModVcsX121Type=mscModVcsX121Type, mscModVcsWinsTable=mscModVcsWinsTable, mscModVcsE164NatlPrefixDigit=mscModVcsE164NatlPrefixDigit, subnetInterfaceMIB=subnetInterfaceMIB, mscModVcsAccountingFax=mscModVcsAccountingFax, mscModVcsMaxSubnetPacketSize=mscModVcsMaxSubnetPacketSize, mscModVcsAddOptTable=mscModVcsAddOptTable, mscModVcsWinsValue=mscModVcsWinsValue, subnetInterfaceCapabilitiesCA02A=subnetInterfaceCapabilitiesCA02A, subnetInterfaceCapabilities=subnetInterfaceCapabilities, subnetInterfaceGroupCA02=subnetInterfaceGroupCA02, subnetInterfaceCapabilitiesCA=subnetInterfaceCapabilitiesCA, mscModVcsX121MaxAddressLength=mscModVcsX121MaxAddressLength, mscModVcsE164IntlFormatAllowed=mscModVcsE164IntlFormatAllowed, subnetInterfaceGroup=subnetInterfaceGroup, mscModVcsSegmentSize=mscModVcsSegmentSize, mscModVcsX121IntlAddresses=mscModVcsX121IntlAddresses, mscModVcsGenerationMode=mscModVcsGenerationMode, mscModVcsWinsEntry=mscModVcsWinsEntry, mscModVcsUnitsCounted=mscModVcsUnitsCounted, mscModVcsNetworkIdType=mscModVcsNetworkIdType, mscModVcsAccOptEntry=mscModVcsAccOptEntry, mscModVcsAddOptEntry=mscModVcsAddOptEntry, mscModVcsX121ToE164EscapeSignificance=mscModVcsX121ToE164EscapeSignificance, mscModVcsDefaultNumberingPlan=mscModVcsDefaultNumberingPlan, mscModVcsIntOptTable=mscModVcsIntOptTable, mscModVcsCallRetryTimer=mscModVcsCallRetryTimer, mscModVcsWinsPktIndex=mscModVcsWinsPktIndex, mscModVcsCallSetupTimer=mscModVcsCallSetupTimer, mscModVcsE164NatlMaxAddressLength=mscModVcsE164NatlMaxAddressLength, subnetInterfaceGroupCA02A=subnetInterfaceGroupCA02A, mscModVcsNetworkIdCode=mscModVcsNetworkIdCode, mscModVcsE164TeleCountryCode=mscModVcsE164TeleCountryCode, mscModVcsIntOptEntry=mscModVcsIntOptEntry, subnetInterfaceCapabilitiesCA02=subnetInterfaceCapabilitiesCA02, mscModVcsE164LocalMinAddressLength=mscModVcsE164LocalMinAddressLength, mscModVcsRowStatusTable=mscModVcsRowStatusTable, mscModVcsHighPriorityPacketSizes=mscModVcsHighPriorityPacketSizes)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, constraints_intersection, single_value_constraint, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint') (msc_mod, msc_mod_index) = mibBuilder.importSymbols('Nortel-MsCarrier-MscPassport-BaseShelfMIB', 'mscMod', 'mscModIndex') (display_string, row_status, storage_type, unsigned32, integer32) = mibBuilder.importSymbols('Nortel-MsCarrier-MscPassport-StandardTextualConventionsMIB', 'DisplayString', 'RowStatus', 'StorageType', 'Unsigned32', 'Integer32') (digit_string, non_replicated) = mibBuilder.importSymbols('Nortel-MsCarrier-MscPassport-TextualConventionsMIB', 'DigitString', 'NonReplicated') (msc_passport_mi_bs,) = mibBuilder.importSymbols('Nortel-MsCarrier-MscPassport-UsefulDefinitionsMIB', 'mscPassportMIBs') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (counter32, counter64, ip_address, object_identity, bits, iso, unsigned32, gauge32, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, integer32, time_ticks, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'Counter64', 'IpAddress', 'ObjectIdentity', 'Bits', 'iso', 'Unsigned32', 'Gauge32', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Integer32', 'TimeTicks', 'ModuleIdentity') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') subnet_interface_mib = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45)) msc_mod_vcs = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2)) msc_mod_vcs_row_status_table = mib_table((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1)) if mibBuilder.loadTexts: mscModVcsRowStatusTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsRowStatusTable.setDescription('This entry controls the addition and deletion of mscModVcs components.') msc_mod_vcs_row_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1)).setIndexNames((0, 'Nortel-MsCarrier-MscPassport-BaseShelfMIB', 'mscModIndex'), (0, 'Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', 'mscModVcsIndex')) if mibBuilder.loadTexts: mscModVcsRowStatusEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsRowStatusEntry.setDescription('A single entry in the table represents a single mscModVcs component.') msc_mod_vcs_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 1), row_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsRowStatus.setDescription('This variable is used as the basis for SNMP naming of mscModVcs components. These components can be added and deleted.') msc_mod_vcs_component_name = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 2), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: mscModVcsComponentName.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface") msc_mod_vcs_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 4), storage_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: mscModVcsStorageType.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsStorageType.setDescription('This variable represents the storage type value for the mscModVcs tables.') msc_mod_vcs_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 1, 1, 10), non_replicated()) if mibBuilder.loadTexts: mscModVcsIndex.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsIndex.setDescription('This variable represents the index for the mscModVcs tables.') msc_mod_vcs_acc_opt_table = mib_table((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10)) if mibBuilder.loadTexts: mscModVcsAccOptTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAccOptTable.setDescription("Accounting information is owned by the Vc System; it is stored in the Vc Accounting component, which itself is considered to be a component on the switch. The Accounting Component contains a bit map indicating which of the accounting facilities are to be spooled in the accounting record - for example, bit '0' if set indicates that the accounting facility with facility code H.00 should be spooled if present in the Vc for accounting purposes. The data contained in the Vc Accounting must be identical network wide even though the component can be changed and upgraded on a module by module basis.") msc_mod_vcs_acc_opt_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1)).setIndexNames((0, 'Nortel-MsCarrier-MscPassport-BaseShelfMIB', 'mscModIndex'), (0, 'Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', 'mscModVcsIndex')) if mibBuilder.loadTexts: mscModVcsAccOptEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAccOptEntry.setDescription('An entry in the mscModVcsAccOptTable.') msc_mod_vcs_segment_size = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=named_values(('n1', 0), ('n2', 1), ('n4', 2), ('n8', 3), ('n16', 4), ('n32', 5), ('n64', 6), ('n128', 7), ('n256', 8), ('n512', 9), ('n1024', 10), ('n2048', 11), ('n4096', 12))).clone('n128')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsSegmentSize.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsSegmentSize.setDescription('This attribute specifies the segment size for accounting of national calls. Minimum allowed segment size is 1. If data segment is sent which is less than segmentSize it is still counted as one segment.') msc_mod_vcs_units_counted = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('segments', 0), ('frames', 1))).clone('segments')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsUnitsCounted.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsUnitsCounted.setDescription('This attribute specifies what is counted by frame services. If set to frames, frames are counted, else segments are counted.') msc_mod_vcs_accounting_fax = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(1, 1)).setFixedLength(1).clone(hexValue='20')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsAccountingFax.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAccountingFax.setDescription('Each value corresponds to an accounting facility code, of which there are currently 10 facility codes defined with codes H.00 to H.09, and corresponding to the above 10 facilities. Each of the above facilities may or may not be present and stored in the Vc for accounting purposes, depending on the nature of the call. For example, only those Vcs where a NUI (Network User Identifier) is used for charging or identification purposes will have a NUI stored in the Vc. Description of bits: notused0(0) notused1(1) originalCalledAddressFax(2)') msc_mod_vcs_generation_mode = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 10, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('bothEnds', 0), ('singleEnd', 1))).clone('singleEnd')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsGenerationMode.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsGenerationMode.setDescription('This attribute specifies part of the rules by which the network generates accounting records. If set to bothEnds, then both ends of the Vc generate accounting records. If set to singleEnd, then the charged end of the Vc generates accounting records. In single end generation mode, if the call does not clear gracefully, both ends of the Vc will generate accounting record.') msc_mod_vcs_add_opt_table = mib_table((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12)) if mibBuilder.loadTexts: mscModVcsAddOptTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAddOptTable.setDescription('The Vc AddressingOptions group describes the addressing parameters. It is currently owned by the Vc. Most of the data contained in the Vc AddressingOptions group is identical network wide even though the group can be changed and upgraded on a module by module basis.') msc_mod_vcs_add_opt_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1)).setIndexNames((0, 'Nortel-MsCarrier-MscPassport-BaseShelfMIB', 'mscModIndex'), (0, 'Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', 'mscModVcsIndex')) if mibBuilder.loadTexts: mscModVcsAddOptEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsAddOptEntry.setDescription('An entry in the mscModVcsAddOptTable.') msc_mod_vcs_default_numbering_plan = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('x121', 0), ('e164', 1))).clone('x121')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsDefaultNumberingPlan.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsDefaultNumberingPlan.setDescription('This attribute specifies the numbering plan used which determines the address format: X.121-- the international numbering plan for public packet switched data networks or E.164-- the international numbering plan for ISDN and PSTN. The default numbering plan does not need to be consistent across all of the nodes in the network.') msc_mod_vcs_network_id_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('dnic', 0), ('inic', 1))).clone('dnic')).setMaxAccess('readonly') if mibBuilder.loadTexts: mscModVcsNetworkIdType.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsNetworkIdType.setDescription('This attribute specifies whether the network uses a DNIC or INIC. It is used by X.75 Gateways to indicate whether in network the DNIC or INIC is used in various utilities. If it is DNIC it can be DNIC or DCC type. If it is INIC it can be 4 digits only.') msc_mod_vcs_x121_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('dnic', 0), ('dcc', 1))).clone('dnic')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsX121Type.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121Type.setDescription('This attribute specifies whether DNIC mode or DCC mode is used in X.121 address of international calls. If DCC is specified, then the first 3 digits of each DNA must be the Network ID Code. If this attribute is changed all Dnas in the network must start with this code. Numbering plan is affected by the change.') msc_mod_vcs_network_id_code = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 6), digit_string().subtype(subtypeSpec=value_size_constraint(3, 4))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsNetworkIdCode.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsNetworkIdCode.setDescription('This attribute specifies the DNIC (Data Network ID Code) of the network or DCC code.') msc_mod_vcs_x121_intl_addresses = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disallowed', 0), ('allowed', 1))).clone('allowed')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsX121IntlAddresses.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121IntlAddresses.setDescription('This attribute indicates if any DTE is allowed to signal international addresses.') msc_mod_vcs_x121_intll_prefix_digit = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 8), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 9)).clone(9)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsX121IntllPrefixDigit.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121IntllPrefixDigit.setDescription('This attribute indicates the prefix digit to be used for X.121 international calls. When this digit is provided the call will have full international address.') msc_mod_vcs_x121_min_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 11), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsX121MinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121MinAddressLength.setDescription('This attribute indicates minimum length of x121 address.') msc_mod_vcs_x121_max_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 12), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(15)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsX121MaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121MaxAddressLength.setDescription('This attribute indicates maximum length of x121 address.') msc_mod_vcs_x121_to_e164_escape_significance = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 13), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('no', 0), ('yes', 1))).clone('no')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsX121ToE164EscapeSignificance.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsX121ToE164EscapeSignificance.setDescription('This attribute specifies whether an X.121 to E.164 escape digit has significance in selecting an X.32 (analog) or an ISDN switched path. If two values are significant (the value 0 or the value 9) then yes is set to this attribute. If the value of the originally entered escape digit is not significant in routing the call then value of no is assigned to this attribute.') msc_mod_vcs_e164_intl_format_allowed = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disallowed', 0), ('allowed', 1))).clone('allowed')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164IntlFormatAllowed.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlFormatAllowed.setDescription("This attribute indicates whether or not to allow national format E.164 addresses. If this attribute is set to a value of Yes (=1) then national format E.164 addresses are not allowed and international format addresses only are allowed. If this attribute is set to a value of No (=0), then national format E.164 addresses are allowed. If only international format E.164 addresses are allowed, then the 'e164NatlPrefixDigit' attribute is not required, nor is the 'e164IntlPrefixDigits' required.") msc_mod_vcs_e164_intl_prefix_digits = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 15), digit_string().subtype(subtypeSpec=value_size_constraint(0, 3)).clone(hexValue='30')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164IntlPrefixDigits.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlPrefixDigits.setDescription("This attribute specifies the E.164 international prefix digits. If applicable, it is specified as 1 to 3 BCD digits. The 3 BCD digits are stored with the length of the international prefix in the low order nibble, nibble [0] followed by the most significant digit of the international prefix in the next low order nibble, nibble [1], etc. This attribute is not required if the corresponding attribute, 'e164IntlFormatOnly' is set to a value of Yes (=1).") msc_mod_vcs_e164_natl_prefix_digit = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 16), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 9)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164NatlPrefixDigit.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164NatlPrefixDigit.setDescription('This attribute contains the E.164 national prefix which may be added in front of E.164 local or national call. If e164IntlFormatOnly is set to 1, this attribute is not needed.') msc_mod_vcs_e164_local_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 17), unsigned32().subtype(subtypeSpec=value_range_constraint(4, 15)).clone(7)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164LocalAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164LocalAddressLength.setDescription('This attribute indicates the length of a local E.164 DNA on this module. This attribute is not required if the corresponding attribute, e164IntlFormatOnly is set to a value of yes. This attribute does not need to be consistent across all of the nodes in the network.') msc_mod_vcs_e164_tele_country_code = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 18), digit_string().subtype(subtypeSpec=value_size_constraint(1, 4)).clone(hexValue='31')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164TeleCountryCode.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164TeleCountryCode.setDescription('This attribute specifies the E.164 Telephone Country Code (TCC) for the country in which the network resides. If applicable, it is specified as 1 to 3 BCD digits. The 3 BCD digits are stored with the length of the TCC in the low order nibble, nibble [0] followed by the most significant digit of the TCC in the next low order nibble, nibble [1], etc.') msc_mod_vcs_e164_natl_min_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 20), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164NatlMinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164NatlMinAddressLength.setDescription('This attribute indicates minimum length of e164 national address.') msc_mod_vcs_e164_natl_max_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 21), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(15)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164NatlMaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164NatlMaxAddressLength.setDescription('This attribute indicates maximum length of e164 national address.') msc_mod_vcs_e164_intl_min_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 22), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164IntlMinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlMinAddressLength.setDescription('This attribute indicates minimum length of e164 international address.') msc_mod_vcs_e164_intl_max_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 23), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(15)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164IntlMaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164IntlMaxAddressLength.setDescription('This attribute indicates maximum length of e164 international address.') msc_mod_vcs_e164_local_min_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 24), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164LocalMinAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164LocalMinAddressLength.setDescription('This attribute indicates minimum length of e164 local address.') msc_mod_vcs_e164_local_max_address_length = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 12, 1, 25), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16)).clone(15)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsE164LocalMaxAddressLength.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsE164LocalMaxAddressLength.setDescription('This attribute indicates maximum length of e164 local address.') msc_mod_vcs_int_opt_table = mib_table((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13)) if mibBuilder.loadTexts: mscModVcsIntOptTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsIntOptTable.setDescription('The Vc InterfaceOptions group defines Vc system parameters common in the network. It is owned by the Vc and is considered to be a module wide component on the switch. The data contained in the Vc InterfaceOptions group must be identical network wide even though this group can be changed and upgraded on a module by module basis.') msc_mod_vcs_int_opt_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1)).setIndexNames((0, 'Nortel-MsCarrier-MscPassport-BaseShelfMIB', 'mscModIndex'), (0, 'Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', 'mscModVcsIndex')) if mibBuilder.loadTexts: mscModVcsIntOptEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsIntOptEntry.setDescription('An entry in the mscModVcsIntOptTable.') msc_mod_vcs_high_priority_packet_sizes = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 1), octet_string().subtype(subtypeSpec=value_size_constraint(2, 2)).setFixedLength(2).clone(hexValue='ff80')).setMaxAccess('readonly') if mibBuilder.loadTexts: mscModVcsHighPriorityPacketSizes.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsHighPriorityPacketSizes.setDescription('This attribute indicates which packet sizes are supported for high priority calls within the network. Description of bits: n16(0) n32(1) n64(2) n128(3) n256(4) n512(5) n1024(6) n2048(7) n4096(8)') msc_mod_vcs_max_subnet_packet_size = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(4, 5, 6, 7, 8, 9, 10, 11, 12))).clone(namedValues=named_values(('n16', 4), ('n32', 5), ('n64', 6), ('n128', 7), ('n256', 8), ('n512', 9), ('n1024', 10), ('n2048', 11), ('n4096', 12))).clone('n512')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsMaxSubnetPacketSize.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsMaxSubnetPacketSize.setDescription('This attribute specifies the maximum subnet packet size used for the connections originating or terminating on this module. All modules in the same network should have the same maxSubnetPacketSize. If this value is not identical throughout the network, the following points need to be considered: a) When Passport and DPN switches are connected in the same network, the maxSubnetPacketSize on a DPN switch can be at most 2048 and the DPN part of the network must be configured with hardware which supports this size: - Dedicated PE386 Network link/Trunk - Minimum measured link speed of 256Kbits/sec This hardware has to be present on every potential data path between connecting end points! b) The calling end of the connection signals the maxSubnetPacketSize value to the called end. The called end then compares this value to its own provisioned value and selects the smaller value. Note that this smaller value is not signalled back to the calling end. The calling and called ends can therefore have different maxSubnetPacketSize values.') msc_mod_vcs_call_setup_timer = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 3), unsigned32().subtype(subtypeSpec=value_range_constraint(5, 100)).clone(5)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsCallSetupTimer.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsCallSetupTimer.setDescription('This attribute specifies the Vc callSetupTimer in units of 1 second ticks. This timer specifies how long the Vc will wait, after sending a subnet Call Request packet into the network, for a response from the remote end of the Vc (in the form of a subnet Raccept packet). If, after sending a subnet Call packet into the network, a response is not received within this time period, the Vc will time out, clearing the call in the assumption that the remote end is unreachable. This timer must be long enough to take into account the time required for routing the subnet Call Request through the Source Call Routing and the Destination Call Routing systems in order to be delivered to the final destination.') msc_mod_vcs_call_retry_timer = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 4), unsigned32().subtype(subtypeSpec=value_range_constraint(30, 300)).clone(60)).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsCallRetryTimer.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsCallRetryTimer.setDescription('This attribute specifies, for Vc implementing Direct Calls with the auto-call retry feature (including PVCs), the Vc callRetryTimer in units of 1 second ticks. This timer specifies how long the Vc will wait between unsuccessful call attempts.') msc_mod_vcs_delay_subnet_acks = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 13, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('no', 0), ('yes', 1))).clone('no')).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsDelaySubnetAcks.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsDelaySubnetAcks.setDescription('This attribute specifies delay acknowledgment timer mechanism. If this attribute is set to no, then the Vc will automatically return acknowledgment packets without delay. If this attribute is set to yes, then the Vc will wait for one second in an attempt to piggyback the acknowledgment packet on another credit or data packet. If the Vc cannot piggyback the acknowledgment packet within this time, then the packet is returned without piggybacking.') msc_mod_vcs_wins_table = mib_table((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213)) if mibBuilder.loadTexts: mscModVcsWinsTable.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsTable.setDescription('This is the windowSize corresponding to the given packet size and throughput class. All Vcs using the windowSize matrix support large Vc windows on both ends of the Vc, and support the signalling of the chosen Vc window size from the destination (called) end to the source (calling) end. This is the only matrix supported. The windowSize should be configured in the same way network wide, though it can be upgraded on a module by module basis. Vcs using the windowSize matrix will run properly if the matrices on different nodes differ since the Vc window is selected by the destination (called) side of the Vc.') msc_mod_vcs_wins_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1)).setIndexNames((0, 'Nortel-MsCarrier-MscPassport-BaseShelfMIB', 'mscModIndex'), (0, 'Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', 'mscModVcsIndex'), (0, 'Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', 'mscModVcsWinsPktIndex'), (0, 'Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', 'mscModVcsWinsTptIndex')) if mibBuilder.loadTexts: mscModVcsWinsEntry.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsEntry.setDescription('An entry in the mscModVcsWinsTable.') msc_mod_vcs_wins_pkt_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=named_values(('n16', 0), ('n32', 1), ('n64', 2), ('n128', 3), ('n256', 4), ('n512', 5), ('n1024', 6), ('n2048', 7), ('n4096', 8), ('n8192', 9), ('n32768', 10), ('n65535', 11)))) if mibBuilder.loadTexts: mscModVcsWinsPktIndex.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsPktIndex.setDescription('This variable represents the next to last index for the mscModVcsWinsTable.') msc_mod_vcs_wins_tpt_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 15))) if mibBuilder.loadTexts: mscModVcsWinsTptIndex.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsTptIndex.setDescription('This variable represents the final index for the mscModVcsWinsTable.') msc_mod_vcs_wins_value = mib_table_column((1, 3, 6, 1, 4, 1, 562, 36, 2, 1, 16, 2, 213, 1, 3), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 63))).setMaxAccess('readwrite') if mibBuilder.loadTexts: mscModVcsWinsValue.setStatus('mandatory') if mibBuilder.loadTexts: mscModVcsWinsValue.setDescription('This variable represents an individual value for the mscModVcsWinsTable.') subnet_interface_group = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1)) subnet_interface_group_ca = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1, 1)) subnet_interface_group_ca02 = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1, 1, 3)) subnet_interface_group_ca02_a = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 1, 1, 3, 2)) subnet_interface_capabilities = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3)) subnet_interface_capabilities_ca = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3, 1)) subnet_interface_capabilities_ca02 = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3, 1, 3)) subnet_interface_capabilities_ca02_a = mib_identifier((1, 3, 6, 1, 4, 1, 562, 36, 2, 2, 45, 3, 1, 3, 2)) mibBuilder.exportSymbols('Nortel-MsCarrier-MscPassport-SubnetInterfaceMIB', mscModVcsStorageType=mscModVcsStorageType, mscModVcs=mscModVcs, mscModVcsRowStatusEntry=mscModVcsRowStatusEntry, mscModVcsX121MinAddressLength=mscModVcsX121MinAddressLength, mscModVcsRowStatus=mscModVcsRowStatus, mscModVcsE164NatlMinAddressLength=mscModVcsE164NatlMinAddressLength, mscModVcsAccOptTable=mscModVcsAccOptTable, mscModVcsE164LocalAddressLength=mscModVcsE164LocalAddressLength, mscModVcsE164IntlMinAddressLength=mscModVcsE164IntlMinAddressLength, mscModVcsE164IntlMaxAddressLength=mscModVcsE164IntlMaxAddressLength, mscModVcsE164LocalMaxAddressLength=mscModVcsE164LocalMaxAddressLength, mscModVcsWinsTptIndex=mscModVcsWinsTptIndex, mscModVcsE164IntlPrefixDigits=mscModVcsE164IntlPrefixDigits, mscModVcsComponentName=mscModVcsComponentName, mscModVcsIndex=mscModVcsIndex, subnetInterfaceGroupCA=subnetInterfaceGroupCA, mscModVcsX121IntllPrefixDigit=mscModVcsX121IntllPrefixDigit, mscModVcsDelaySubnetAcks=mscModVcsDelaySubnetAcks, mscModVcsX121Type=mscModVcsX121Type, mscModVcsWinsTable=mscModVcsWinsTable, mscModVcsE164NatlPrefixDigit=mscModVcsE164NatlPrefixDigit, subnetInterfaceMIB=subnetInterfaceMIB, mscModVcsAccountingFax=mscModVcsAccountingFax, mscModVcsMaxSubnetPacketSize=mscModVcsMaxSubnetPacketSize, mscModVcsAddOptTable=mscModVcsAddOptTable, mscModVcsWinsValue=mscModVcsWinsValue, subnetInterfaceCapabilitiesCA02A=subnetInterfaceCapabilitiesCA02A, subnetInterfaceCapabilities=subnetInterfaceCapabilities, subnetInterfaceGroupCA02=subnetInterfaceGroupCA02, subnetInterfaceCapabilitiesCA=subnetInterfaceCapabilitiesCA, mscModVcsX121MaxAddressLength=mscModVcsX121MaxAddressLength, mscModVcsE164IntlFormatAllowed=mscModVcsE164IntlFormatAllowed, subnetInterfaceGroup=subnetInterfaceGroup, mscModVcsSegmentSize=mscModVcsSegmentSize, mscModVcsX121IntlAddresses=mscModVcsX121IntlAddresses, mscModVcsGenerationMode=mscModVcsGenerationMode, mscModVcsWinsEntry=mscModVcsWinsEntry, mscModVcsUnitsCounted=mscModVcsUnitsCounted, mscModVcsNetworkIdType=mscModVcsNetworkIdType, mscModVcsAccOptEntry=mscModVcsAccOptEntry, mscModVcsAddOptEntry=mscModVcsAddOptEntry, mscModVcsX121ToE164EscapeSignificance=mscModVcsX121ToE164EscapeSignificance, mscModVcsDefaultNumberingPlan=mscModVcsDefaultNumberingPlan, mscModVcsIntOptTable=mscModVcsIntOptTable, mscModVcsCallRetryTimer=mscModVcsCallRetryTimer, mscModVcsWinsPktIndex=mscModVcsWinsPktIndex, mscModVcsCallSetupTimer=mscModVcsCallSetupTimer, mscModVcsE164NatlMaxAddressLength=mscModVcsE164NatlMaxAddressLength, subnetInterfaceGroupCA02A=subnetInterfaceGroupCA02A, mscModVcsNetworkIdCode=mscModVcsNetworkIdCode, mscModVcsE164TeleCountryCode=mscModVcsE164TeleCountryCode, mscModVcsIntOptEntry=mscModVcsIntOptEntry, subnetInterfaceCapabilitiesCA02=subnetInterfaceCapabilitiesCA02, mscModVcsE164LocalMinAddressLength=mscModVcsE164LocalMinAddressLength, mscModVcsRowStatusTable=mscModVcsRowStatusTable, mscModVcsHighPriorityPacketSizes=mscModVcsHighPriorityPacketSizes)
samples = { "2_brother_plays": { "question_parts": [range(1, 13), range(13, 17)], "sp_parts": [range(20, 43), range(50, 60)] } }
samples = {'2_brother_plays': {'question_parts': [range(1, 13), range(13, 17)], 'sp_parts': [range(20, 43), range(50, 60)]}}
class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzagLevelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] a = [root] b = [] c = [] r = [[root.val]] i = 1 while True: for n in a: if n.left: b.append(n.left) c.append(n.left.val) if n.right: b.append(n.right) c.append(n.right.val) if not b: break else: a = b if i & 1 == 1: c.reverse() r.append(c) b = [] c = [] i += 1 return r def test_zigzag_level_order(): a = TreeNode(3) b = TreeNode(9) c = TreeNode(20) d = TreeNode(15) e = TreeNode(7) a.left = b a.right = c c.left = d c.right = e assert Solution().zigzagLevelOrder(a) == [ [3], [20, 9], [15, 7] ]
class Treenode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def zigzag_level_order(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ if not root: return [] a = [root] b = [] c = [] r = [[root.val]] i = 1 while True: for n in a: if n.left: b.append(n.left) c.append(n.left.val) if n.right: b.append(n.right) c.append(n.right.val) if not b: break else: a = b if i & 1 == 1: c.reverse() r.append(c) b = [] c = [] i += 1 return r def test_zigzag_level_order(): a = tree_node(3) b = tree_node(9) c = tree_node(20) d = tree_node(15) e = tree_node(7) a.left = b a.right = c c.left = d c.right = e assert solution().zigzagLevelOrder(a) == [[3], [20, 9], [15, 7]]
def insert_metatable(): """SQL query to insert records from table insert into a table on a DB """ return """ INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES ('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0][0] }}, current_timestamp(), '{{ params.type }}'); """
def insert_metatable(): """SQL query to insert records from table insert into a table on a DB """ return "\n INSERT INTO TABLE {{ params.target_schema }}.{{ params.target_table }} VALUES \n ('{{ params.schema }}', '{{ params.table }}', {{ ti.xcom_pull(key='hive_res', task_ids=params.count_inserts)[0][0] }}, current_timestamp(), '{{ params.type }}');\n "
# # Copyright (c) 2013-2018 Quarkslab. # This file is part of IRMA project. # # 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 in the top-level directory # of this distribution and at: # # http://www.apache.org/licenses/LICENSE-2.0 # # No part of the project, including this file, may be copied, # modified, propagated, or distributed except according to the # terms contained in the LICENSE file. class IrmaDependencyError(Exception): """Error caused by a missing dependency.""" pass class IrmaMachineManagerError(Exception): """Error on a machine manager.""" pass class IrmaMachineError(Exception): """Error on a machine.""" pass class IrmaAdminError(Exception): """Error in admin part.""" pass class IrmaDatabaseError(Exception): """Error on a database manager.""" pass class IrmaCoreError(Exception): """Error in core parts (Db, Ftp, Celery..)""" pass class IrmaDatabaseResultNotFound(IrmaDatabaseError): """A database result was required but none was found.""" pass class IrmaFileSystemError(IrmaDatabaseError): """Nothing corresponding to the request has been found in the database.""" pass class IrmaConfigurationError(IrmaCoreError): """Error wrong configuration.""" pass class IrmaFtpError(IrmaCoreError): """Error on ftp manager.""" pass class IrmaFTPSError(IrmaFtpError): """Error on ftp/tls manager.""" pass class IrmaSFTPError(IrmaFtpError): """Error on sftp manager.""" pass class IrmaTaskError(IrmaCoreError): """Error while processing celery tasks.""" pass class IrmaLockError(Exception): """Error for the locks on db content (already taken)""" pass class IrmaLockModeError(Exception): """Error for the mode of the locks (doesn't exist)""" pass class IrmaValueError(Exception): """Error for the parameters passed to the functions""" pass
class Irmadependencyerror(Exception): """Error caused by a missing dependency.""" pass class Irmamachinemanagererror(Exception): """Error on a machine manager.""" pass class Irmamachineerror(Exception): """Error on a machine.""" pass class Irmaadminerror(Exception): """Error in admin part.""" pass class Irmadatabaseerror(Exception): """Error on a database manager.""" pass class Irmacoreerror(Exception): """Error in core parts (Db, Ftp, Celery..)""" pass class Irmadatabaseresultnotfound(IrmaDatabaseError): """A database result was required but none was found.""" pass class Irmafilesystemerror(IrmaDatabaseError): """Nothing corresponding to the request has been found in the database.""" pass class Irmaconfigurationerror(IrmaCoreError): """Error wrong configuration.""" pass class Irmaftperror(IrmaCoreError): """Error on ftp manager.""" pass class Irmaftpserror(IrmaFtpError): """Error on ftp/tls manager.""" pass class Irmasftperror(IrmaFtpError): """Error on sftp manager.""" pass class Irmataskerror(IrmaCoreError): """Error while processing celery tasks.""" pass class Irmalockerror(Exception): """Error for the locks on db content (already taken)""" pass class Irmalockmodeerror(Exception): """Error for the mode of the locks (doesn't exist)""" pass class Irmavalueerror(Exception): """Error for the parameters passed to the functions""" pass
def save_form(form, actor=None): """Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require this to be passed (is not handled by middleware), you can use this to replace form.save(). Requires you to use the audit.Model model as the actor is passed to the object's save method. """ obj = form.save(commit=False) obj.save(actor=actor) form.save_m2m() return obj #def intermediate_save(instance, actor=None): # """Allows saving of an instance, without storing the changes, but keeping the history. This allows you to perform # intermediate saves: # # obj.value1 = 1 # intermediate_save(obj) # obj.value2 = 2 # obj.save() # <value 1 and value 2 are both stored in the database> # """ # if hasattr(instance, '_audit_changes'): # tmp = instance._audit_changes # if actor: # instance.save(actor=actor) # else: # instance.save() # instance._audit_changes = tmp # else: # if actor: # instance.save(actor=actor) # else: # instance.save()
def save_form(form, actor=None): """Allows storing a form with a passed actor. Normally, Form.save() does not accept an actor, but if you require this to be passed (is not handled by middleware), you can use this to replace form.save(). Requires you to use the audit.Model model as the actor is passed to the object's save method. """ obj = form.save(commit=False) obj.save(actor=actor) form.save_m2m() return obj
# coding = utf-8 # Create date: 2018-11-05 # Author :Hailong def test_sysctl(ros_kvm_with_paramiko, cloud_config_url): command = 'sudo cat /proc/sys/kernel/domainname' feed_back = 'test' client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url)) stdin, stdout, stderr = client.exec_command(command, timeout=10) output = stdout.read().decode('utf-8').replace('\n', '') assert (feed_back == output) command_b = 'sudo cat /proc/sys/dev/cdrom/debug' feed_back_b = '1' stdin, stdout, stderr = client.exec_command(command_b, timeout=10) output_b = stdout.read().decode('utf-8').replace('\n', '') client.close() assert (feed_back_b == output_b)
def test_sysctl(ros_kvm_with_paramiko, cloud_config_url): command = 'sudo cat /proc/sys/kernel/domainname' feed_back = 'test' client = ros_kvm_with_paramiko(cloud_config='{url}/test_sysctl.yml'.format(url=cloud_config_url)) (stdin, stdout, stderr) = client.exec_command(command, timeout=10) output = stdout.read().decode('utf-8').replace('\n', '') assert feed_back == output command_b = 'sudo cat /proc/sys/dev/cdrom/debug' feed_back_b = '1' (stdin, stdout, stderr) = client.exec_command(command_b, timeout=10) output_b = stdout.read().decode('utf-8').replace('\n', '') client.close() assert feed_back_b == output_b
#Datos de entrada num=int(input("Ingrese un numero: ")) # Proceso if num==10: print("Calificacion: A") elif num==9: print("Calificacion: B") elif num==8: print("Calificacion: C") elif num==7 and num==6: print("Calificacion: D") elif num<=5 and num>=0: print("Calificacion: F")
num = int(input('Ingrese un numero: ')) if num == 10: print('Calificacion: A') elif num == 9: print('Calificacion: B') elif num == 8: print('Calificacion: C') elif num == 7 and num == 6: print('Calificacion: D') elif num <= 5 and num >= 0: print('Calificacion: F')
ribbon_needed = 0 with open("input.txt", "r") as puzzle_input: for line in puzzle_input: length, width, height = [int(item) for item in line.split("x")] dimensions = [length, width, height] smallest_side = min(dimensions) dimensions.remove(smallest_side) second_smallest_side = min(dimensions) ribbon_needed += 2*smallest_side + 2*second_smallest_side + length*width*height print(ribbon_needed)
ribbon_needed = 0 with open('input.txt', 'r') as puzzle_input: for line in puzzle_input: (length, width, height) = [int(item) for item in line.split('x')] dimensions = [length, width, height] smallest_side = min(dimensions) dimensions.remove(smallest_side) second_smallest_side = min(dimensions) ribbon_needed += 2 * smallest_side + 2 * second_smallest_side + length * width * height print(ribbon_needed)
""" # refactoring Refactoring is the key to successfull projects. Refactor: 1) annuity_factor such that: conversion to integer is handled, no extra printing 2) policy_book into a class such that: a function generates the book and the premium stats and visualizations functions are avalaible 3) book_report such that: it uses all the previous improvements """
""" # refactoring Refactoring is the key to successfull projects. Refactor: 1) annuity_factor such that: conversion to integer is handled, no extra printing 2) policy_book into a class such that: a function generates the book and the premium stats and visualizations functions are avalaible 3) book_report such that: it uses all the previous improvements """
class Solution: def hammingDistance(self, x: int, y: int) -> int: xor = x ^ y distance = 0 while xor: if xor & 1: distance += 1 xor = xor >> 1 return distance class Solution: def hammingDistance(self, x: int, y: int) -> int: xor = x ^ y distance = 0 while xor: distance += 1 xor = xor & (xor-1) return distance
class Solution: def hamming_distance(self, x: int, y: int) -> int: xor = x ^ y distance = 0 while xor: if xor & 1: distance += 1 xor = xor >> 1 return distance class Solution: def hamming_distance(self, x: int, y: int) -> int: xor = x ^ y distance = 0 while xor: distance += 1 xor = xor & xor - 1 return distance
""" Visual Genome Python API wrapper, models """ class Image: """ Image. ID int url hyperlink string width int height int """ def __init__(self, id, url, width, height, coco_id, flickr_id): self.id = id self.url = url self.width = width self.height = height self.coco_id = coco_id self.flickr_id = flickr_id def __str__(self): return 'id: %d, coco_id: %d, flickr_id: %d, width: %d, url: %s' \ % (self.id, -1 if self.coco_id is None else self.coco_id, -1 if self.flickr_id is None else self.flickr_id, self.width, self.url) def __repr__(self): return str(self) class Region: """ Region. image int phrase string x int y int width int height int """ def __init__(self, id, image, phrase, x, y, width, height): self.id = id self.image = image self.phrase = phrase self.x = x self.y = y self.width = width self.height = height def __str__(self): stat_str = 'id: {0}, x: {1}, y: {2}, width: {3},' \ 'height: {4}, phrase: {5}, image: {6}' return stat_str.format(self.id, self.x, self.y, self.width, self.height, self.phrase, self.image.id) def __repr__(self): return str(self) class Graph: """ Graphs contain objects, relationships and attributes image Image bboxes Object array relationships Relationship array attributes Attribute array """ def __init__(self, image, objects, relationships, attributes): self.image = image self.objects = objects self.relationships = relationships self.attributes = attributes class Object: """ Objects. id int x int y int width int height int names string array synsets Synset array """ def __init__(self, id, x, y, width, height, names, synsets): self.id = id self.x = x self.y = y self.width = width self.height = height self.names = names[0] self.synsets = synsets self.bbox = [x, y, width, height] def __str__(self): name = self.names[0] if len(self.names) != 0 else 'None' return '%s' % (name) def __repr__(self): return str(self) class Relationship: """ Relationships. Ex, 'man - jumping over - fire hydrant'. subject int predicate string object int rel_canon Synset """ def __init__(self, id, subject, predicate, object, synset): self.id = id self.subject = subject self.predicate = predicate self.object = object self.synset = synset def __str__(self): return "{0}: {1} {2} {3}".format(self.id, self.subject, self.predicate, self.object) def __repr__(self): return str(self) class Attribute: """ Attributes. Ex, 'man - old'. subject Object attribute string synset Synset """ def __init__(self, id, subject, attribute, synset): self.id = id self.subject = subject self.attribute = attribute self.synset = synset def __str__(self): return "%d: %s is %s" % (self.id, self.subject, self.attribute) def __repr__(self): return str(self) class QA: """ Question Answer Pairs. ID int image int question string answer string q_objects QAObject array a_objects QAObject array """ def __init__(self, id, image, question, answer, question_objects, answer_objects): self.id = id self.image = image self.question = question self.answer = answer self.q_objects = question_objects self.a_objects = answer_objects def __str__(self): return 'id: %d, image: %d, question: %s, answer: %s' \ % (self.id, self.image.id, self.question, self.answer) def __repr__(self): return str(self) class QAObject: """ Question Answer Objects are localized in the image and refer to a part of the question text or the answer text. start_idx int end_idx int name string synset_name string synset_definition string """ def __init__(self, start_idx, end_idx, name, synset): self.start_idx = start_idx self.end_idx = end_idx self.name = name self.synset = synset def __repr__(self): return str(self) class Synset: """ Wordnet Synsets. name string definition string """ def __init__(self, name, definition): self.name = name self.definition = definition def __str__(self): return '{} - {}'.format(self.name, self.definition) def __repr__(self): return str(self)
""" Visual Genome Python API wrapper, models """ class Image: """ Image. ID int url hyperlink string width int height int """ def __init__(self, id, url, width, height, coco_id, flickr_id): self.id = id self.url = url self.width = width self.height = height self.coco_id = coco_id self.flickr_id = flickr_id def __str__(self): return 'id: %d, coco_id: %d, flickr_id: %d, width: %d, url: %s' % (self.id, -1 if self.coco_id is None else self.coco_id, -1 if self.flickr_id is None else self.flickr_id, self.width, self.url) def __repr__(self): return str(self) class Region: """ Region. image int phrase string x int y int width int height int """ def __init__(self, id, image, phrase, x, y, width, height): self.id = id self.image = image self.phrase = phrase self.x = x self.y = y self.width = width self.height = height def __str__(self): stat_str = 'id: {0}, x: {1}, y: {2}, width: {3},height: {4}, phrase: {5}, image: {6}' return stat_str.format(self.id, self.x, self.y, self.width, self.height, self.phrase, self.image.id) def __repr__(self): return str(self) class Graph: """ Graphs contain objects, relationships and attributes image Image bboxes Object array relationships Relationship array attributes Attribute array """ def __init__(self, image, objects, relationships, attributes): self.image = image self.objects = objects self.relationships = relationships self.attributes = attributes class Object: """ Objects. id int x int y int width int height int names string array synsets Synset array """ def __init__(self, id, x, y, width, height, names, synsets): self.id = id self.x = x self.y = y self.width = width self.height = height self.names = names[0] self.synsets = synsets self.bbox = [x, y, width, height] def __str__(self): name = self.names[0] if len(self.names) != 0 else 'None' return '%s' % name def __repr__(self): return str(self) class Relationship: """ Relationships. Ex, 'man - jumping over - fire hydrant'. subject int predicate string object int rel_canon Synset """ def __init__(self, id, subject, predicate, object, synset): self.id = id self.subject = subject self.predicate = predicate self.object = object self.synset = synset def __str__(self): return '{0}: {1} {2} {3}'.format(self.id, self.subject, self.predicate, self.object) def __repr__(self): return str(self) class Attribute: """ Attributes. Ex, 'man - old'. subject Object attribute string synset Synset """ def __init__(self, id, subject, attribute, synset): self.id = id self.subject = subject self.attribute = attribute self.synset = synset def __str__(self): return '%d: %s is %s' % (self.id, self.subject, self.attribute) def __repr__(self): return str(self) class Qa: """ Question Answer Pairs. ID int image int question string answer string q_objects QAObject array a_objects QAObject array """ def __init__(self, id, image, question, answer, question_objects, answer_objects): self.id = id self.image = image self.question = question self.answer = answer self.q_objects = question_objects self.a_objects = answer_objects def __str__(self): return 'id: %d, image: %d, question: %s, answer: %s' % (self.id, self.image.id, self.question, self.answer) def __repr__(self): return str(self) class Qaobject: """ Question Answer Objects are localized in the image and refer to a part of the question text or the answer text. start_idx int end_idx int name string synset_name string synset_definition string """ def __init__(self, start_idx, end_idx, name, synset): self.start_idx = start_idx self.end_idx = end_idx self.name = name self.synset = synset def __repr__(self): return str(self) class Synset: """ Wordnet Synsets. name string definition string """ def __init__(self, name, definition): self.name = name self.definition = definition def __str__(self): return '{} - {}'.format(self.name, self.definition) def __repr__(self): return str(self)
def setIntersectionCount(group): return len(set.intersection(*group)) groupList = [] tempGroup = [] with open("./6/input.txt") as inputFile: for line in inputFile: line = line.replace("\n","") if len(line) > 0: tempGroup.append(set(line)) else: groupList.append(tempGroup) tempGroup = [] if len(tempGroup) > 0: groupList.append(tempGroup) groupList = list(map(setIntersectionCount,groupList)) print("{} common options in groups".format(sum(groupList)))
def set_intersection_count(group): return len(set.intersection(*group)) group_list = [] temp_group = [] with open('./6/input.txt') as input_file: for line in inputFile: line = line.replace('\n', '') if len(line) > 0: tempGroup.append(set(line)) else: groupList.append(tempGroup) temp_group = [] if len(tempGroup) > 0: groupList.append(tempGroup) group_list = list(map(setIntersectionCount, groupList)) print('{} common options in groups'.format(sum(groupList)))
"""Errors module.""" __all__ = [ 'Error', 'AddressError', 'AuthenticationError', 'TransportError', 'ValidationError', 'RegisterError', 'MessageError', 'DBusError', 'SignatureError', 'TooLongError', ] class Error(Exception): """Base class.""" class AddressError(Error): """Raised for errors in server addresses.""" class AuthenticationError(Error): """Raised when authentication failed.""" class TransportError(Error): """Raised for transport related errors.""" class ValidationError(Error): """Raised when validation failed.""" class RegisterError(Error): """Raised when a signal or method could not be registered.""" class MessageError(Error): """Raised for errors in messages.""" class DBusError(MessageError): """Raised for errors from ERROR messages.""" class SignatureError(MessageError): """Raised for errors in signatures.""" class TooLongError(MessageError): """Raised when a message, an array, a name etc. is too long."""
"""Errors module.""" __all__ = ['Error', 'AddressError', 'AuthenticationError', 'TransportError', 'ValidationError', 'RegisterError', 'MessageError', 'DBusError', 'SignatureError', 'TooLongError'] class Error(Exception): """Base class.""" class Addresserror(Error): """Raised for errors in server addresses.""" class Authenticationerror(Error): """Raised when authentication failed.""" class Transporterror(Error): """Raised for transport related errors.""" class Validationerror(Error): """Raised when validation failed.""" class Registererror(Error): """Raised when a signal or method could not be registered.""" class Messageerror(Error): """Raised for errors in messages.""" class Dbuserror(MessageError): """Raised for errors from ERROR messages.""" class Signatureerror(MessageError): """Raised for errors in signatures.""" class Toolongerror(MessageError): """Raised when a message, an array, a name etc. is too long."""
# If you're new to file handling, be sure to check out with_open.py first! # You'll also want to check out read_text.py before this example. This one is a bit more advanced. with open('read_csv.csv', 'r') as states_file: # Instead of leaving the file contents as a string, we're splitting the file into a list at every new line, and we save that list into the variable states states = states_file.read().split("\n") # Since this is a spreadsheet in comma separated values (CSV) format, we can think of states as a list of rows. # But we'll need to split the columns into a list as well! for index, state in enumerate(states): states[index] = state.split(",") # Now we have a nested list with all of the information! # Our file looks like this: # State, Population Estimate, Percent of Total population # California, 38332521, 11.91% # Texas, 26448193, 8.04% # ... # Our header row is at state[0], so we can use that to display the information in a prettier way. for state in states[1:]: # We use [1:] so we skip the header row. # state[0] is the first column in the row, which contains the name of the state. print("\n---{0}---".format(state[0])) for index, info in enumerate(state[1:]): # We use [1:] so we don't repeat the state name. print("{0}:\t{1}".format(states[0][index+1], info)) # states is the full list of all of the states. It's a nested list. The outer list contains the rows, each inner list contains the columns in that row. # states[0] refers to the header row of the list # So states[0][0] would refer to "State", states[0][1] would refer to "Population Estimate", and states[0][2] would refer to "Percent of total population" # state is one state within states. state is also a list, containing the name, population, and percentage of that particular state. # So the first time through the loop, state[0] would refer to "California", state[1] would refer to 38332521, and state[2] would refer to 11.91% # Since state is being create by the for loop in line 24, it gets a new value each time through. # We're using enumerate to get the index (slicing number) of the column we're on, along with the information. # That way we can pair the column name with the information, as shown in line 30. # NOTE: Since we're slicing from [1:] in line 29, we need to increase the index by + 1, otherwise our headers will be off by one. # Sample output: # ---"California"--- # "Population Estimate": 38332521 # "Percent of Total population": "11.91%" # ---"Texas"--- # "Population Estimate": 26448193 # "Percent of Total population": "8.04%" # ---"New York"--- # "Population Estimate": 19651127 # "Percent of Total population": "6.19%"
with open('read_csv.csv', 'r') as states_file: states = states_file.read().split('\n') for (index, state) in enumerate(states): states[index] = state.split(',') for state in states[1:]: print('\n---{0}---'.format(state[0])) for (index, info) in enumerate(state[1:]): print('{0}:\t{1}'.format(states[0][index + 1], info))
class Student: studentLevel = 'first year computer science 2020/2021 session' studentCounter = 0 registeredCourse='csc102' def __init__(self, thename, thematricno, thesex,thehostelname,theage,thecsc102examscore): self.name = thename self.matricno = thematricno self.sex = thesex self.hostelname =thehostelname self.age=theage self.csc102examscore=thecsc102examscore Student.studentCounter = Student.studentCounter + 1 def getName(self): return self.name def setName(self, thenewName): self.name = thenewName def agedeterminer(self): if self.age>16: print('Student is above 16') def finalscore(self): if self.csc102examscore < 45: print('You will carryover this course, sorry') else: print('You have passed') @classmethod def course(): print(f'Students registered course is {Student.registeredCourse}') @staticmethod def PAUNanthem(): print('Pau, here we come, Pau, here we come ') @staticmethod def ODDorEVEN(num): if num % 2==0: print('Number is even') else: print('Number is odd') @classmethod def studentnum(cls): print(Student.studentCounter) studendt1 = Student('James Kaka', '021074', 'M','Amethyst','16', '49') print(studendt1.getName()) studendt1.setName('James Gaga') print(studendt1.getName()) Student.PAUNanthem()
class Student: student_level = 'first year computer science 2020/2021 session' student_counter = 0 registered_course = 'csc102' def __init__(self, thename, thematricno, thesex, thehostelname, theage, thecsc102examscore): self.name = thename self.matricno = thematricno self.sex = thesex self.hostelname = thehostelname self.age = theage self.csc102examscore = thecsc102examscore Student.studentCounter = Student.studentCounter + 1 def get_name(self): return self.name def set_name(self, thenewName): self.name = thenewName def agedeterminer(self): if self.age > 16: print('Student is above 16') def finalscore(self): if self.csc102examscore < 45: print('You will carryover this course, sorry') else: print('You have passed') @classmethod def course(): print(f'Students registered course is {Student.registeredCourse}') @staticmethod def pau_nanthem(): print('Pau, here we come, Pau, here we come ') @staticmethod def od_dor_even(num): if num % 2 == 0: print('Number is even') else: print('Number is odd') @classmethod def studentnum(cls): print(Student.studentCounter) studendt1 = student('James Kaka', '021074', 'M', 'Amethyst', '16', '49') print(studendt1.getName()) studendt1.setName('James Gaga') print(studendt1.getName()) Student.PAUNanthem()
def say_hi(name,age): print("Hello " + name + ", you are " + age) say_hi("Mike", "35") def cube(num): # function return num*num*num result = cube(4) # variable print(result)
def say_hi(name, age): print('Hello ' + name + ', you are ' + age) say_hi('Mike', '35') def cube(num): return num * num * num result = cube(4) print(result)
MUTATION = '''mutation {{ {mutation} }}''' def _verify_additional_type(additionaltype): """Check that the input to additionaltype is a list of strings. If it is empty, raise ValueError If it is a string, convert it to a list of strings.""" if additionaltype is None: return None if isinstance(additionaltype, str): additionaltype = [additionaltype] if len(additionaltype) == 0: raise ValueError("additionaltype must be a non-empty list") return additionaltype
mutation = 'mutation {{\n {mutation}\n}}' def _verify_additional_type(additionaltype): """Check that the input to additionaltype is a list of strings. If it is empty, raise ValueError If it is a string, convert it to a list of strings.""" if additionaltype is None: return None if isinstance(additionaltype, str): additionaltype = [additionaltype] if len(additionaltype) == 0: raise value_error('additionaltype must be a non-empty list') return additionaltype
# # PySNMP MIB module CXConsoleDriver-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXConsoleDriver-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:32:28 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion") cxConsoleDriver, = mibBuilder.importSymbols("CXProduct-SMI", "cxConsoleDriver") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter64, Gauge32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, Integer32, ModuleIdentity, NotificationType, ObjectIdentity, MibIdentifier, Counter32, iso, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "Gauge32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "Integer32", "ModuleIdentity", "NotificationType", "ObjectIdentity", "MibIdentifier", "Counter32", "iso", "Bits") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") cxCdBaudRate = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 1), Integer32().clone(9600)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxCdBaudRate.setStatus('mandatory') if mibBuilder.loadTexts: cxCdBaudRate.setDescription('Determines the baud rate of the console port. The setting of this object is dynamic. The console port immediately implements the option you enter. Options: 9600 19200 38400 115200 Default Value: 9600 Configuration Changed: operative') cxCdCharSize = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(7, 8)).clone(8)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxCdCharSize.setStatus('mandatory') if mibBuilder.loadTexts: cxCdCharSize.setDescription('Determines how many bits constitute a character for the console port. Options: none - the value is fixed at 8 Default Value: 8 Configuration Changed: none ') cxCdParity = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("noParity", 1), ("evenParity", 2), ("oddParity", 3))).clone('noParity')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxCdParity.setStatus('mandatory') if mibBuilder.loadTexts: cxCdParity.setDescription('Determines the parity scheme the CPU uses to validate the characters it receives through the console port. Options: none - the value is fixed at noParity Default Value: noParity Configuration Changed: none ') cxCdStopBit = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxCdStopBit.setStatus('mandatory') if mibBuilder.loadTexts: cxCdStopBit.setDescription('Determines how many stop bits are at the end of each character the console port receives. Options: none - the value is fixed at 1 Default Value: 1 Configuration Changed: none ') cxCdProtocol = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("localConsole", 1), ("ppp", 2))).clone('localConsole')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cxCdProtocol.setStatus('mandatory') if mibBuilder.loadTexts: cxCdProtocol.setDescription('Determines the protocol (configuration method) for the console port. The setting of this object is dynamic. The console port immediately implements the option you enter. However, if you change the protocol you are currently using to configure the port your connection will be lost. Options: localConsole (1): you use this protocol when you attach a TTY terminal directly to the console port. This protocol requires you to use command line configuration. You also must enter a password to gain access to the configuration tables. You can define the password using the object uiPassword of the CXUserInterface Table. ppp (2): you use this protocol when you are configuring via a windows-based application such as HP/OV (Hewlett Packard-OpenView). Default Value: ppp (2) Configuration Changed: operative') mibBuilder.exportSymbols("CXConsoleDriver-MIB", cxCdParity=cxCdParity, cxCdProtocol=cxCdProtocol, cxCdBaudRate=cxCdBaudRate, cxCdStopBit=cxCdStopBit, cxCdCharSize=cxCdCharSize)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, single_value_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion') (cx_console_driver,) = mibBuilder.importSymbols('CXProduct-SMI', 'cxConsoleDriver') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (counter64, gauge32, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, unsigned32, integer32, module_identity, notification_type, object_identity, mib_identifier, counter32, iso, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'Gauge32', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'Unsigned32', 'Integer32', 'ModuleIdentity', 'NotificationType', 'ObjectIdentity', 'MibIdentifier', 'Counter32', 'iso', 'Bits') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') cx_cd_baud_rate = mib_scalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 1), integer32().clone(9600)).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxCdBaudRate.setStatus('mandatory') if mibBuilder.loadTexts: cxCdBaudRate.setDescription('Determines the baud rate of the console port. The setting of this object is dynamic. The console port immediately implements the option you enter. Options: 9600 19200 38400 115200 Default Value: 9600 Configuration Changed: operative') cx_cd_char_size = mib_scalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 2), integer32().subtype(subtypeSpec=value_range_constraint(7, 8)).clone(8)).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxCdCharSize.setStatus('mandatory') if mibBuilder.loadTexts: cxCdCharSize.setDescription('Determines how many bits constitute a character for the console port. Options: none - the value is fixed at 8 Default Value: 8 Configuration Changed: none ') cx_cd_parity = mib_scalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('noParity', 1), ('evenParity', 2), ('oddParity', 3))).clone('noParity')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxCdParity.setStatus('mandatory') if mibBuilder.loadTexts: cxCdParity.setDescription('Determines the parity scheme the CPU uses to validate the characters it receives through the console port. Options: none - the value is fixed at noParity Default Value: noParity Configuration Changed: none ') cx_cd_stop_bit = mib_scalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 4), integer32().subtype(subtypeSpec=value_range_constraint(1, 2)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxCdStopBit.setStatus('mandatory') if mibBuilder.loadTexts: cxCdStopBit.setDescription('Determines how many stop bits are at the end of each character the console port receives. Options: none - the value is fixed at 1 Default Value: 1 Configuration Changed: none ') cx_cd_protocol = mib_scalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 5, 6, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('localConsole', 1), ('ppp', 2))).clone('localConsole')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cxCdProtocol.setStatus('mandatory') if mibBuilder.loadTexts: cxCdProtocol.setDescription('Determines the protocol (configuration method) for the console port. The setting of this object is dynamic. The console port immediately implements the option you enter. However, if you change the protocol you are currently using to configure the port your connection will be lost. Options: localConsole (1): you use this protocol when you attach a TTY terminal directly to the console port. This protocol requires you to use command line configuration. You also must enter a password to gain access to the configuration tables. You can define the password using the object uiPassword of the CXUserInterface Table. ppp (2): you use this protocol when you are configuring via a windows-based application such as HP/OV (Hewlett Packard-OpenView). Default Value: ppp (2) Configuration Changed: operative') mibBuilder.exportSymbols('CXConsoleDriver-MIB', cxCdParity=cxCdParity, cxCdProtocol=cxCdProtocol, cxCdBaudRate=cxCdBaudRate, cxCdStopBit=cxCdStopBit, cxCdCharSize=cxCdCharSize)
# written by abraham on aug 24 def dyear2date(dyear): year = int(dyear) month_lengths = [31,28,31,30,31,30,31,31,30,31,30,31] days_before_months = [0,31,59,90,120,151,181,212,243,273,304,334] days_into_year_f = (dyear-year)*365 days_into_year_i = int(days_into_year_f) for i in range(12): if days_before_months[i] < days_into_year_f < (days_before_months[i]+month_lengths[i]): month = i+1 break date = days_into_year_i - days_before_months[month-1] hours_f = (days_into_year_f-days_into_year_i)*24 hours_i = int(hours_f) minutes_f = (hours_f-hours_i)*60 minutes_i = int(minutes_f) seconds_i = int((minutes_f-minutes_i)*60) return "%02d/%02d/%d %02d:%02d:%02d" % (month,date,year,hours_i,minutes_i,seconds_i)
def dyear2date(dyear): year = int(dyear) month_lengths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] days_before_months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334] days_into_year_f = (dyear - year) * 365 days_into_year_i = int(days_into_year_f) for i in range(12): if days_before_months[i] < days_into_year_f < days_before_months[i] + month_lengths[i]: month = i + 1 break date = days_into_year_i - days_before_months[month - 1] hours_f = (days_into_year_f - days_into_year_i) * 24 hours_i = int(hours_f) minutes_f = (hours_f - hours_i) * 60 minutes_i = int(minutes_f) seconds_i = int((minutes_f - minutes_i) * 60) return '%02d/%02d/%d %02d:%02d:%02d' % (month, date, year, hours_i, minutes_i, seconds_i)
class Camera: """docstring for .""" def __init__(self, brand, sensor, lens, battery): self.brand = brand self.sensor = sensor self.lens = lens self.battery = battery def __str__(self): return self.brand + ' ' + self.sensor + ' ' + self.lens + ' ' + self.battery def focus(self): print('Focusing using', self.lens, '...') print('') def frame(self): print('Move until your subject is in the desired position') print('.') print('.') print('.') def flash(self, flash_use): if flash_use == 's': print('Shooting with flash...') else: print('Shooting without flash...') print('') def format(self, save_format): if save_format == 'jpg': print('Saving in: ' + save_format) elif save_format == 'raw': print('Saving in: ' + save_format) else: print('No valid format to save') def take_picture(self, save_format, flash_use): print('Say cheese!') self.focus() self.frame() self.flash(flash_use) self.format(save_format)
class Camera: """docstring for .""" def __init__(self, brand, sensor, lens, battery): self.brand = brand self.sensor = sensor self.lens = lens self.battery = battery def __str__(self): return self.brand + ' ' + self.sensor + ' ' + self.lens + ' ' + self.battery def focus(self): print('Focusing using', self.lens, '...') print('') def frame(self): print('Move until your subject is in the desired position') print('.') print('.') print('.') def flash(self, flash_use): if flash_use == 's': print('Shooting with flash...') else: print('Shooting without flash...') print('') def format(self, save_format): if save_format == 'jpg': print('Saving in: ' + save_format) elif save_format == 'raw': print('Saving in: ' + save_format) else: print('No valid format to save') def take_picture(self, save_format, flash_use): print('Say cheese!') self.focus() self.frame() self.flash(flash_use) self.format(save_format)
#!/usr/bin/python3 """ Good morning! Here's your coding interview problem for today. This problem was recently asked by Google. Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? """ def func(l, k): sums = [] for index, element in enumerate(l): print(f'Current element: {element}') if index == 0: # first element - need another print() continue for num in range(index): print(f'Appending {l[index]} + {l[num]}') sums.append(l[num] + l[index]) print() print(sums) return k in sums print(func([10, 15, 3, 7], 17))
""" Good morning! Here's your coding interview problem for today. This problem was recently asked by Google. Given a list of numbers and a number k, return whether any two numbers from the list add up to k. For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. Bonus: Can you do this in one pass? """ def func(l, k): sums = [] for (index, element) in enumerate(l): print(f'Current element: {element}') if index == 0: print() continue for num in range(index): print(f'Appending {l[index]} + {l[num]}') sums.append(l[num] + l[index]) print() print(sums) return k in sums print(func([10, 15, 3, 7], 17))
# file = open('C:\\Users\\dks10\\OneDrive\\Desktop\\Projects\\Code\\Python\\PythonCrypto\\Module_3\\eye.png', 'rb') file = open('encrypt_eye.png', 'rb') image = file.read() file.close() image = bytearray(image) key = 48 for index, value in enumerate(image): image[index] = value^key file = open('2eye.png','wb') file.write(image) file.close()
file = open('encrypt_eye.png', 'rb') image = file.read() file.close() image = bytearray(image) key = 48 for (index, value) in enumerate(image): image[index] = value ^ key file = open('2eye.png', 'wb') file.write(image) file.close()
n=int(input()) c = 1 while c**2 < n: print(c**2) c += 1
n = int(input()) c = 1 while c ** 2 < n: print(c ** 2) c += 1
class BSTNode: def __init__(self, data = None) -> None: self.data = data self.left = None self.right = None def __repr__(self) -> str: return(f"BSTNode({self.data})") def __str__(self) -> str: return str(self.data) def __eq__(self, o: object) -> bool: pass def __hash__(self) -> int: pass class BST: def __init__(self) -> None: pass def insert(self, item: int) -> None: pass def remove(self, item: int) -> int: pass def swap_nodes(self, item_a: int, item_b: int) -> None: pass def rebalance(self) -> None: pass def get_min_value(self) -> int: pass def get_max_value(self) -> int: pass def clear(self) -> None: pass def get_dept(self) -> int: """Returns the current depth of the tree.""" pass def is_bst(self) -> bool: """Returns True if the tree is properly configured bst.""" pass def is_balanced(self) -> bool: """ Returns True if the tree is balanced """ pass def is_perfect(self) -> bool: """ Returns True if the tree is perfect """ pass def in_order(self): """Returns an iterable of the nodes in the tree.""" pass def pre_order(self): """Returns an iterable of the nodes in the tree.""" pass def post_order(self): """Returns an iterable of the nodes in the tree.""" pass
class Bstnode: def __init__(self, data=None) -> None: self.data = data self.left = None self.right = None def __repr__(self) -> str: return f'BSTNode({self.data})' def __str__(self) -> str: return str(self.data) def __eq__(self, o: object) -> bool: pass def __hash__(self) -> int: pass class Bst: def __init__(self) -> None: pass def insert(self, item: int) -> None: pass def remove(self, item: int) -> int: pass def swap_nodes(self, item_a: int, item_b: int) -> None: pass def rebalance(self) -> None: pass def get_min_value(self) -> int: pass def get_max_value(self) -> int: pass def clear(self) -> None: pass def get_dept(self) -> int: """Returns the current depth of the tree.""" pass def is_bst(self) -> bool: """Returns True if the tree is properly configured bst.""" pass def is_balanced(self) -> bool: """ Returns True if the tree is balanced """ pass def is_perfect(self) -> bool: """ Returns True if the tree is perfect """ pass def in_order(self): """Returns an iterable of the nodes in the tree.""" pass def pre_order(self): """Returns an iterable of the nodes in the tree.""" pass def post_order(self): """Returns an iterable of the nodes in the tree.""" pass
''' Given an array of intervals, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. ''' def merge(intervals): #sort the array intervals.sort() #take another empty list intervals_stack = [] for pair in intervals: if len(intervals_stack) == 0: intervals_stack.append(pair) #adding all the number in intervals elements in empty list #check number is equal or greater and less than pop elements else: current_pair = intervals_stack[-1] if current_pair[1]>=pair[0]: intervals_stack.pop() if current_pair[1]<pair[1]: new_pair = [current_pair[0],pair[1]] intervals_stack.append(new_pair) else: new_pair = [current_pair[0],current_pair[1]] intervals_stack.append(new_pair) else: intervals_stack.append(pair) # result return intervals_stack if __name__ == '__main__': R = int(input("Enter the number of rows:")) C = int(input("Enter the number of columns:")) interval = [[int(input("Enter the elements: ")) for x in range (C)] for y in range(R)] print("Overlapping interval: ",interval) print("Non-overlapping intervals: ",merge(interval)) """ Time complexity : O(n^2) Space complexity : O(n^2) INPUT:- Enter the number of rows:4 Enter the number of columns:2 Enter the elements: 1 Enter the elements: 3 Enter the elements: 2 Enter the elements: 6 Enter the elements: 8 Enter the elements: 10 Enter the elements: 15 Enter the elements: 18 OUTPUT:- Overlapping interval: [[1, 3], [2, 6], [8, 10], [15, 18]] Non-overlapping intervals: [[1, 6], [8, 10], [15, 18]] """
""" Given an array of intervals, merge all overlapping intervals, and return an array of the non-overlapping intervals that cover all the intervals in the input. Input: intervals = [[1,3],[2,6],[8,10],[15,18]] Output: [[1,6],[8,10],[15,18]] Explanation: Since intervals [1,3] and [2,6] overlaps, merge them into [1,6]. """ def merge(intervals): intervals.sort() intervals_stack = [] for pair in intervals: if len(intervals_stack) == 0: intervals_stack.append(pair) else: current_pair = intervals_stack[-1] if current_pair[1] >= pair[0]: intervals_stack.pop() if current_pair[1] < pair[1]: new_pair = [current_pair[0], pair[1]] intervals_stack.append(new_pair) else: new_pair = [current_pair[0], current_pair[1]] intervals_stack.append(new_pair) else: intervals_stack.append(pair) return intervals_stack if __name__ == '__main__': r = int(input('Enter the number of rows:')) c = int(input('Enter the number of columns:')) interval = [[int(input('Enter the elements: ')) for x in range(C)] for y in range(R)] print('Overlapping interval: ', interval) print('Non-overlapping intervals: ', merge(interval)) '\nTime complexity : O(n^2) \nSpace complexity : O(n^2) \n\nINPUT:-\nEnter the number of rows:4\nEnter the number of columns:2\nEnter the elements: 1\nEnter the elements: 3\nEnter the elements: 2\nEnter the elements: 6\nEnter the elements: 8\nEnter the elements: 10\nEnter the elements: 15\nEnter the elements: 18\n\nOUTPUT:-\nOverlapping interval: [[1, 3], [2, 6], [8, 10], [15, 18]]\nNon-overlapping intervals: [[1, 6], [8, 10], [15, 18]]\n\n'
# CPU: 0.06 s possessed, found, condition = map(int, input().split()) possessed += found count = 0 while possessed >= condition: div, mod = divmod(possessed, condition) count += div possessed = div + mod print(count)
(possessed, found, condition) = map(int, input().split()) possessed += found count = 0 while possessed >= condition: (div, mod) = divmod(possessed, condition) count += div possessed = div + mod print(count)
print(18 * 1234) print(18 * 1234 * 2) print(0 * 1) print(1 * 0) print(0.0 * 1.0) print(1.0 * 0.0)
print(18 * 1234) print(18 * 1234 * 2) print(0 * 1) print(1 * 0) print(0.0 * 1.0) print(1.0 * 0.0)
""" The roseguarden project Copyright (C) 2018-2020 Marcus Drobisch, This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ __authors__ = ["Marcus Drobisch"] __contact__ = "roseguarden@fabba.space" __credits__ = [] __license__ = "GPLv3" class BaseAction(object): action = 'undefined' target = 'undefined' source = 'server' version = '1.0.0' def __init__(self, ): print("Instance of BaseAction created") def execute(self, ): print("Execute not defined") @classmethod def generate(cls, delay=0.0): action = {} action['action'] = cls.action action['target'] = cls.target action['version'] = cls.version action['source'] = cls.source action['delay'] = delay return action class BaseNodeAction(object): action = 'undefined' version = '1.0.0' def __init__(self, ): print("Instance of BaseAction created") def execute(self, ): print("Execute not defined") @classmethod def generate(cls): action = {} action['action'] = cls.action action['version'] = cls.version return action
""" The roseguarden project Copyright (C) 2018-2020 Marcus Drobisch, This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ __authors__ = ['Marcus Drobisch'] __contact__ = 'roseguarden@fabba.space' __credits__ = [] __license__ = 'GPLv3' class Baseaction(object): action = 'undefined' target = 'undefined' source = 'server' version = '1.0.0' def __init__(self): print('Instance of BaseAction created') def execute(self): print('Execute not defined') @classmethod def generate(cls, delay=0.0): action = {} action['action'] = cls.action action['target'] = cls.target action['version'] = cls.version action['source'] = cls.source action['delay'] = delay return action class Basenodeaction(object): action = 'undefined' version = '1.0.0' def __init__(self): print('Instance of BaseAction created') def execute(self): print('Execute not defined') @classmethod def generate(cls): action = {} action['action'] = cls.action action['version'] = cls.version return action
class Dummy(): def __init__(self, data): self.name = data['name'] self.age = data['age'] self.city = data['city'] class DummyData(): def __init__(self): self.results = [ Dummy({ 'name': 'PA', 'age': 29, 'city': 'Paris' }), Dummy({ 'name': 'Cairo', 'age': 0, 'city': 'Muizenberg' }), Dummy({ 'name': 'Carina', 'age': 26, 'city': 'Windhoek' }) ] def write_name(self, instance, kwargs={}): return instance.name def write_age(self, instance, kwargs={}): return instance.age def write_city(self, instance, kwargs={}): return instance.city def get_age_list(self): return [i for i in range(0, 99)] def get_city_list(self): return [ 'Paris', 'Muizenberg', 'Windhoek', 'Saint-Dizier' ] def write_get_repeat_func(self): return len(self.results) def write_get_name_func(self, instance, kwargs={}): return self.results[kwargs['index']].name
class Dummy: def __init__(self, data): self.name = data['name'] self.age = data['age'] self.city = data['city'] class Dummydata: def __init__(self): self.results = [dummy({'name': 'PA', 'age': 29, 'city': 'Paris'}), dummy({'name': 'Cairo', 'age': 0, 'city': 'Muizenberg'}), dummy({'name': 'Carina', 'age': 26, 'city': 'Windhoek'})] def write_name(self, instance, kwargs={}): return instance.name def write_age(self, instance, kwargs={}): return instance.age def write_city(self, instance, kwargs={}): return instance.city def get_age_list(self): return [i for i in range(0, 99)] def get_city_list(self): return ['Paris', 'Muizenberg', 'Windhoek', 'Saint-Dizier'] def write_get_repeat_func(self): return len(self.results) def write_get_name_func(self, instance, kwargs={}): return self.results[kwargs['index']].name
######## # Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # * See the License for the specific language governing permissions and # * limitations under the License. class CloudifyClientError(Exception): def __init__(self, message, server_traceback=None, status_code=-1, error_code=None, response=None): super(CloudifyClientError, self).__init__(message) self.status_code = status_code self.error_code = error_code self.server_traceback = server_traceback self.response = response self.message = message def __str__(self): if self.status_code != -1: formatted_error = '{0}: {1}'.format(self.status_code, self.message) return formatted_error return self.message class DeploymentEnvironmentCreationInProgressError(CloudifyClientError): """ Raised when there's attempt to execute a deployment workflow and deployment environment creation workflow execution is still running. In such a case, workflow execution should be retried after a reasonable time or after the execution of deployment environment creation workflow has terminated. """ ERROR_CODE = 'deployment_environment_creation_in_progress_error' class DeploymentEnvironmentCreationPendingError(CloudifyClientError): """ Raised when there's attempt to execute a deployment workflow and deployment environment creation workflow execution is pending. In such a case, workflow execution should be retried after a reasonable time or after the execution of deployment environment creation workflow has terminated. """ ERROR_CODE = 'deployment_environment_creation_pending_error' class IllegalExecutionParametersError(CloudifyClientError): """ Raised when an attempt to execute a workflow with wrong/missing parameters has been made. """ ERROR_CODE = 'illegal_execution_parameters_error' class NoSuchIncludeFieldError(CloudifyClientError): """ Raised when an _include query parameter contains a field which does not exist for the queried data model. """ ERROR_CODE = 'no_such_include_field_error' class MissingRequiredDeploymentInputError(CloudifyClientError): """ Raised when a required deployment input was not specified on deployment creation. """ ERROR_CODE = 'missing_required_deployment_input_error' class UnknownDeploymentInputError(CloudifyClientError): """ Raised when an unexpected input was specified on deployment creation. """ ERROR_CODE = 'unknown_deployment_input_error' class UnknownDeploymentSecretError(CloudifyClientError): """ Raised when a required secret was not found on deployment creation. """ ERROR_CODE = 'unknown_deployment_secret_error' class UnsupportedDeploymentGetSecretError(CloudifyClientError): """ Raised when an unsupported get_secret intrinsic function appears in the blueprint on deployment creation. """ ERROR_CODE = 'unsupported_deployment_get_secret_error' class FunctionsEvaluationError(CloudifyClientError): """ Raised when function evaluation failed. """ ERROR_CODE = 'functions_evaluation_error' class UnknownModificationStageError(CloudifyClientError): """ Raised when an unknown modification stage was provided. """ ERROR_CODE = 'unknown_modification_stage_error' class ExistingStartedDeploymentModificationError(CloudifyClientError): """ Raised when a deployment modification start is attempted while another deployment modification is currently started """ ERROR_CODE = 'existing_started_deployment_modification_error' class DeploymentModificationAlreadyEndedError(CloudifyClientError): """ Raised when a deployment modification finish/rollback is attempted on a deployment modification that has already been finished/rolledback """ ERROR_CODE = 'deployment_modification_already_ended_error' class UserUnauthorizedError(CloudifyClientError): """ Raised when a call has been made to a secured resource with an unauthorized user (no credentials / bad credentials) """ ERROR_CODE = 'unauthorized_error' class ForbiddenError(CloudifyClientError): """ Raised when a call has been made by a user that is not permitted to perform it """ ERROR_CODE = 'forbidden_error' class PluginInUseError(CloudifyClientError): """ Raised if a central deployment agent plugin deletion is attempted and at least one deployment is currently using this plugin. """ ERROR_CODE = 'plugin_in_use' class PluginInstallationError(CloudifyClientError): """ Raised if a central deployment agent plugin installation fails. """ ERROR_CODE = 'plugin_installation_error' class PluginInstallationTimeout(CloudifyClientError): """ Raised if a central deployment agent plugin installation times out. """ ERROR_CODE = 'plugin_installation_timeout' class MaintenanceModeActiveError(CloudifyClientError): """ Raised when a call has been blocked due to maintenance mode being active. """ ERROR_CODE = 'maintenance_mode_active' def __str__(self): return self.message class MaintenanceModeActivatingError(CloudifyClientError): """ Raised when a call has been blocked while maintenance mode is activating. """ ERROR_CODE = 'entering_maintenance_mode' def __str__(self): return self.message class NotModifiedError(CloudifyClientError): """ Raised when a 304 not modified error was returned """ ERROR_CODE = 'not_modified' def __str__(self): return self.message class InvalidExecutionUpdateStatus(CloudifyClientError): """ Raised when execution update failed do to invalid status update """ ERROR_CODE = 'invalid_exception_status_update' class NotClusterMaster(CloudifyClientError): """ Raised when the request was served by a manager that is not the master node of a manager cluster. The client should query for the cluster status to learn the master's address, and retry the request. If the client stores the server address, it should update the storage with the new master node address. """ ERROR_CODE = 'not_cluster_master' class RemovedFromCluster(CloudifyClientError): """ Raised when attempting to contact a manager that was removed from a cluster. The client should retry the request with another manager in the cluster. If the client stores the server address, it should remove this node's address from storage. """ ERROR_CODE = 'removed_from_cluster' class DeploymentPluginNotFound(CloudifyClientError): """ Raised when a plugin is listed in the blueprint but is not installed on the manager. """ ERROR_CODE = 'deployment_plugin_not_found' ERROR_MAPPING = dict([ (error.ERROR_CODE, error) for error in [ DeploymentEnvironmentCreationInProgressError, DeploymentEnvironmentCreationPendingError, IllegalExecutionParametersError, NoSuchIncludeFieldError, MissingRequiredDeploymentInputError, UnknownDeploymentInputError, UnknownDeploymentSecretError, UnsupportedDeploymentGetSecretError, FunctionsEvaluationError, UnknownModificationStageError, ExistingStartedDeploymentModificationError, DeploymentModificationAlreadyEndedError, UserUnauthorizedError, ForbiddenError, MaintenanceModeActiveError, MaintenanceModeActivatingError, NotModifiedError, InvalidExecutionUpdateStatus, PluginInUseError, PluginInstallationError, PluginInstallationTimeout, NotClusterMaster, RemovedFromCluster, DeploymentPluginNotFound]])
class Cloudifyclienterror(Exception): def __init__(self, message, server_traceback=None, status_code=-1, error_code=None, response=None): super(CloudifyClientError, self).__init__(message) self.status_code = status_code self.error_code = error_code self.server_traceback = server_traceback self.response = response self.message = message def __str__(self): if self.status_code != -1: formatted_error = '{0}: {1}'.format(self.status_code, self.message) return formatted_error return self.message class Deploymentenvironmentcreationinprogresserror(CloudifyClientError): """ Raised when there's attempt to execute a deployment workflow and deployment environment creation workflow execution is still running. In such a case, workflow execution should be retried after a reasonable time or after the execution of deployment environment creation workflow has terminated. """ error_code = 'deployment_environment_creation_in_progress_error' class Deploymentenvironmentcreationpendingerror(CloudifyClientError): """ Raised when there's attempt to execute a deployment workflow and deployment environment creation workflow execution is pending. In such a case, workflow execution should be retried after a reasonable time or after the execution of deployment environment creation workflow has terminated. """ error_code = 'deployment_environment_creation_pending_error' class Illegalexecutionparameterserror(CloudifyClientError): """ Raised when an attempt to execute a workflow with wrong/missing parameters has been made. """ error_code = 'illegal_execution_parameters_error' class Nosuchincludefielderror(CloudifyClientError): """ Raised when an _include query parameter contains a field which does not exist for the queried data model. """ error_code = 'no_such_include_field_error' class Missingrequireddeploymentinputerror(CloudifyClientError): """ Raised when a required deployment input was not specified on deployment creation. """ error_code = 'missing_required_deployment_input_error' class Unknowndeploymentinputerror(CloudifyClientError): """ Raised when an unexpected input was specified on deployment creation. """ error_code = 'unknown_deployment_input_error' class Unknowndeploymentsecreterror(CloudifyClientError): """ Raised when a required secret was not found on deployment creation. """ error_code = 'unknown_deployment_secret_error' class Unsupporteddeploymentgetsecreterror(CloudifyClientError): """ Raised when an unsupported get_secret intrinsic function appears in the blueprint on deployment creation. """ error_code = 'unsupported_deployment_get_secret_error' class Functionsevaluationerror(CloudifyClientError): """ Raised when function evaluation failed. """ error_code = 'functions_evaluation_error' class Unknownmodificationstageerror(CloudifyClientError): """ Raised when an unknown modification stage was provided. """ error_code = 'unknown_modification_stage_error' class Existingstarteddeploymentmodificationerror(CloudifyClientError): """ Raised when a deployment modification start is attempted while another deployment modification is currently started """ error_code = 'existing_started_deployment_modification_error' class Deploymentmodificationalreadyendederror(CloudifyClientError): """ Raised when a deployment modification finish/rollback is attempted on a deployment modification that has already been finished/rolledback """ error_code = 'deployment_modification_already_ended_error' class Userunauthorizederror(CloudifyClientError): """ Raised when a call has been made to a secured resource with an unauthorized user (no credentials / bad credentials) """ error_code = 'unauthorized_error' class Forbiddenerror(CloudifyClientError): """ Raised when a call has been made by a user that is not permitted to perform it """ error_code = 'forbidden_error' class Plugininuseerror(CloudifyClientError): """ Raised if a central deployment agent plugin deletion is attempted and at least one deployment is currently using this plugin. """ error_code = 'plugin_in_use' class Plugininstallationerror(CloudifyClientError): """ Raised if a central deployment agent plugin installation fails. """ error_code = 'plugin_installation_error' class Plugininstallationtimeout(CloudifyClientError): """ Raised if a central deployment agent plugin installation times out. """ error_code = 'plugin_installation_timeout' class Maintenancemodeactiveerror(CloudifyClientError): """ Raised when a call has been blocked due to maintenance mode being active. """ error_code = 'maintenance_mode_active' def __str__(self): return self.message class Maintenancemodeactivatingerror(CloudifyClientError): """ Raised when a call has been blocked while maintenance mode is activating. """ error_code = 'entering_maintenance_mode' def __str__(self): return self.message class Notmodifiederror(CloudifyClientError): """ Raised when a 304 not modified error was returned """ error_code = 'not_modified' def __str__(self): return self.message class Invalidexecutionupdatestatus(CloudifyClientError): """ Raised when execution update failed do to invalid status update """ error_code = 'invalid_exception_status_update' class Notclustermaster(CloudifyClientError): """ Raised when the request was served by a manager that is not the master node of a manager cluster. The client should query for the cluster status to learn the master's address, and retry the request. If the client stores the server address, it should update the storage with the new master node address. """ error_code = 'not_cluster_master' class Removedfromcluster(CloudifyClientError): """ Raised when attempting to contact a manager that was removed from a cluster. The client should retry the request with another manager in the cluster. If the client stores the server address, it should remove this node's address from storage. """ error_code = 'removed_from_cluster' class Deploymentpluginnotfound(CloudifyClientError): """ Raised when a plugin is listed in the blueprint but is not installed on the manager. """ error_code = 'deployment_plugin_not_found' error_mapping = dict([(error.ERROR_CODE, error) for error in [DeploymentEnvironmentCreationInProgressError, DeploymentEnvironmentCreationPendingError, IllegalExecutionParametersError, NoSuchIncludeFieldError, MissingRequiredDeploymentInputError, UnknownDeploymentInputError, UnknownDeploymentSecretError, UnsupportedDeploymentGetSecretError, FunctionsEvaluationError, UnknownModificationStageError, ExistingStartedDeploymentModificationError, DeploymentModificationAlreadyEndedError, UserUnauthorizedError, ForbiddenError, MaintenanceModeActiveError, MaintenanceModeActivatingError, NotModifiedError, InvalidExecutionUpdateStatus, PluginInUseError, PluginInstallationError, PluginInstallationTimeout, NotClusterMaster, RemovedFromCluster, DeploymentPluginNotFound]])
array = [] for _ in range(int(input())): command = input().strip().split(" ") cmd_type = command[0] if (cmd_type == "print"): print(array) elif (cmd_type == "sort"): array.sort() elif (cmd_type == "reverse"): array.reverse() elif (cmd_type == "pop"): array.pop() elif (cmd_type == "remove"): array.remove(int(command[1])) elif (cmd_type == "append"): array.append(int(command[1])) elif (cmd_type == "insert"): array.insert(int(command[1]), int(command[2]))
array = [] for _ in range(int(input())): command = input().strip().split(' ') cmd_type = command[0] if cmd_type == 'print': print(array) elif cmd_type == 'sort': array.sort() elif cmd_type == 'reverse': array.reverse() elif cmd_type == 'pop': array.pop() elif cmd_type == 'remove': array.remove(int(command[1])) elif cmd_type == 'append': array.append(int(command[1])) elif cmd_type == 'insert': array.insert(int(command[1]), int(command[2]))
# -*- coding: utf-8 -*- """ mundiapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class UpdatePlanRequest(object): """Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text that will be shown on the credit card's statement currency (string): Currency interval (string): Interval interval_count (int): Interval count payment_methods (list of string): Payment methods accepted by the plan billing_type (string): Billing type status (string): Plan status shippable (bool): Indicates if the plan is shippable billing_days (list of int): Billing days accepted by the plan metadata (dict<object, string>): Metadata minimum_price (int): Minimum price trial_period_days (int): Number of trial period in days, where the customer will not be charged """ # Create a mapping from Model property names to API property names _names = { "name":'name', "description":'description', "installments":'installments', "statement_descriptor":'statement_descriptor', "currency":'currency', "interval":'interval', "interval_count":'interval_count', "payment_methods":'payment_methods', "billing_type":'billing_type', "status":'status', "shippable":'shippable', "billing_days":'billing_days', "metadata":'metadata', "minimum_price":'minimum_price', "trial_period_days":'trial_period_days' } def __init__(self, name=None, description=None, installments=None, statement_descriptor=None, currency=None, interval=None, interval_count=None, payment_methods=None, billing_type=None, status=None, shippable=None, billing_days=None, metadata=None, minimum_price=None, trial_period_days=None): """Constructor for the UpdatePlanRequest class""" # Initialize members of the class self.name = name self.description = description self.installments = installments self.statement_descriptor = statement_descriptor self.currency = currency self.interval = interval self.interval_count = interval_count self.payment_methods = payment_methods self.billing_type = billing_type self.status = status self.shippable = shippable self.billing_days = billing_days self.metadata = metadata self.minimum_price = minimum_price self.trial_period_days = trial_period_days @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None # Extract variables from the dictionary name = dictionary.get('name') description = dictionary.get('description') installments = dictionary.get('installments') statement_descriptor = dictionary.get('statement_descriptor') currency = dictionary.get('currency') interval = dictionary.get('interval') interval_count = dictionary.get('interval_count') payment_methods = dictionary.get('payment_methods') billing_type = dictionary.get('billing_type') status = dictionary.get('status') shippable = dictionary.get('shippable') billing_days = dictionary.get('billing_days') metadata = dictionary.get('metadata') minimum_price = dictionary.get('minimum_price') trial_period_days = dictionary.get('trial_period_days') # Return an object of this model return cls(name, description, installments, statement_descriptor, currency, interval, interval_count, payment_methods, billing_type, status, shippable, billing_days, metadata, minimum_price, trial_period_days)
""" mundiapi This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ class Updateplanrequest(object): """Implementation of the 'UpdatePlanRequest' model. Request for updating a plan Attributes: name (string): Plan's name description (string): Description installments (list of int): Number os installments statement_descriptor (string): Text that will be shown on the credit card's statement currency (string): Currency interval (string): Interval interval_count (int): Interval count payment_methods (list of string): Payment methods accepted by the plan billing_type (string): Billing type status (string): Plan status shippable (bool): Indicates if the plan is shippable billing_days (list of int): Billing days accepted by the plan metadata (dict<object, string>): Metadata minimum_price (int): Minimum price trial_period_days (int): Number of trial period in days, where the customer will not be charged """ _names = {'name': 'name', 'description': 'description', 'installments': 'installments', 'statement_descriptor': 'statement_descriptor', 'currency': 'currency', 'interval': 'interval', 'interval_count': 'interval_count', 'payment_methods': 'payment_methods', 'billing_type': 'billing_type', 'status': 'status', 'shippable': 'shippable', 'billing_days': 'billing_days', 'metadata': 'metadata', 'minimum_price': 'minimum_price', 'trial_period_days': 'trial_period_days'} def __init__(self, name=None, description=None, installments=None, statement_descriptor=None, currency=None, interval=None, interval_count=None, payment_methods=None, billing_type=None, status=None, shippable=None, billing_days=None, metadata=None, minimum_price=None, trial_period_days=None): """Constructor for the UpdatePlanRequest class""" self.name = name self.description = description self.installments = installments self.statement_descriptor = statement_descriptor self.currency = currency self.interval = interval self.interval_count = interval_count self.payment_methods = payment_methods self.billing_type = billing_type self.status = status self.shippable = shippable self.billing_days = billing_days self.metadata = metadata self.minimum_price = minimum_price self.trial_period_days = trial_period_days @classmethod def from_dictionary(cls, dictionary): """Creates an instance of this model from a dictionary Args: dictionary (dictionary): A dictionary representation of the object as obtained from the deserialization of the server's response. The keys MUST match property names in the API description. Returns: object: An instance of this structure class. """ if dictionary is None: return None name = dictionary.get('name') description = dictionary.get('description') installments = dictionary.get('installments') statement_descriptor = dictionary.get('statement_descriptor') currency = dictionary.get('currency') interval = dictionary.get('interval') interval_count = dictionary.get('interval_count') payment_methods = dictionary.get('payment_methods') billing_type = dictionary.get('billing_type') status = dictionary.get('status') shippable = dictionary.get('shippable') billing_days = dictionary.get('billing_days') metadata = dictionary.get('metadata') minimum_price = dictionary.get('minimum_price') trial_period_days = dictionary.get('trial_period_days') return cls(name, description, installments, statement_descriptor, currency, interval, interval_count, payment_methods, billing_type, status, shippable, billing_days, metadata, minimum_price, trial_period_days)
class AuthError(Exception): pass class JsonError(Exception): pass
class Autherror(Exception): pass class Jsonerror(Exception): pass
# 3. Define a function to check whether a number is even def even(num): if num%2 == 0: return True else: return False print(even(4)) print(even(-5))
def even(num): if num % 2 == 0: return True else: return False print(even(4)) print(even(-5))
class OverlapResult: def __init__(self, overlap_map: dict[tuple[float, float], int]): self._overlap_map = overlap_map self._overlaps = overlap_map_to_overlaps(overlap_map) @property def overlaps(self) -> int: return self._overlaps @property def overlap_map(self) -> dict[tuple[float, float], int]: return self._overlap_map def overlap_map_to_overlaps(overlap_map: dict[tuple[float, float], int], minimal_overlap=2) -> int: return len(list(filter(lambda val: val >= minimal_overlap, overlap_map.values())))
class Overlapresult: def __init__(self, overlap_map: dict[tuple[float, float], int]): self._overlap_map = overlap_map self._overlaps = overlap_map_to_overlaps(overlap_map) @property def overlaps(self) -> int: return self._overlaps @property def overlap_map(self) -> dict[tuple[float, float], int]: return self._overlap_map def overlap_map_to_overlaps(overlap_map: dict[tuple[float, float], int], minimal_overlap=2) -> int: return len(list(filter(lambda val: val >= minimal_overlap, overlap_map.values())))
class Config: def __init__(self, config_file_name): self.config_file_name = config_file_name
class Config: def __init__(self, config_file_name): self.config_file_name = config_file_name
""" module logging""" # logging
""" module logging"""
# @AUTHOR : lonsty # @DATE : 2020/3/28 18:01 class CookiesExpiredException(Exception): pass class NoImagesException(Exception): pass class ContentParserError(Exception): pass class UserNotFound(Exception): pass
class Cookiesexpiredexception(Exception): pass class Noimagesexception(Exception): pass class Contentparsererror(Exception): pass class Usernotfound(Exception): pass
"""Errors.""" class ProxyError(Exception): pass class NoProxyError(Exception): pass class ResolveError(Exception): pass class ProxyConnError(ProxyError): pass class ProxyRecvError(ProxyError): # connection_is_reset pass class ProxySendError(ProxyError): # connection_is_reset pass class ProxyTimeoutError(ProxyError): pass class ProxyEmptyResponseError(ProxyError): pass class BadStatusError(Exception): # BadStatusLine pass class BadResponseError(Exception): pass class BadStatusLine(Exception): pass class ErrorOnStream(Exception): pass
"""Errors.""" class Proxyerror(Exception): pass class Noproxyerror(Exception): pass class Resolveerror(Exception): pass class Proxyconnerror(ProxyError): pass class Proxyrecverror(ProxyError): pass class Proxysenderror(ProxyError): pass class Proxytimeouterror(ProxyError): pass class Proxyemptyresponseerror(ProxyError): pass class Badstatuserror(Exception): pass class Badresponseerror(Exception): pass class Badstatusline(Exception): pass class Erroronstream(Exception): pass
def can_build(env, platform): return True def configure(env): pass def get_doc_classes(): return [ "WorldArea", "VoxelLight", "VoxelLightNode", "VoxelLevelGenerator", "VoxelLevelGeneratorFlat", "VoxelSurfaceMerger", "VoxelSurfaceSimple", "VoxelSurface", "VoxelLibraryMerger", "VoxelLibrarySimple", "VoxelLibrary", "VoxelLibraryMergerPCM", "VoxelMaterialCache", "VoxelMaterialCachePCM", "VoxelCubePoints", "VoxelMesherCubic", "VoxelMeshData", "MarchingCubesCellData", "VoxelMesherMarchingCubes", "VoxelMesher", "EnvironmentData", "VoxelChunk", "VoxelChunkDefault", "VoxelStructure", "BlockVoxelStructure", "VoxelWorld", "VoxelMesherBlocky", "VoxelWorldBlocky", "VoxelChunkBlocky", "VoxelMesherLiquidBlocky", "VoxelWorldMarchingCubes", "VoxelChunkMarchingCubes", "VoxelMesherCubic", "VoxelWorldCubic", "VoxelChunkCubic", "VoxelMesherDefault", "VoxelWorldDefault", "VoxelJob", "VoxelTerrainJob", "VoxelLightJob", "VoxelPropJob", "VoxelMesherJobStep", ] def get_doc_path(): return "doc_classes"
def can_build(env, platform): return True def configure(env): pass def get_doc_classes(): return ['WorldArea', 'VoxelLight', 'VoxelLightNode', 'VoxelLevelGenerator', 'VoxelLevelGeneratorFlat', 'VoxelSurfaceMerger', 'VoxelSurfaceSimple', 'VoxelSurface', 'VoxelLibraryMerger', 'VoxelLibrarySimple', 'VoxelLibrary', 'VoxelLibraryMergerPCM', 'VoxelMaterialCache', 'VoxelMaterialCachePCM', 'VoxelCubePoints', 'VoxelMesherCubic', 'VoxelMeshData', 'MarchingCubesCellData', 'VoxelMesherMarchingCubes', 'VoxelMesher', 'EnvironmentData', 'VoxelChunk', 'VoxelChunkDefault', 'VoxelStructure', 'BlockVoxelStructure', 'VoxelWorld', 'VoxelMesherBlocky', 'VoxelWorldBlocky', 'VoxelChunkBlocky', 'VoxelMesherLiquidBlocky', 'VoxelWorldMarchingCubes', 'VoxelChunkMarchingCubes', 'VoxelMesherCubic', 'VoxelWorldCubic', 'VoxelChunkCubic', 'VoxelMesherDefault', 'VoxelWorldDefault', 'VoxelJob', 'VoxelTerrainJob', 'VoxelLightJob', 'VoxelPropJob', 'VoxelMesherJobStep'] def get_doc_path(): return 'doc_classes'
# The Pokemon class should receive a name (string) and health (int) upon initialization. # It should also have a method called pokemon_details that returns the information about the pokemon: # "{pokemon_name} with health {pokemon_health}" class Pokemon: def __init__(self, name: str, health: int) -> None: self.name = name self.health = health def pokemon_details(self) -> str: return f"{self.name} with health {self.health}"
class Pokemon: def __init__(self, name: str, health: int) -> None: self.name = name self.health = health def pokemon_details(self) -> str: return f'{self.name} with health {self.health}'
{ "includes": [ "../common.gypi" ], "targets": [ { "target_name": "libgdal_ogr_mem_frmt", "type": "static_library", "sources": [ "../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp", "../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp", "../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp" ], "include_dirs": [ "../gdal/ogr/ogrsf_frmts/mem" ] } ] }
{'includes': ['../common.gypi'], 'targets': [{'target_name': 'libgdal_ogr_mem_frmt', 'type': 'static_library', 'sources': ['../gdal/ogr/ogrsf_frmts/mem/ogrmemdatasource.cpp', '../gdal/ogr/ogrsf_frmts/mem/ogrmemlayer.cpp', '../gdal/ogr/ogrsf_frmts/mem/ogrmemdriver.cpp'], 'include_dirs': ['../gdal/ogr/ogrsf_frmts/mem']}]}
_base_ = ['./tracktor_faster-rcnn_r50_fpn_4e_mot17-public-half.py'] model = dict( pretrains=dict( detector= # noqa: E251 'https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-ffa52ae7.pth' # noqa: E501 )) data_root = 'data/MOT17/' test_set = 'test' data = dict( train=dict(ann_file=data_root + 'annotations/train_cocoformat.json'), val=dict( ann_file=data_root + 'annotations/train_cocoformat.json', detection_file=data_root + 'annotations/train_detections.pkl'), test=dict( ann_file=data_root + f'annotations/{test_set}_cocoformat.json', img_prefix=data_root + test_set, detection_file=data_root + f'annotations/{test_set}_detections.pkl'))
_base_ = ['./tracktor_faster-rcnn_r50_fpn_4e_mot17-public-half.py'] model = dict(pretrains=dict(detector='https://download.openmmlab.com/mmtracking/mot/faster_rcnn/faster-rcnn_r50_fpn_4e_mot17-ffa52ae7.pth')) data_root = 'data/MOT17/' test_set = 'test' data = dict(train=dict(ann_file=data_root + 'annotations/train_cocoformat.json'), val=dict(ann_file=data_root + 'annotations/train_cocoformat.json', detection_file=data_root + 'annotations/train_detections.pkl'), test=dict(ann_file=data_root + f'annotations/{test_set}_cocoformat.json', img_prefix=data_root + test_set, detection_file=data_root + f'annotations/{test_set}_detections.pkl'))
# This file is part of Ansible # # Ansible is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Ansible is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Ansible. If not, see <http://www.gnu.org/licenses/>. # class ModuleDocFragment(object): # Docker doc fragment DOCUMENTATION = ''' options: docker_host: description: - "The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the TCP connection string. For example, 'tcp://192.0.2.23:2376'. If TLS is used to encrypt the connection, the module will automatically replace 'tcp' in the connection URL with 'https'." required: false default: "unix://var/run/docker.sock" aliases: - docker_url tls_hostname: description: - When verifying the authenticity of the Docker Host server, provide the expected name of the server. default: localhost required: false api_version: description: - The version of the Docker API running on the Docker Host. Defaults to the latest version of the API supported by docker-py. required: false default: default provided by docker-py aliases: - docker_api_version timeout: description: - The maximum amount of time in seconds to wait on a response from the API. required: false default: 60 cacert_path: description: - Use a CA certificate when performing server verification by providing the path to a CA certificate file. required: false default: null aliases: - tls_ca_cert cert_path: description: - Path to the client's TLS certificate file. required: false default: null aliases: - tls_client_cert key_path: description: - Path to the client's TLS key file. required: false default: null aliases: - tls_client_key ssl_version: description: - Provide a valid SSL version number. Default value determined by docker-py, currently 1.0. required: false default: "1.0" tls: description: - Secure the connection to the API by using TLS without verifying the authenticity of the Docker host server. default: false tls_verify: description: - Secure the connection to the API by using TLS and verifying the authenticity of the Docker host server. default: false notes: - Connect to the Docker daemon by providing parameters with each task or by defining environment variables. You can define DOCKER_HOST, DOCKER_TLS_HOSTNAME, DOCKER_API_VERSION, DOCKER_CERT_PATH, DOCKER_SSL_VERSION, DOCKER_TLS, DOCKER_TLS_VERIFY and DOCKER_TIMEOUT. If you are using docker machine, run the script shipped with the product that sets up the environment. It will set these variables for you. See https://docker-py.readthedocs.org/en/stable/machine/ for more details. '''
class Moduledocfragment(object): documentation = '\n\noptions:\n docker_host:\n description:\n - "The URL or Unix socket path used to connect to the Docker API. To connect to a remote host, provide the\n TCP connection string. For example, \'tcp://192.0.2.23:2376\'. If TLS is used to encrypt the connection,\n the module will automatically replace \'tcp\' in the connection URL with \'https\'."\n required: false\n default: "unix://var/run/docker.sock"\n aliases:\n - docker_url\n tls_hostname:\n description:\n - When verifying the authenticity of the Docker Host server, provide the expected name of the server.\n default: localhost\n required: false\n api_version:\n description:\n - The version of the Docker API running on the Docker Host. Defaults to the latest version of the API\n supported by docker-py.\n required: false\n default: default provided by docker-py\n aliases:\n - docker_api_version\n timeout:\n description:\n - The maximum amount of time in seconds to wait on a response from the API.\n required: false\n default: 60\n cacert_path:\n description:\n - Use a CA certificate when performing server verification by providing the path to a CA certificate file.\n required: false\n default: null\n aliases:\n - tls_ca_cert\n cert_path:\n description:\n - Path to the client\'s TLS certificate file.\n required: false\n default: null\n aliases:\n - tls_client_cert\n key_path:\n description:\n - Path to the client\'s TLS key file.\n required: false\n default: null\n aliases:\n - tls_client_key\n ssl_version:\n description:\n - Provide a valid SSL version number. Default value determined by docker-py, currently 1.0.\n required: false\n default: "1.0"\n tls:\n description:\n - Secure the connection to the API by using TLS without verifying the authenticity of the Docker host\n server.\n default: false\n tls_verify:\n description:\n - Secure the connection to the API by using TLS and verifying the authenticity of the Docker host server.\n default: false\n\nnotes:\n - Connect to the Docker daemon by providing parameters with each task or by defining environment variables.\n You can define DOCKER_HOST, DOCKER_TLS_HOSTNAME, DOCKER_API_VERSION, DOCKER_CERT_PATH, DOCKER_SSL_VERSION,\n DOCKER_TLS, DOCKER_TLS_VERIFY and DOCKER_TIMEOUT. If you are using docker machine, run the script shipped\n with the product that sets up the environment. It will set these variables for you. See\n https://docker-py.readthedocs.org/en/stable/machine/ for more details.\n'
DEFAULT_MIRRORS = { "bitbucket": [ "https://bitbucket.org/{repository}/get/{commit}.tar.gz", ], "buildifier": [ "https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}", ], "github": [ "https://github.com/{repository}/archive/{commit}.tar.gz", ], "pypi": [ "https://files.pythonhosted.org/packages/source/{p}/{package}/{package}-{version}.tar.gz", ], }
default_mirrors = {'bitbucket': ['https://bitbucket.org/{repository}/get/{commit}.tar.gz'], 'buildifier': ['https://github.com/bazelbuild/buildtools/releases/download/{version}/{filename}'], 'github': ['https://github.com/{repository}/archive/{commit}.tar.gz'], 'pypi': ['https://files.pythonhosted.org/packages/source/{p}/{package}/{package}-{version}.tar.gz']}
#!/usr/bin/env python3.4 # coding: utf-8 class Drawable: """ Base class for drawable objects. """ def draw(self): """ Returns a Surface object. """ raise NotImplementedError( "Method `draw` is not implemented for {}".format(type(self)))
class Drawable: """ Base class for drawable objects. """ def draw(self): """ Returns a Surface object. """ raise not_implemented_error('Method `draw` is not implemented for {}'.format(type(self)))
def integrate_exponential(a, x0, dt, T): """Compute solution of the differential equation xdot=a*x with initial condition x0 for a duration T. Use time step dt for numerical solution. Args: a (scalar): parameter of xdot (xdot=a*x) x0 (scalar): initial condition (x at time 0) dt (scalar): timestep of the simulation T (scalar): total duration of the simulation Returns: ndarray, ndarray: `x` for all simulation steps and the time `t` at each step """ # Initialize variables t = np.arange(0, T, dt) x = np.zeros_like(t, dtype=complex) x[0] = x0 # Step through system and integrate in time for k in range(1, len(t)): # for each point in time, compute xdot = a*x xdot = (a*x[k-1]) # update x by adding xdot scaled by dt x[k] = x[k-1] + xdot * dt return x, t # choose parameters a = -0.5 # parameter in f(x) T = 10 # total Time duration dt = 0.001 # timestep of our simulation x0 = 1. # initial condition of x at time 0 x, t = integrate_exponential(a, x0, dt, T) with plt.xkcd(): fig = plt.figure(figsize=(8, 6)) plt.plot(t, x.real) plt.xlabel('Time (s)') plt.ylabel('x')
def integrate_exponential(a, x0, dt, T): """Compute solution of the differential equation xdot=a*x with initial condition x0 for a duration T. Use time step dt for numerical solution. Args: a (scalar): parameter of xdot (xdot=a*x) x0 (scalar): initial condition (x at time 0) dt (scalar): timestep of the simulation T (scalar): total duration of the simulation Returns: ndarray, ndarray: `x` for all simulation steps and the time `t` at each step """ t = np.arange(0, T, dt) x = np.zeros_like(t, dtype=complex) x[0] = x0 for k in range(1, len(t)): xdot = a * x[k - 1] x[k] = x[k - 1] + xdot * dt return (x, t) a = -0.5 t = 10 dt = 0.001 x0 = 1.0 (x, t) = integrate_exponential(a, x0, dt, T) with plt.xkcd(): fig = plt.figure(figsize=(8, 6)) plt.plot(t, x.real) plt.xlabel('Time (s)') plt.ylabel('x')
class Animal(): edad:int patas:int ruido:str nombre: str kgComida: float = 0 def __init__(self, edad, patas, ruido, nombre): self.edad =edad self.patas = patas self.ruido = ruido self.nombre = nombre def comer(self, alimento): self.kgComida += alimento print('Hola,', self.nombre, 'comes', self.kgComida) def hacerRuido(self): print('Hola', self.nombre, 'haces' , self.ruido)
class Animal: edad: int patas: int ruido: str nombre: str kg_comida: float = 0 def __init__(self, edad, patas, ruido, nombre): self.edad = edad self.patas = patas self.ruido = ruido self.nombre = nombre def comer(self, alimento): self.kgComida += alimento print('Hola,', self.nombre, 'comes', self.kgComida) def hacer_ruido(self): print('Hola', self.nombre, 'haces', self.ruido)
maxWeight = 30 value = [15, 7, 10, 5, 8, 17] weight = [15, 3, 2, 5, 9, 20] def bag(pos, selected): # calcula o total totalValue = 0 pesoTotal = 0 for i in selected: totalValue += value[i] pesoTotal += weight[i] if pesoTotal > maxWeight: return (0,0) if pos >= len(weight): return (totalValue, pesoTotal) answer1 = bag(pos + 1, selected + [pos]) answer2 = bag(pos + 1, list(selected)) if answer1[0] > answer2[0]: return answer1 else: return answer2 bestAnswer = bag(0, []) print(bestAnswer)
max_weight = 30 value = [15, 7, 10, 5, 8, 17] weight = [15, 3, 2, 5, 9, 20] def bag(pos, selected): total_value = 0 peso_total = 0 for i in selected: total_value += value[i] peso_total += weight[i] if pesoTotal > maxWeight: return (0, 0) if pos >= len(weight): return (totalValue, pesoTotal) answer1 = bag(pos + 1, selected + [pos]) answer2 = bag(pos + 1, list(selected)) if answer1[0] > answer2[0]: return answer1 else: return answer2 best_answer = bag(0, []) print(bestAnswer)
def fibo(n): return n <= 1 or fibo(n-1) + fibo(n-2) def fibo_main(): for n in range(1,47): res = fibo(n) print("%s\t%s" % (n, res)) fibo_main() # profiling result for 47 numbers # profile: python -m profile fibo.py """ -1273940835 function calls (275 primitive calls) in 18966.707 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 90 0.000 0.000 0.001 0.000 cp857.py:18(encode) 1 0.000 0.000 18966.707 18966.707 fibo.py:1(<module>) -1273941064/46 18966.697 -0.000 18966.697 412.319 fibo.py:1(fibo) 1 0.001 0.001 18966.707 18966.707 fibo.py:4(main) 90 0.000 0.000 0.000 0.000 {built-in method charmap_encode} 1 0.000 0.000 18966.707 18966.707 {built-in method exec} 45 0.009 0.000 0.010 0.000 {built-in method print} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Prof iler' objects} """
def fibo(n): return n <= 1 or fibo(n - 1) + fibo(n - 2) def fibo_main(): for n in range(1, 47): res = fibo(n) print('%s\t%s' % (n, res)) fibo_main() "\n -1273940835 function calls (275 primitive calls) in 18966.707 seconds\n\n Ordered by: standard name\n\n ncalls tottime percall cumtime percall filename:lineno(function)\n 90 0.000 0.000 0.001 0.000 cp857.py:18(encode)\n 1 0.000 0.000 18966.707 18966.707 fibo.py:1(<module>)\n-1273941064/46 18966.697 -0.000 18966.697 412.319 fibo.py:1(fibo)\n 1 0.001 0.001 18966.707 18966.707 fibo.py:4(main)\n 90 0.000 0.000 0.000 0.000 {built-in method charmap_encode}\n 1 0.000 0.000 18966.707 18966.707 {built-in method exec}\n 45 0.009 0.000 0.010 0.000 {built-in method print}\n 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Prof\niler' objects}\n"
#!/usr/bin/env python3 # Copyright (c) 2014, Ruslan Baratov # All rights reserved. """ * Wiki table for `leathers` C++ project Expected format: ### Main table Name | Clang | GCC | MSVC | -----------------------------|----------|----------|------| static-ctor-not-thread-safe | *no* | *no* | 4640 | switch | **same** | **same** | 4062 | switch-enum | **same** | **same** | 4061 | ### Xcode/Clang table Clang | Xcode | Objective-C | -----------------------|--------------------------------|-------------| bool-conversion | CLANG_WARN_BOOL_CONVERSION | no | c++11-extensions | CLANG_WARN_CXX0X_EXTENSIONS | no | strict-selector-match | GCC_WARN_STRICT_SELECTOR_MATCH | yes | undeclared-selector | GCC_WARN_UNDECLARED_SELECTOR | yes | """ def generate(main_warnings_table): groups = set() for i in main_warnings_table: if i.group != "": groups.add(i.group) wiki_file = open("wiki-table.txt", "w") generate_main_table(main_warnings_table, wiki_file) for group in groups: generate_group_table(main_warnings_table, wiki_file, group) generate_xcode_table(main_warnings_table, wiki_file) def generate_main_table(main_warnings_table, wiki_file): head_name = "Name" head_clang = "Clang" head_gcc = "GCC" head_msvc = "MSVC" def calc_max(head, visitor): max_len = len(head) for x in main_warnings_table: cur_len = visitor(x) if cur_len > max_len: max_len = cur_len return max_len + 2 def name_visitor(table_entry): if table_entry.group != "": return 0 return len(table_entry.warning_name) def clang_visitor(table_entry): if table_entry.group != "": return 0 return len(table_entry.clang.wiki_entry(table_entry.warning_name)) def gcc_visitor(table_entry): if table_entry.group != "": return 0 return len(table_entry.gcc.wiki_entry(table_entry.warning_name)) def msvc_visitor(table_entry): if table_entry.group != "": return 0 return len(table_entry.msvc.wiki_entry(table_entry.warning_name)) max_name = calc_max(head_name, name_visitor) max_clang = calc_max(head_clang, clang_visitor) max_gcc = calc_max(head_gcc, gcc_visitor) max_msvc = calc_max(head_msvc, msvc_visitor) def fill_string(name, max_name): result = " " + name + " "; assert(max_name >= len(result)) left = max_name - len(result) return result + " " * left wiki_file.write("### Main table\n\n") s = "{}|{}|{}|{}|\n".format( fill_string(head_name, max_name), fill_string(head_clang, max_clang), fill_string(head_gcc, max_gcc), fill_string(head_msvc, max_msvc), ) wiki_file.write(s) s = "{}|{}|{}|{}|\n".format( '-' * max_name, '-' * max_clang, '-' * max_gcc, '-' * max_msvc, ) wiki_file.write(s) for entry in main_warnings_table: if entry.group != "": continue s = "{}|{}|{}|{}|\n".format( fill_string(entry.warning_name, max_name), fill_string(entry.clang.wiki_entry(entry.warning_name), max_clang), fill_string(entry.gcc.wiki_entry(entry.warning_name), max_gcc), fill_string(entry.msvc.wiki_entry(entry.warning_name), max_msvc), ) wiki_file.write(s) def generate_group_table(main_warnings_table, wiki_file, group): head_name = "Name" head_clang = "Clang" head_gcc = "GCC" head_msvc = "MSVC" def calc_max(head, visitor): max_len = len(head) for x in main_warnings_table: cur_len = visitor(x) if cur_len > max_len: max_len = cur_len return max_len + 2 def name_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.warning_name) def clang_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.clang.wiki_entry(table_entry.warning_name)) def gcc_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.gcc.wiki_entry(table_entry.warning_name)) def msvc_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.msvc.wiki_entry(table_entry.warning_name)) max_name = calc_max(head_name, name_visitor) max_clang = calc_max(head_clang, clang_visitor) max_gcc = calc_max(head_gcc, gcc_visitor) max_msvc = calc_max(head_msvc, msvc_visitor) def fill_string(name, max_name): result = " " + name + " "; assert(max_name >= len(result)) left = max_name - len(result) return result + " " * left wiki_file.write("\n### Table for group: `{}`\n\n".format(group)) s = "{}|{}|{}|{}|\n".format( fill_string(head_name, max_name), fill_string(head_clang, max_clang), fill_string(head_gcc, max_gcc), fill_string(head_msvc, max_msvc), ) wiki_file.write(s) s = "{}|{}|{}|{}|\n".format( '-' * max_name, '-' * max_clang, '-' * max_gcc, '-' * max_msvc, ) wiki_file.write(s) for entry in main_warnings_table: if entry.group != group: continue s = "{}|{}|{}|{}|\n".format( fill_string(entry.warning_name, max_name), fill_string(entry.clang.wiki_entry(entry.warning_name), max_clang), fill_string(entry.gcc.wiki_entry(entry.warning_name), max_gcc), fill_string(entry.msvc.wiki_entry(entry.warning_name), max_msvc), ) wiki_file.write(s) def generate_xcode_table(main_warnings_table, wiki_file): head_clang = "Clang" head_xcode = "Xcode" head_objc = "Objective-C" def calc_max(head, visitor): max_len = len(head) for x in main_warnings_table: cur_len = visitor(x) if cur_len > max_len: max_len = cur_len return max_len + 2 def clang_visitor(table_entry): if table_entry.xcode.option == "": return 0 return len(table_entry.clang.option) def xcode_visitor(table_entry): if table_entry.xcode.option == "": return 0 return len(table_entry.xcode.option) def objc_visitor(table_entry): if table_entry.xcode.option == "": return 0 if table_entry.objc: return 3 # "yes" else: return 2 # "no" max_clang = calc_max(head_clang, clang_visitor) max_xcode = calc_max(head_xcode, xcode_visitor) max_objc = calc_max(head_objc, objc_visitor) def fill_string(name, max_name): result = " " + name + " "; assert(max_name >= len(result)) left = max_name - len(result) return result + " " * left wiki_file.write("\n\n### Xcode/Clang table\n\n") s = "{}|{}|{}|\n".format( fill_string(head_clang, max_clang), fill_string(head_xcode, max_xcode), fill_string(head_objc, max_objc), ) wiki_file.write(s) s = "{}|{}|{}|\n".format( '-' * max_clang, '-' * max_xcode, '-' * max_objc, ) wiki_file.write(s) done_list = [] for entry in main_warnings_table: if entry.xcode.option == "": continue if entry.clang.option in done_list: continue done_list.append(entry.clang.option) if entry.objc: objc = "yes" else: objc = "no" s = "{}|{}|{}|\n".format( fill_string(entry.clang.option, max_clang), fill_string(entry.xcode.option, max_xcode), fill_string(objc, max_objc), ) wiki_file.write(s)
""" * Wiki table for `leathers` C++ project Expected format: ### Main table Name | Clang | GCC | MSVC | -----------------------------|----------|----------|------| static-ctor-not-thread-safe | *no* | *no* | 4640 | switch | **same** | **same** | 4062 | switch-enum | **same** | **same** | 4061 | ### Xcode/Clang table Clang | Xcode | Objective-C | -----------------------|--------------------------------|-------------| bool-conversion | CLANG_WARN_BOOL_CONVERSION | no | c++11-extensions | CLANG_WARN_CXX0X_EXTENSIONS | no | strict-selector-match | GCC_WARN_STRICT_SELECTOR_MATCH | yes | undeclared-selector | GCC_WARN_UNDECLARED_SELECTOR | yes | """ def generate(main_warnings_table): groups = set() for i in main_warnings_table: if i.group != '': groups.add(i.group) wiki_file = open('wiki-table.txt', 'w') generate_main_table(main_warnings_table, wiki_file) for group in groups: generate_group_table(main_warnings_table, wiki_file, group) generate_xcode_table(main_warnings_table, wiki_file) def generate_main_table(main_warnings_table, wiki_file): head_name = 'Name' head_clang = 'Clang' head_gcc = 'GCC' head_msvc = 'MSVC' def calc_max(head, visitor): max_len = len(head) for x in main_warnings_table: cur_len = visitor(x) if cur_len > max_len: max_len = cur_len return max_len + 2 def name_visitor(table_entry): if table_entry.group != '': return 0 return len(table_entry.warning_name) def clang_visitor(table_entry): if table_entry.group != '': return 0 return len(table_entry.clang.wiki_entry(table_entry.warning_name)) def gcc_visitor(table_entry): if table_entry.group != '': return 0 return len(table_entry.gcc.wiki_entry(table_entry.warning_name)) def msvc_visitor(table_entry): if table_entry.group != '': return 0 return len(table_entry.msvc.wiki_entry(table_entry.warning_name)) max_name = calc_max(head_name, name_visitor) max_clang = calc_max(head_clang, clang_visitor) max_gcc = calc_max(head_gcc, gcc_visitor) max_msvc = calc_max(head_msvc, msvc_visitor) def fill_string(name, max_name): result = ' ' + name + ' ' assert max_name >= len(result) left = max_name - len(result) return result + ' ' * left wiki_file.write('### Main table\n\n') s = '{}|{}|{}|{}|\n'.format(fill_string(head_name, max_name), fill_string(head_clang, max_clang), fill_string(head_gcc, max_gcc), fill_string(head_msvc, max_msvc)) wiki_file.write(s) s = '{}|{}|{}|{}|\n'.format('-' * max_name, '-' * max_clang, '-' * max_gcc, '-' * max_msvc) wiki_file.write(s) for entry in main_warnings_table: if entry.group != '': continue s = '{}|{}|{}|{}|\n'.format(fill_string(entry.warning_name, max_name), fill_string(entry.clang.wiki_entry(entry.warning_name), max_clang), fill_string(entry.gcc.wiki_entry(entry.warning_name), max_gcc), fill_string(entry.msvc.wiki_entry(entry.warning_name), max_msvc)) wiki_file.write(s) def generate_group_table(main_warnings_table, wiki_file, group): head_name = 'Name' head_clang = 'Clang' head_gcc = 'GCC' head_msvc = 'MSVC' def calc_max(head, visitor): max_len = len(head) for x in main_warnings_table: cur_len = visitor(x) if cur_len > max_len: max_len = cur_len return max_len + 2 def name_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.warning_name) def clang_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.clang.wiki_entry(table_entry.warning_name)) def gcc_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.gcc.wiki_entry(table_entry.warning_name)) def msvc_visitor(table_entry): if table_entry.group != group: return 0 return len(table_entry.msvc.wiki_entry(table_entry.warning_name)) max_name = calc_max(head_name, name_visitor) max_clang = calc_max(head_clang, clang_visitor) max_gcc = calc_max(head_gcc, gcc_visitor) max_msvc = calc_max(head_msvc, msvc_visitor) def fill_string(name, max_name): result = ' ' + name + ' ' assert max_name >= len(result) left = max_name - len(result) return result + ' ' * left wiki_file.write('\n### Table for group: `{}`\n\n'.format(group)) s = '{}|{}|{}|{}|\n'.format(fill_string(head_name, max_name), fill_string(head_clang, max_clang), fill_string(head_gcc, max_gcc), fill_string(head_msvc, max_msvc)) wiki_file.write(s) s = '{}|{}|{}|{}|\n'.format('-' * max_name, '-' * max_clang, '-' * max_gcc, '-' * max_msvc) wiki_file.write(s) for entry in main_warnings_table: if entry.group != group: continue s = '{}|{}|{}|{}|\n'.format(fill_string(entry.warning_name, max_name), fill_string(entry.clang.wiki_entry(entry.warning_name), max_clang), fill_string(entry.gcc.wiki_entry(entry.warning_name), max_gcc), fill_string(entry.msvc.wiki_entry(entry.warning_name), max_msvc)) wiki_file.write(s) def generate_xcode_table(main_warnings_table, wiki_file): head_clang = 'Clang' head_xcode = 'Xcode' head_objc = 'Objective-C' def calc_max(head, visitor): max_len = len(head) for x in main_warnings_table: cur_len = visitor(x) if cur_len > max_len: max_len = cur_len return max_len + 2 def clang_visitor(table_entry): if table_entry.xcode.option == '': return 0 return len(table_entry.clang.option) def xcode_visitor(table_entry): if table_entry.xcode.option == '': return 0 return len(table_entry.xcode.option) def objc_visitor(table_entry): if table_entry.xcode.option == '': return 0 if table_entry.objc: return 3 else: return 2 max_clang = calc_max(head_clang, clang_visitor) max_xcode = calc_max(head_xcode, xcode_visitor) max_objc = calc_max(head_objc, objc_visitor) def fill_string(name, max_name): result = ' ' + name + ' ' assert max_name >= len(result) left = max_name - len(result) return result + ' ' * left wiki_file.write('\n\n### Xcode/Clang table\n\n') s = '{}|{}|{}|\n'.format(fill_string(head_clang, max_clang), fill_string(head_xcode, max_xcode), fill_string(head_objc, max_objc)) wiki_file.write(s) s = '{}|{}|{}|\n'.format('-' * max_clang, '-' * max_xcode, '-' * max_objc) wiki_file.write(s) done_list = [] for entry in main_warnings_table: if entry.xcode.option == '': continue if entry.clang.option in done_list: continue done_list.append(entry.clang.option) if entry.objc: objc = 'yes' else: objc = 'no' s = '{}|{}|{}|\n'.format(fill_string(entry.clang.option, max_clang), fill_string(entry.xcode.option, max_xcode), fill_string(objc, max_objc)) wiki_file.write(s)
# Copyright (C) 2014 VA Linux Systems Japan K.K. # Copyright (C) 2014 YAMAMOTO Takashi <yamamoto at valinux co jp> # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. class OFPort(object): def __init__(self, port_name, ofport): self.port_name = port_name self.ofport = ofport @classmethod def from_ofp_port(cls, ofp_port): """Convert from ryu OFPPort.""" return cls(port_name=ofp_port.name, ofport=ofp_port.port_no) PORT_NAME_LEN = 14 PORT_NAME_PREFIXES = [ "tap", # common cases, including ovs_use_veth=True "qvo", # nova hybrid interface driver "qr-", # l3-agent INTERNAL_DEV_PREFIX (ovs_use_veth=False) "qg-", # l3-agent EXTERNAL_DEV_PREFIX (ovs_use_veth=False) ] def _is_neutron_port(name): """Return True if the port name looks like a neutron port.""" if len(name) != PORT_NAME_LEN: return False for pref in PORT_NAME_PREFIXES: if name.startswith(pref): return True return False def get_normalized_port_name(interface_id): """Convert from neutron device id (uuid) to "normalized" port name. This needs to be synced with ML2 plugin's _device_to_port_id(). An assumption: The switch uses an OS's interface name as the corresponding OpenFlow port name. NOTE(yamamoto): While it's true for Open vSwitch, it isn't necessarily true everywhere. For example, LINC uses something like "LogicalSwitch0-Port2". NOTE(yamamoto): The actual prefix might be different. For example, with the hybrid interface driver, it's "qvo". However, we always use "tap" prefix throughout the agent and plugin for simplicity. Some care should be taken when talking to the switch. """ return ("tap" + interface_id)[0:PORT_NAME_LEN] def _normalize_port_name(name): """Normalize port name. See comments in _get_ofport_name. """ for pref in PORT_NAME_PREFIXES: if name.startswith(pref): return "tap" + name[len(pref):] return name class Port(OFPort): def __init__(self, *args, **kwargs): super(Port, self).__init__(*args, **kwargs) self.vif_mac = None def is_neutron_port(self): """Return True if the port looks like a neutron port.""" return _is_neutron_port(self.port_name) def normalized_port_name(self): return _normalize_port_name(self.port_name)
class Ofport(object): def __init__(self, port_name, ofport): self.port_name = port_name self.ofport = ofport @classmethod def from_ofp_port(cls, ofp_port): """Convert from ryu OFPPort.""" return cls(port_name=ofp_port.name, ofport=ofp_port.port_no) port_name_len = 14 port_name_prefixes = ['tap', 'qvo', 'qr-', 'qg-'] def _is_neutron_port(name): """Return True if the port name looks like a neutron port.""" if len(name) != PORT_NAME_LEN: return False for pref in PORT_NAME_PREFIXES: if name.startswith(pref): return True return False def get_normalized_port_name(interface_id): """Convert from neutron device id (uuid) to "normalized" port name. This needs to be synced with ML2 plugin's _device_to_port_id(). An assumption: The switch uses an OS's interface name as the corresponding OpenFlow port name. NOTE(yamamoto): While it's true for Open vSwitch, it isn't necessarily true everywhere. For example, LINC uses something like "LogicalSwitch0-Port2". NOTE(yamamoto): The actual prefix might be different. For example, with the hybrid interface driver, it's "qvo". However, we always use "tap" prefix throughout the agent and plugin for simplicity. Some care should be taken when talking to the switch. """ return ('tap' + interface_id)[0:PORT_NAME_LEN] def _normalize_port_name(name): """Normalize port name. See comments in _get_ofport_name. """ for pref in PORT_NAME_PREFIXES: if name.startswith(pref): return 'tap' + name[len(pref):] return name class Port(OFPort): def __init__(self, *args, **kwargs): super(Port, self).__init__(*args, **kwargs) self.vif_mac = None def is_neutron_port(self): """Return True if the port looks like a neutron port.""" return _is_neutron_port(self.port_name) def normalized_port_name(self): return _normalize_port_name(self.port_name)
ADDED_KARMA_TO_MEMBER = "Gave {} karma to {}, their karma is now at {}." REMOVED_KARMA_FROM_MEMBER = "Removed {} karma from {}, their karma is now at {}." LIST_KARMA_OWN = "You currently have {} karma." LIST_KARMA_OBJECT = "\"{}\" currently has {} karma." LIST_KARMA_MEMBER = "{} currently has {} karma." KARMA_TOP_START = "Top karma in server:\n" KARMA_TOP_FORMAT = "{}. {} \\| {}\n"
added_karma_to_member = 'Gave {} karma to {}, their karma is now at {}.' removed_karma_from_member = 'Removed {} karma from {}, their karma is now at {}.' list_karma_own = 'You currently have {} karma.' list_karma_object = '"{}" currently has {} karma.' list_karma_member = '{} currently has {} karma.' karma_top_start = 'Top karma in server:\n' karma_top_format = '{}. {} \\| {}\n'
# simple test function that uses python 3 features (e.g., f-strings) # see https://github.com/localstack/localstack/issues/264 def handler(event, context): # the following line is Python 3.6+ specific msg = f"Successfully processed {event}" # noqa This code is Python 3.6+ only return event
def handler(event, context): msg = f'Successfully processed {event}' return event
def decimal_to_binary_fraction(x=0.5): """ Input: x, a float between 0 and 1 Returns binary representation of x """ p = 0 while ((2 ** p) * x) % 1 != 0: # print('Remainder = ' + str((2**p)*x - int((2**p)*x))) p += 1 num = int(x * (2 ** p)) result = '' if num == 0: result = '0' while num > 0: result = str(num % 2) + result num //= 2 for i in range(p - len(result)): result = '0' + result result = result[0:-p] + '.' + result[-p:] return result # If there is no integer p such that x*(2**p) is a whole number, then internal # representation is always an approximation # Suggest that testing equality of floats is not exact: Use abs(x-y) < some # small number, rather than x == y # Why does print(0.1) return 0.1, if not exact? # Because Python designers set it up this way to automatically round
def decimal_to_binary_fraction(x=0.5): """ Input: x, a float between 0 and 1 Returns binary representation of x """ p = 0 while 2 ** p * x % 1 != 0: p += 1 num = int(x * 2 ** p) result = '' if num == 0: result = '0' while num > 0: result = str(num % 2) + result num //= 2 for i in range(p - len(result)): result = '0' + result result = result[0:-p] + '.' + result[-p:] return result
def deco1(func): print("before myfunc() called.") func() print("after myfunc() called.") def myfunc(): print("myfunc() called.") deco1(myfunc)
def deco1(func): print('before myfunc() called.') func() print('after myfunc() called.') def myfunc(): print('myfunc() called.') deco1(myfunc)
class ShoppingCart(object): def __init__(self): self.total = 0 self.items = dict() def add_item(self, item_name, quantity, price): if item_name != None and quantity >= 1: self.items.update({item_name: quantity}) if quantity and price >= 1: self.total += (quantity * price) def remove_item(self, item_name, quantity, price): if item_name in self.items: if quantity < self.items[item_name] and quantity > 0: self.items[item_name] -= quantity self.total -= price*quantity def checkout(self, cash_paid): balance = 0 if cash_paid < self.total: return "Cash paid not enough" balance = cash_paid - self.total return balance class Shop(ShoppingCart): def __init__(self): self.quantity = 100 def remove_item(self): self.quantity -= 1
class Shoppingcart(object): def __init__(self): self.total = 0 self.items = dict() def add_item(self, item_name, quantity, price): if item_name != None and quantity >= 1: self.items.update({item_name: quantity}) if quantity and price >= 1: self.total += quantity * price def remove_item(self, item_name, quantity, price): if item_name in self.items: if quantity < self.items[item_name] and quantity > 0: self.items[item_name] -= quantity self.total -= price * quantity def checkout(self, cash_paid): balance = 0 if cash_paid < self.total: return 'Cash paid not enough' balance = cash_paid - self.total return balance class Shop(ShoppingCart): def __init__(self): self.quantity = 100 def remove_item(self): self.quantity -= 1
def solution(bridge_length, weight, truck_weights): answer = 0 # { weight, time } wait = truck_weights[:] bridge = [] passed = 0 currWeight = 0 while True: if passed == len(truck_weights) and len(wait) == 0: return answer answer += 1 # sth needs to be passed if bridge: if bridge[0]['t'] + bridge_length == answer: front = bridge.pop(0) currWeight -= front['w'] passed += 1 # add new truck if wait: if currWeight + wait[0] <= weight: bridge.append({ 'w' : wait[0], 't' : answer }) currWeight += wait[0] wait.pop(0) # print(solution(2, 10, [7, 4, 5, 6])) print(solution(100, 100, [10]))
def solution(bridge_length, weight, truck_weights): answer = 0 wait = truck_weights[:] bridge = [] passed = 0 curr_weight = 0 while True: if passed == len(truck_weights) and len(wait) == 0: return answer answer += 1 if bridge: if bridge[0]['t'] + bridge_length == answer: front = bridge.pop(0) curr_weight -= front['w'] passed += 1 if wait: if currWeight + wait[0] <= weight: bridge.append({'w': wait[0], 't': answer}) curr_weight += wait[0] wait.pop(0) print(solution(100, 100, [10]))
"""Holds the device gemoetry parameters (Table 5), taken from Wu et al., >> A Predictive 3-D Source/Drain Resistance Compact Model and the Impact on 7 nm and Scaled FinFets<<, 2020, with interpolation for 4nm. 16nm is taken from PTM HP. """ node_names = [16, 7, 5, 4, 3] GP = [64, 56, 48, 44, 41] FP = [40, 30, 28, 24, 22] GL = [20, 18, 16, 15, 14] FH = [26, 35, 45, 50, 55] FW = [12, 6.5, 6, 5.5, 5.5] vdd = [0.85, 0.75, 0.7, 0.65, 0.65]
"""Holds the device gemoetry parameters (Table 5), taken from Wu et al., >> A Predictive 3-D Source/Drain Resistance Compact Model and the Impact on 7 nm and Scaled FinFets<<, 2020, with interpolation for 4nm. 16nm is taken from PTM HP. """ node_names = [16, 7, 5, 4, 3] gp = [64, 56, 48, 44, 41] fp = [40, 30, 28, 24, 22] gl = [20, 18, 16, 15, 14] fh = [26, 35, 45, 50, 55] fw = [12, 6.5, 6, 5.5, 5.5] vdd = [0.85, 0.75, 0.7, 0.65, 0.65]
def check_difference(): pass def update_benchmark(): pass
def check_difference(): pass def update_benchmark(): pass
# while True: # # ejecuta esto # print("Hola") real = 7 print("Entre un numero entre el 1 y el 10") guess = int(input()) # =/= while guess != real: print("Ese no es el numero") print("Entre un numero entre el 1 y el 10") guess = int(input()) # el resto print("Yay! Lo sacastes!")
real = 7 print('Entre un numero entre el 1 y el 10') guess = int(input()) while guess != real: print('Ese no es el numero') print('Entre un numero entre el 1 y el 10') guess = int(input()) print('Yay! Lo sacastes!')
class Foo: def bar(self): return "a" if __name__ == "__main__": f = Foo() b = f.bar() print(b)
class Foo: def bar(self): return 'a' if __name__ == '__main__': f = foo() b = f.bar() print(b)
''' Speed: 95.97% Memory: 24.96% Time complexity: O(n) Space complexity: O(n) ''' class Solution(object): def longestValidParentheses(self, s): ans=0 stack=[-1] for i in range(len(s)): if(s[i]=='('): stack.append(i) else: stack.pop() if(len(stack)==0): stack.append(i) else: ans=max(ans,i-stack[-1]) return ans
""" Speed: 95.97% Memory: 24.96% Time complexity: O(n) Space complexity: O(n) """ class Solution(object): def longest_valid_parentheses(self, s): ans = 0 stack = [-1] for i in range(len(s)): if s[i] == '(': stack.append(i) else: stack.pop() if len(stack) == 0: stack.append(i) else: ans = max(ans, i - stack[-1]) return ans
def greet(): print("Hi") def greet_again(message): print(message) def greet_again_with_type(message): print(type(message)) print(message) greet() greet_again("Hello Again") greet_again_with_type("One Last Time") greet_again_with_type(1234) # multiple types def multiple_types(x): if x < 0: return -1 else: return "Returning Hello" print(multiple_types(-2)) print(multiple_types(10)) # variable arguments def var_arguments(*args): # args will be tuples containing all the values for value in args: print(value) var_arguments(1, 2, 3) a = [1, 2, 3] var_arguments(a) var_arguments(*a) # expanding def key_arg(**kwargs): for key,value in kwargs.items(): print(key, value) v b = {"first" : "python", "second" : "python again"} key_arg(b)
def greet(): print('Hi') def greet_again(message): print(message) def greet_again_with_type(message): print(type(message)) print(message) greet() greet_again('Hello Again') greet_again_with_type('One Last Time') greet_again_with_type(1234) def multiple_types(x): if x < 0: return -1 else: return 'Returning Hello' print(multiple_types(-2)) print(multiple_types(10)) def var_arguments(*args): for value in args: print(value) var_arguments(1, 2, 3) a = [1, 2, 3] var_arguments(a) var_arguments(*a) def key_arg(**kwargs): for (key, value) in kwargs.items(): print(key, value) v b = {'first': 'python', 'second': 'python again'} key_arg(b)
# Authentication & API Keys # Many APIs require an API key. Just as a real-world key allows you to access something, an API key grants you access to a particular API. Moreover, an API key identifies you to the API, which helps the API provider keep track of how their service is used and prevent unauthorized or malicious activity. # # Some APIs require authentication using a protocol called OAuth. We won't get into the details, but if you've ever been redirected to a page asking for permission to link an application with your account, you've probably used OAuth. # # API keys are often long alphanumeric strings. We've made one up in the editor to the right! (It won't actually work on anything, but when you receive your own API keys in future projects, they'll look a lot like this.) api_key = "string"
api_key = 'string'
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jun 18 08:40:11 2020 @author: krishan """ def funny_division2(anumber): try: if anumber == 13: raise ValueError("13 is an unlucky number") return 100 / anumber except (ZeroDivisionError, TypeError): return "Enter a number other than zero" def funny_division3(anumber): try: if anumber == 13: raise ValueError("13 is an unlucky number") return 100 / anumber except ZeroDivisionError: return "Enter a number other than zero" except TypeError: return "Enter a numerical value" except ValueError as e: print("The exception arguments were",e.args) #raise for val in (0, "hello", 50.0, 13): print(f"Testing {val}:", funny_division3(val))
""" Created on Thu Jun 18 08:40:11 2020 @author: krishan """ def funny_division2(anumber): try: if anumber == 13: raise value_error('13 is an unlucky number') return 100 / anumber except (ZeroDivisionError, TypeError): return 'Enter a number other than zero' def funny_division3(anumber): try: if anumber == 13: raise value_error('13 is an unlucky number') return 100 / anumber except ZeroDivisionError: return 'Enter a number other than zero' except TypeError: return 'Enter a numerical value' except ValueError as e: print('The exception arguments were', e.args) for val in (0, 'hello', 50.0, 13): print(f'Testing {val}:', funny_division3(val))
class BackupUnit(object): def __init__(self, name, password=None, email=None): """ BackupUnit class initializer. :param name: A name of that resource (only alphanumeric characters are acceptable)" :type name: ``str`` :param password: The password associated to that resource. :type password: ``str`` :param email: The email associated with the backup unit. Bear in mind that this email does not be the same email as of the user. :type email: ``str`` """ self.name = name self.password = password self.email = email def __repr__(self): return ('<BackupUnit: name=%s, password=%s, email=%s>' % (self.name, str(self.password), self.email))
class Backupunit(object): def __init__(self, name, password=None, email=None): """ BackupUnit class initializer. :param name: A name of that resource (only alphanumeric characters are acceptable)" :type name: ``str`` :param password: The password associated to that resource. :type password: ``str`` :param email: The email associated with the backup unit. Bear in mind that this email does not be the same email as of the user. :type email: ``str`` """ self.name = name self.password = password self.email = email def __repr__(self): return '<BackupUnit: name=%s, password=%s, email=%s>' % (self.name, str(self.password), self.email)