content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# First, we collect a url from users:
url = input("Enter the URL you'd like to clean up:\n")
remove_query_strings = input("Should we remove query strings (y/n/yes/no)?\n")
if remove_query_strings == "y" or remove_query_strings == "yes":
remove_query_strings = True
else:
remove_query_strings = False
# Remove query strings
if remove_query_strings:
url = url.split("?")[0]
# Extend URL
if url[:3] == "www":
# Example: "www.andover.edu"
url = "https://" + url
elif url[:4] != "http":
# Example: "andover.edu"
url = "https://www." + url
print("\nThe result is: {}".format(url))
"""
Good things to make sure work:
* andover.edu -> https://www.andover.edu
* www.andover.edu -> https://www.andover.edu
* wikipedia.com -> https://www.wikipedia.com (Starts with a w)
* https://www.youtube.com/watch?v=e4BdyyVEJks -> https://www.youtube.com/watch (strip query strings)
"""
| url = input("Enter the URL you'd like to clean up:\n")
remove_query_strings = input('Should we remove query strings (y/n/yes/no)?\n')
if remove_query_strings == 'y' or remove_query_strings == 'yes':
remove_query_strings = True
else:
remove_query_strings = False
if remove_query_strings:
url = url.split('?')[0]
if url[:3] == 'www':
url = 'https://' + url
elif url[:4] != 'http':
url = 'https://www.' + url
print('\nThe result is: {}'.format(url))
'\nGood things to make sure work:\n* andover.edu -> https://www.andover.edu\n* www.andover.edu -> https://www.andover.edu\n* wikipedia.com -> https://www.wikipedia.com (Starts with a w)\n* https://www.youtube.com/watch?v=e4BdyyVEJks -> https://www.youtube.com/watch (strip query strings)\n' |
envs = [
'dm.acrobot.swingup',
'dm.cheetah.run',
'dm.finger.turn_hard',
'dm.walker.run',
'dm.quadruped.run',
'dm.quadruped.walk',
'dm.hopper.hop',
]
times = [
1e6, 1e6, 1e6, 1e6, 2e6, 2e6, 1e6
]
sigma = 0.001
f_dims = [1024, 512, 256, 128, 64]
lr = '1e-4'
count = 0
for i, env in enumerate(envs):
commands = []
base_str = f"python main.py --policy PytorchSAC --env {env} --start_timesteps 5000 --hidden_dim 1024 --batch_size 1024 --n_hidden 2 --lr {lr}"
max_timesteps = int(times[i])
# LFF
for fourier_dim in f_dims:
for seed in [10, 20, 30]:
commands.append(base_str + f' --network_class FourierMLP --concatenate_fourier --train_B'
f' --sigma {sigma} --fourier_dim {fourier_dim} --seed {seed}')
for command in commands:
count += 1
print(f'CUDA_VISIBLE_DEVICES=0 taskset -c a-b {command} --max_timesteps {max_timesteps} &')
if count % 10 == 0:
print(count)
print(count)
# ablation_envs = []
| envs = ['dm.acrobot.swingup', 'dm.cheetah.run', 'dm.finger.turn_hard', 'dm.walker.run', 'dm.quadruped.run', 'dm.quadruped.walk', 'dm.hopper.hop']
times = [1000000.0, 1000000.0, 1000000.0, 1000000.0, 2000000.0, 2000000.0, 1000000.0]
sigma = 0.001
f_dims = [1024, 512, 256, 128, 64]
lr = '1e-4'
count = 0
for (i, env) in enumerate(envs):
commands = []
base_str = f'python main.py --policy PytorchSAC --env {env} --start_timesteps 5000 --hidden_dim 1024 --batch_size 1024 --n_hidden 2 --lr {lr}'
max_timesteps = int(times[i])
for fourier_dim in f_dims:
for seed in [10, 20, 30]:
commands.append(base_str + f' --network_class FourierMLP --concatenate_fourier --train_B --sigma {sigma} --fourier_dim {fourier_dim} --seed {seed}')
for command in commands:
count += 1
print(f'CUDA_VISIBLE_DEVICES=0 taskset -c a-b {command} --max_timesteps {max_timesteps} &')
if count % 10 == 0:
print(count)
print(count) |
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 16 15:39:58 2022
@author: jced0001
"""
class Bias:
"""
Nanonis Bias Module
"""
def __init__(self, nanonisTCP):
self.nanonisTCP = nanonisTCP
def Set(self, bias):
"""
Set the tip voltage bias
Parameters
bias (float32): bias (V)
"""
## Make Header
hex_rep = self.nanonisTCP.make_header('Bias.Set', body_size=4)
## Arguments
hex_rep += self.nanonisTCP.float32_to_hex(bias) # bias (float 32)
self.nanonisTCP.send_command(hex_rep)
self.nanonisTCP.receive_response(0)
def Get(self):
"""
Returns the tip bias
Returns
bias (float32): bias (V)
"""
## Make Header
hex_rep = self.nanonisTCP.make_header('Bias.Get', body_size=0)
self.nanonisTCP.send_command(hex_rep)
response = self.nanonisTCP.receive_response(4)
bias = self.nanonisTCP.hex_to_float32(response[0:4])
return bias
def RangeSet(self,bias_range_index):
"""
Sets the range of the Bias voltage, if different ranges are available
Parameters
bias_range_index : is the index out of the list of ranges which can be
retrieved by the function Bias.RangeGet
"""
## Make Header
hex_rep = self.nanonisTCP.make_header('Bias.RangeSet', body_size=2)
## Arguments
hex_rep += self.nanonisTCP.to_hex(bias_range_index,2) # uint16
self.nanonisTCP.send_command(hex_rep)
# Receive response (check errors)
self.nanonisTCP.receive_response(0)
def RangeGet(self):
"""
Returns the selectable ranges of bias voltage and the index of the
selected one
Returns
bias_ranges : returns an array of selectable bias ranges (if your
system supports it switching. see bias module doco)
bias_range_index : is the index out of the list of bias ranges
"""
## Make Header
hex_rep = self.nanonisTCP.make_header('Bias.RangeGet', body_size=0)
self.nanonisTCP.send_command(hex_rep)
# Receive response
response = self.nanonisTCP.receive_response() # Not checking for errors because return arguments are variable size
# bias_ranges_size = self.nanonisTCP.hex_to_int32(response[0:4]) # Not needed.
number_of_ranges = self.nanonisTCP.hex_to_int32(response[4:8])
bias_ranges = []
idx = 8
for i in range(number_of_ranges):
size = self.nanonisTCP.hex_to_uint32(response[idx:idx+4])
idx += 4
bias_ranges.append(response[idx:idx+size].decode())
idx += size
bias_range_index = self.nanonisTCP.hex_to_uint16(response[idx:idx+2])
return [bias_ranges, bias_range_index]
def CalibrSet(self,calibration,offset):
"""
Set the calibration and offset of bias voltage
Parameters
----------
calibration : calibration
offset : offset
"""
## Make Header
hex_rep = self.nanonisTCP.make_header('Bias.CalibrSet', body_size=8)
## Arguments
hex_rep += self.nanonisTCP.float32_to_hex(calibration)
hex_rep += self.nanonisTCP.float32_to_hex(offset)
self.nanonisTCP.send_command(hex_rep)
# Receive response (check errors)
self.nanonisTCP.receive_response(0)
def CalibrGet(self):
"""
Gets the calibration and offset of bias voltage
Returns
-------
calibration : calibration
offset : offset
"""
## Make Header
hex_rep = self.nanonisTCP.make_header('Bias.CalibrGet', body_size=0)
self.nanonisTCP.send_command(hex_rep)
# Receive response
response = self.nanonisTCP.receive_response(8)
calibration = self.nanonisTCP.hex_to_float32(response[0:4])
offset = self.nanonisTCP.hex_to_float32(response[4:8])
return [calibration,offset]
def Pulse(self,bias_pulse_width,bias_value,z_hold=0,rel_abs=0,wait_until_done=False):
"""
Generates one bias pulse
Parameters
----------
bias_pulse_width : is the pulse duration in seconds
bias_value : is the bias value applied during the pulse
z_hold : sets whether the controller is set to hold
(deactivated) during the pulse.
0: no change (leave setting as is in nanonis)
1: hold
2: don't hold
rel_abs : sets whether the bias value argument is an absolute
value or relative to the current bias
0: no change (leave setting as is in nanonis)
1: hold
2: absolute
wait_until_done : 0: don't wait
1: wait until function is done
"""
## Make Header
hex_rep = self.nanonisTCP.make_header('Bias.Pulse', body_size=16)
## Arguments
hex_rep += self.nanonisTCP.to_hex(wait_until_done,4)
hex_rep += self.nanonisTCP.float32_to_hex(bias_pulse_width)
hex_rep += self.nanonisTCP.float32_to_hex(bias_value)
hex_rep += self.nanonisTCP.to_hex(z_hold,2)
hex_rep += self.nanonisTCP.to_hex(rel_abs,2)
self.nanonisTCP.send_command(hex_rep)
# Receive response (check errors)
self.nanonisTCP.receive_response(0) | """
Created on Sat Apr 16 15:39:58 2022
@author: jced0001
"""
class Bias:
"""
Nanonis Bias Module
"""
def __init__(self, nanonisTCP):
self.nanonisTCP = nanonisTCP
def set(self, bias):
"""
Set the tip voltage bias
Parameters
bias (float32): bias (V)
"""
hex_rep = self.nanonisTCP.make_header('Bias.Set', body_size=4)
hex_rep += self.nanonisTCP.float32_to_hex(bias)
self.nanonisTCP.send_command(hex_rep)
self.nanonisTCP.receive_response(0)
def get(self):
"""
Returns the tip bias
Returns
bias (float32): bias (V)
"""
hex_rep = self.nanonisTCP.make_header('Bias.Get', body_size=0)
self.nanonisTCP.send_command(hex_rep)
response = self.nanonisTCP.receive_response(4)
bias = self.nanonisTCP.hex_to_float32(response[0:4])
return bias
def range_set(self, bias_range_index):
"""
Sets the range of the Bias voltage, if different ranges are available
Parameters
bias_range_index : is the index out of the list of ranges which can be
retrieved by the function Bias.RangeGet
"""
hex_rep = self.nanonisTCP.make_header('Bias.RangeSet', body_size=2)
hex_rep += self.nanonisTCP.to_hex(bias_range_index, 2)
self.nanonisTCP.send_command(hex_rep)
self.nanonisTCP.receive_response(0)
def range_get(self):
"""
Returns the selectable ranges of bias voltage and the index of the
selected one
Returns
bias_ranges : returns an array of selectable bias ranges (if your
system supports it switching. see bias module doco)
bias_range_index : is the index out of the list of bias ranges
"""
hex_rep = self.nanonisTCP.make_header('Bias.RangeGet', body_size=0)
self.nanonisTCP.send_command(hex_rep)
response = self.nanonisTCP.receive_response()
number_of_ranges = self.nanonisTCP.hex_to_int32(response[4:8])
bias_ranges = []
idx = 8
for i in range(number_of_ranges):
size = self.nanonisTCP.hex_to_uint32(response[idx:idx + 4])
idx += 4
bias_ranges.append(response[idx:idx + size].decode())
idx += size
bias_range_index = self.nanonisTCP.hex_to_uint16(response[idx:idx + 2])
return [bias_ranges, bias_range_index]
def calibr_set(self, calibration, offset):
"""
Set the calibration and offset of bias voltage
Parameters
----------
calibration : calibration
offset : offset
"""
hex_rep = self.nanonisTCP.make_header('Bias.CalibrSet', body_size=8)
hex_rep += self.nanonisTCP.float32_to_hex(calibration)
hex_rep += self.nanonisTCP.float32_to_hex(offset)
self.nanonisTCP.send_command(hex_rep)
self.nanonisTCP.receive_response(0)
def calibr_get(self):
"""
Gets the calibration and offset of bias voltage
Returns
-------
calibration : calibration
offset : offset
"""
hex_rep = self.nanonisTCP.make_header('Bias.CalibrGet', body_size=0)
self.nanonisTCP.send_command(hex_rep)
response = self.nanonisTCP.receive_response(8)
calibration = self.nanonisTCP.hex_to_float32(response[0:4])
offset = self.nanonisTCP.hex_to_float32(response[4:8])
return [calibration, offset]
def pulse(self, bias_pulse_width, bias_value, z_hold=0, rel_abs=0, wait_until_done=False):
"""
Generates one bias pulse
Parameters
----------
bias_pulse_width : is the pulse duration in seconds
bias_value : is the bias value applied during the pulse
z_hold : sets whether the controller is set to hold
(deactivated) during the pulse.
0: no change (leave setting as is in nanonis)
1: hold
2: don't hold
rel_abs : sets whether the bias value argument is an absolute
value or relative to the current bias
0: no change (leave setting as is in nanonis)
1: hold
2: absolute
wait_until_done : 0: don't wait
1: wait until function is done
"""
hex_rep = self.nanonisTCP.make_header('Bias.Pulse', body_size=16)
hex_rep += self.nanonisTCP.to_hex(wait_until_done, 4)
hex_rep += self.nanonisTCP.float32_to_hex(bias_pulse_width)
hex_rep += self.nanonisTCP.float32_to_hex(bias_value)
hex_rep += self.nanonisTCP.to_hex(z_hold, 2)
hex_rep += self.nanonisTCP.to_hex(rel_abs, 2)
self.nanonisTCP.send_command(hex_rep)
self.nanonisTCP.receive_response(0) |
def foo():
return "foo 1"
def bar():
return "bar 1"
if __name__ == "__main__":
print(foo())
print(bar()) | def foo():
return 'foo 1'
def bar():
return 'bar 1'
if __name__ == '__main__':
print(foo())
print(bar()) |
class Comparable(object):
"""
https://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/
"""
def _compare(self, other, method):
try:
if type(other) is type(self):
return method(self._cmpkey, other._cmpkey)
return NotImplemented
except (AttributeError, TypeError):
return NotImplemented
def __lt__(self, other):
return self._compare(other, lambda s, o: s < o)
def __le__(self, other):
return self._compare(other, lambda s, o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s, o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s, o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s, o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s, o: s != o)
def __hash__(self):
try:
return hash(self._cmpkey)
except (AttributeError, TypeError):
return NotImplemented
| class Comparable(object):
"""
https://regebro.wordpress.com/2010/12/13/python-implementing-rich-comparison-the-correct-way/
"""
def _compare(self, other, method):
try:
if type(other) is type(self):
return method(self._cmpkey, other._cmpkey)
return NotImplemented
except (AttributeError, TypeError):
return NotImplemented
def __lt__(self, other):
return self._compare(other, lambda s, o: s < o)
def __le__(self, other):
return self._compare(other, lambda s, o: s <= o)
def __eq__(self, other):
return self._compare(other, lambda s, o: s == o)
def __ge__(self, other):
return self._compare(other, lambda s, o: s >= o)
def __gt__(self, other):
return self._compare(other, lambda s, o: s > o)
def __ne__(self, other):
return self._compare(other, lambda s, o: s != o)
def __hash__(self):
try:
return hash(self._cmpkey)
except (AttributeError, TypeError):
return NotImplemented |
def find_node_in_list(name, l):
for i in l:
if i.name == name:
return i
return False
def remove_bag(string):
string = string.replace('bags', '') if 'bags' in string else string
string = string.replace('bag', '') if 'bag' in string else string
return string.strip()
class LinkedList:
def __init__(self, name):
self.name = name
self.next = {}
def add_next(self, next_node, amount):
self.next[next_node] = amount
def contains(self, name):
if find_node_in_list(name, self.next):
return True
for child in self.next:
if child.contains(name):
return True
return False
def cost(self):
return self._cost() - 1
def _cost(self):
cost = 1
for child in self.next:
cost += self.next[child] * child._cost()
return cost
def __repr__(self):
return f'<LinkedListNode:{self.name}>'
with open('day-07/input.txt', 'r') as file:
puzzle_input_raw = [i.strip() for i in file.readlines()]
puzzle_input = {}
for entry in puzzle_input_raw:
parent, other = entry.split(' contain ')
parent = remove_bag(parent)
puzzle_input[parent] = {}
for child in other.split(', '):
if child == 'no other bags.':
continue
amount, name = child.replace('.', '').split(' ', 1)
name = remove_bag(name)
puzzle_input[parent][name] = int(amount)
puzzle_objects = []
for bag in puzzle_input:
node = LinkedList(bag)
puzzle_objects.append(node)
for bag in puzzle_input:
parent = find_node_in_list(bag, puzzle_objects)
for i in puzzle_input[bag]:
child = find_node_in_list(i, puzzle_objects)
parent.add_next(child, puzzle_input[bag][i])
def part_1(puzzle_input):
return sum([bag.contains('shiny gold') for bag in puzzle_input])
def part_2(puzzle_input):
bag = find_node_in_list('shiny gold', puzzle_input)
return bag.cost()
print(part_1(puzzle_objects))
print(part_2(puzzle_objects))
| def find_node_in_list(name, l):
for i in l:
if i.name == name:
return i
return False
def remove_bag(string):
string = string.replace('bags', '') if 'bags' in string else string
string = string.replace('bag', '') if 'bag' in string else string
return string.strip()
class Linkedlist:
def __init__(self, name):
self.name = name
self.next = {}
def add_next(self, next_node, amount):
self.next[next_node] = amount
def contains(self, name):
if find_node_in_list(name, self.next):
return True
for child in self.next:
if child.contains(name):
return True
return False
def cost(self):
return self._cost() - 1
def _cost(self):
cost = 1
for child in self.next:
cost += self.next[child] * child._cost()
return cost
def __repr__(self):
return f'<LinkedListNode:{self.name}>'
with open('day-07/input.txt', 'r') as file:
puzzle_input_raw = [i.strip() for i in file.readlines()]
puzzle_input = {}
for entry in puzzle_input_raw:
(parent, other) = entry.split(' contain ')
parent = remove_bag(parent)
puzzle_input[parent] = {}
for child in other.split(', '):
if child == 'no other bags.':
continue
(amount, name) = child.replace('.', '').split(' ', 1)
name = remove_bag(name)
puzzle_input[parent][name] = int(amount)
puzzle_objects = []
for bag in puzzle_input:
node = linked_list(bag)
puzzle_objects.append(node)
for bag in puzzle_input:
parent = find_node_in_list(bag, puzzle_objects)
for i in puzzle_input[bag]:
child = find_node_in_list(i, puzzle_objects)
parent.add_next(child, puzzle_input[bag][i])
def part_1(puzzle_input):
return sum([bag.contains('shiny gold') for bag in puzzle_input])
def part_2(puzzle_input):
bag = find_node_in_list('shiny gold', puzzle_input)
return bag.cost()
print(part_1(puzzle_objects))
print(part_2(puzzle_objects)) |
n = int(input())
ans = 0
for a in range(10 ** 5):
if a ** 2 <= n:
ans = a
else:
break
print(ans) | n = int(input())
ans = 0
for a in range(10 ** 5):
if a ** 2 <= n:
ans = a
else:
break
print(ans) |
dict = {
'apples': 7,
'oranges': 12,
'grapes': 5
}
# to get an item from a dictionary
apples = dict.get('apples') # option 1
apples1 = dict['apples'] # option 2
print(apples1)
# add items to the dict
dict['banana'] = 4
print(dict)
# remove items from the dict
dict.popitem() # removes last item from dict
print(dict)
dict.pop('oranges')
print(dict)
| dict = {'apples': 7, 'oranges': 12, 'grapes': 5}
apples = dict.get('apples')
apples1 = dict['apples']
print(apples1)
dict['banana'] = 4
print(dict)
dict.popitem()
print(dict)
dict.pop('oranges')
print(dict) |
A, B = map(int, input().split())
while A != 0 and B != 0:
X = set(map(int, input().split()))
Y = set(map(int, input().split()))
print(min(len(X-Y), len(Y-X)))
A, B = map(int, input().split())
| (a, b) = map(int, input().split())
while A != 0 and B != 0:
x = set(map(int, input().split()))
y = set(map(int, input().split()))
print(min(len(X - Y), len(Y - X)))
(a, b) = map(int, input().split()) |
# 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.
{
'targets': [
{
'target_name': 'array_data_model',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:event_target',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'autocomplete_list',
'dependencies': [
'list',
'list_single_selection_model',
'position_util',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'command',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:ui',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'context_menu_button',
'dependencies': [
'menu_button',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'context_menu_handler',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:event_target',
'../compiled_resources2.gyp:ui',
'menu',
'menu_button',
'position_util',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'dialogs',
'dependencies': [
'../../compiled_resources2.gyp:cr',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'drag_wrapper',
'dependencies': [
'../../compiled_resources2.gyp:assert',
'../../compiled_resources2.gyp:cr',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'focus_grid',
'dependencies': [
'../../compiled_resources2.gyp:assert',
'../../compiled_resources2.gyp:cr',
'../../compiled_resources2.gyp:event_tracker',
'focus_row',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'focus_manager',
'dependencies': ['../../compiled_resources2.gyp:cr'],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'focus_outline_manager',
'dependencies': ['../../compiled_resources2.gyp:cr'],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'focus_row',
'dependencies': [
'../../compiled_resources2.gyp:assert',
'../../compiled_resources2.gyp:cr',
'../../compiled_resources2.gyp:event_tracker',
'../../compiled_resources2.gyp:util',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'focus_without_ink',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:ui',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'grid',
'dependencies': [
'list',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'list',
'dependencies': [
'array_data_model',
'list_item',
'list_selection_controller',
'list_selection_model',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'list_item',
'dependencies': [
'../../compiled_resources2.gyp:cr',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'list_selection_controller',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'list_selection_model',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'list_selection_model',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:event_target',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'list_single_selection_model',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:event_target',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'menu_button',
'dependencies': [
'../../compiled_resources2.gyp:assert',
'../../compiled_resources2.gyp:cr',
'../../compiled_resources2.gyp:event_tracker',
'../compiled_resources2.gyp:ui',
'menu',
'menu_item',
'position_util',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'menu_item',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../../compiled_resources2.gyp:load_time_data',
'../compiled_resources2.gyp:ui',
'command',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'menu',
'dependencies': [
'../../compiled_resources2.gyp:assert',
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:ui',
'menu_item',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'node_utils',
'dependencies': [
'../../compiled_resources2.gyp:cr',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'overlay',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../../compiled_resources2.gyp:util',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'position_util',
'dependencies': [
'../../compiled_resources2.gyp:cr',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'splitter',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../compiled_resources2.gyp:ui',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'table',
'dependencies': [
'list',
'list_single_selection_model',
'table/compiled_resources2.gyp:table_column_model',
'table/compiled_resources2.gyp:table_header',
'table/compiled_resources2.gyp:table_list',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
{
'target_name': 'tree',
'dependencies': [
'../../compiled_resources2.gyp:cr',
'../../compiled_resources2.gyp:util',
'../compiled_resources2.gyp:ui',
],
'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi'],
},
],
}
| {'targets': [{'target_name': 'array_data_model', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:event_target'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'autocomplete_list', 'dependencies': ['list', 'list_single_selection_model', 'position_util'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'command', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:ui'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'context_menu_button', 'dependencies': ['menu_button'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'context_menu_handler', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:event_target', '../compiled_resources2.gyp:ui', 'menu', 'menu_button', 'position_util'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'dialogs', 'dependencies': ['../../compiled_resources2.gyp:cr'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'drag_wrapper', 'dependencies': ['../../compiled_resources2.gyp:assert', '../../compiled_resources2.gyp:cr'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'focus_grid', 'dependencies': ['../../compiled_resources2.gyp:assert', '../../compiled_resources2.gyp:cr', '../../compiled_resources2.gyp:event_tracker', 'focus_row'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'focus_manager', 'dependencies': ['../../compiled_resources2.gyp:cr'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'focus_outline_manager', 'dependencies': ['../../compiled_resources2.gyp:cr'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'focus_row', 'dependencies': ['../../compiled_resources2.gyp:assert', '../../compiled_resources2.gyp:cr', '../../compiled_resources2.gyp:event_tracker', '../../compiled_resources2.gyp:util'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'focus_without_ink', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:ui'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'grid', 'dependencies': ['list'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'list', 'dependencies': ['array_data_model', 'list_item', 'list_selection_controller', 'list_selection_model'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'list_item', 'dependencies': ['../../compiled_resources2.gyp:cr'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'list_selection_controller', 'dependencies': ['../../compiled_resources2.gyp:cr', 'list_selection_model'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'list_selection_model', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:event_target'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'list_single_selection_model', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:event_target'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'menu_button', 'dependencies': ['../../compiled_resources2.gyp:assert', '../../compiled_resources2.gyp:cr', '../../compiled_resources2.gyp:event_tracker', '../compiled_resources2.gyp:ui', 'menu', 'menu_item', 'position_util'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'menu_item', 'dependencies': ['../../compiled_resources2.gyp:cr', '../../compiled_resources2.gyp:load_time_data', '../compiled_resources2.gyp:ui', 'command'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'menu', 'dependencies': ['../../compiled_resources2.gyp:assert', '../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:ui', 'menu_item'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'node_utils', 'dependencies': ['../../compiled_resources2.gyp:cr'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'overlay', 'dependencies': ['../../compiled_resources2.gyp:cr', '../../compiled_resources2.gyp:util'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'position_util', 'dependencies': ['../../compiled_resources2.gyp:cr'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'splitter', 'dependencies': ['../../compiled_resources2.gyp:cr', '../compiled_resources2.gyp:ui'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'table', 'dependencies': ['list', 'list_single_selection_model', 'table/compiled_resources2.gyp:table_column_model', 'table/compiled_resources2.gyp:table_header', 'table/compiled_resources2.gyp:table_list'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}, {'target_name': 'tree', 'dependencies': ['../../compiled_resources2.gyp:cr', '../../compiled_resources2.gyp:util', '../compiled_resources2.gyp:ui'], 'includes': ['../../../../../../third_party/closure_compiler/compile_js2.gypi']}]} |
class MutualExclusionRule(object):
"""Mutual exclusion rules indicate that a group of directives
probably aren't going to show up in the same date string.
('%H','%I') would be an example of mutually-exclusive directives.
MutualExclusionRule objects that are elements in the format_rules
attribute of DsOptions objects are evaluated during parsing.
"""
def __init__(self, directives, pos_score=0, neg_score=0):
"""Constructs a MutualExclusionRule object.
Positive reinforcement: The highest-scoring instance of any of the
specified possibilities is found and the scores for that same
possibility at any token where it's present is affected.
Negative reinforcement: The highest-scoring instance of any of the
specified possibilities is found and the scores for all the other
specified possibilities at any token where they're present are
affected.
Returns the MutualExclusionRule object.
:param directives: A set of directives that the rule applies to,
like ('%H','%I').
:param pos_score: (optional) Increment the score of possibilities
matching the "Positive reinforcement" condition by this much.
Defaults to 0.
:param neg_score: (optional) Increment the score of possibilities
matching the "Negative reinforcement" condition by this much.
Defaults to 0.
"""
self.pos_score = pos_score
self.neg_score = neg_score
self.directives = directives
# Positive reinforcement: The highest-scoring instance of any of the specified possibilities specified is
# found and the scores of that possibility everywhere will be affected
# Negative reinforcement: The highest-scoring instance of any of the specified possibilities specified is
# found and the scores of all the other possibilities will be affected
def apply(self, options):
"""Applies the rule to the provided DsOptions object by affecting token possibility scores."""
# Find the highest-scoring instance of each token possibility specified
matched_tokens = []
for tok_list in options.allowed:
for tok in tok_list:
for i in range(0, len(self.directives)):
matched_tokens.append(None)
match_text = self.directives[i]
if tok.text in match_text:
if (not matched_tokens[i]) or tok.score > matched_tokens[i].score:
matched_tokens[i] = tok
# Determine which of the possibilities had the highest score
highest_tok = None
highest_index = 0
for i in range(0, len(matched_tokens)):
tok = matched_tokens[i]
if tok and ((not highest_tok) or tok.score > highest_tok.score):
highest_tok = tok
highest_index = i
# Affect scores (Ties go to the lowest-index argument.)
if highest_tok:
for tok_list in options.allowed:
for tok in tok_list:
for i in range(0, len(self.directives)):
match_text = self.directives[i]
if tok.text in match_text:
if i == highest_index:
# Positive reinforcement
tok.score += self.pos_score
else:
# Negative reinforcement
tok.score += self.neg_score
| class Mutualexclusionrule(object):
"""Mutual exclusion rules indicate that a group of directives
probably aren't going to show up in the same date string.
('%H','%I') would be an example of mutually-exclusive directives.
MutualExclusionRule objects that are elements in the format_rules
attribute of DsOptions objects are evaluated during parsing.
"""
def __init__(self, directives, pos_score=0, neg_score=0):
"""Constructs a MutualExclusionRule object.
Positive reinforcement: The highest-scoring instance of any of the
specified possibilities is found and the scores for that same
possibility at any token where it's present is affected.
Negative reinforcement: The highest-scoring instance of any of the
specified possibilities is found and the scores for all the other
specified possibilities at any token where they're present are
affected.
Returns the MutualExclusionRule object.
:param directives: A set of directives that the rule applies to,
like ('%H','%I').
:param pos_score: (optional) Increment the score of possibilities
matching the "Positive reinforcement" condition by this much.
Defaults to 0.
:param neg_score: (optional) Increment the score of possibilities
matching the "Negative reinforcement" condition by this much.
Defaults to 0.
"""
self.pos_score = pos_score
self.neg_score = neg_score
self.directives = directives
def apply(self, options):
"""Applies the rule to the provided DsOptions object by affecting token possibility scores."""
matched_tokens = []
for tok_list in options.allowed:
for tok in tok_list:
for i in range(0, len(self.directives)):
matched_tokens.append(None)
match_text = self.directives[i]
if tok.text in match_text:
if not matched_tokens[i] or tok.score > matched_tokens[i].score:
matched_tokens[i] = tok
highest_tok = None
highest_index = 0
for i in range(0, len(matched_tokens)):
tok = matched_tokens[i]
if tok and (not highest_tok or tok.score > highest_tok.score):
highest_tok = tok
highest_index = i
if highest_tok:
for tok_list in options.allowed:
for tok in tok_list:
for i in range(0, len(self.directives)):
match_text = self.directives[i]
if tok.text in match_text:
if i == highest_index:
tok.score += self.pos_score
else:
tok.score += self.neg_score |
########################################
# QUESTION
########################################
# Create a function (or write a script in Shell) that takes an integer as an argument
# and returns "Even" for even numbers or "Odd" for odd numbers.
###################################
# SOLUTION
###################################
def even_or_odd(number):
if number % 2 == 0:
return "Even"
else:
return "Odd"
| def even_or_odd(number):
if number % 2 == 0:
return 'Even'
else:
return 'Odd' |
# -*- coding: utf-8 -*-
VERSION_MAJOR = '0'
VERSION_MINOR = '1'
VERSION_PATCH = '1'
VERSION_DEV = 'dev'
def version():
dev = ''
if VERSION_DEV:
dev = '-' + VERSION_DEV
return VERSION_MAJOR + '.' + VERSION_MINOR + '.' + VERSION_PATCH + dev
| version_major = '0'
version_minor = '1'
version_patch = '1'
version_dev = 'dev'
def version():
dev = ''
if VERSION_DEV:
dev = '-' + VERSION_DEV
return VERSION_MAJOR + '.' + VERSION_MINOR + '.' + VERSION_PATCH + dev |
# coding: utf-8
default_app_config = 'modernrpc.apps.ModernRpcConfig'
__version__ = '0.11.1'
| default_app_config = 'modernrpc.apps.ModernRpcConfig'
__version__ = '0.11.1' |
x = 0
if x < 2 :
print('small')
elif x < 10 :
print('Medium')
else :
print('LARGE')
print('All done')
| x = 0
if x < 2:
print('small')
elif x < 10:
print('Medium')
else:
print('LARGE')
print('All done') |
CONTENT_OPERATIONS_RESOURCES_NAMESPACE = \
'bclearer_boson_1_1_source.resources.content_universes'
ADJUSTMENT_OPERATIONS_RESOURCES_NAMESPACE = \
'bclearer_boson_1_1_source.resources.adjustment_universes'
| content_operations_resources_namespace = 'bclearer_boson_1_1_source.resources.content_universes'
adjustment_operations_resources_namespace = 'bclearer_boson_1_1_source.resources.adjustment_universes' |
class UserSource(object):
""" Generalized UserSource to facilitate ldap sync """
def __init__(self, name, bases, org=None, filters=None, user_type=None,
default_filter='(objectClass=*)',
verbose=False):
self.name = name.lower()
self._bases = bases
self.default_filter = default_filter
if filters:
assert len(filters) == len(bases)
self.filters = filters or self.default_filters
self._org = org
self._user_type = user_type
self.verbose = verbose
@staticmethod
def scalar(value, default=''):
if value and isinstance(value, list):
return value[0]
return value or default
@property
def ldap_attributes(self):
raise NotImplementedError
@property
def ldap_mapping(self):
raise NotImplementedError
@property
def organisation(self):
return getattr(self, f'org_{self.name}', self._org)
@property
def bases(self):
return getattr(self, f'bases_{self.name}', self._bases)
def user_type_default(self, entry):
return self._user_type
def user_type(self, entry):
func = getattr(self, f'user_type_{self.name}', None)
return func(entry) if func else self.user_type_default(entry)
def excluded_default(self, entry):
""" Default when no function specific to the source name exists. """
return False
def excluded(self, entry):
""" Finds a specific exclusion function specific to the name or use
the fallback """
func = getattr(self, f'exclude_{self.name}', None)
return func(entry) if func else self.excluded_default(entry)
@property
def default_filters(self):
return [self.default_filter for i in range(len(self.bases))]
@property
def bases_filters_attributes(self):
return tuple(
(b, f, self.ldap_attributes)
for b, f in zip(self.bases, self.filters)
)
def map_entry(self, entry):
attrs = entry.entry_attributes_as_dict
user = {
column: self.scalar(attrs.get(attr))
for attr, column in self.ldap_mapping.items()
}
return user
def complete_entry(self, user, **kwargs):
""" Add additional logic after the user is mapped before writing to
the db. """
return user
def map_entries(self, entries, **kwargs):
for e in entries:
if self.excluded(e):
continue
user = self.map_entry(e)
user = self.complete_entry(user, **kwargs)
yield user
| class Usersource(object):
""" Generalized UserSource to facilitate ldap sync """
def __init__(self, name, bases, org=None, filters=None, user_type=None, default_filter='(objectClass=*)', verbose=False):
self.name = name.lower()
self._bases = bases
self.default_filter = default_filter
if filters:
assert len(filters) == len(bases)
self.filters = filters or self.default_filters
self._org = org
self._user_type = user_type
self.verbose = verbose
@staticmethod
def scalar(value, default=''):
if value and isinstance(value, list):
return value[0]
return value or default
@property
def ldap_attributes(self):
raise NotImplementedError
@property
def ldap_mapping(self):
raise NotImplementedError
@property
def organisation(self):
return getattr(self, f'org_{self.name}', self._org)
@property
def bases(self):
return getattr(self, f'bases_{self.name}', self._bases)
def user_type_default(self, entry):
return self._user_type
def user_type(self, entry):
func = getattr(self, f'user_type_{self.name}', None)
return func(entry) if func else self.user_type_default(entry)
def excluded_default(self, entry):
""" Default when no function specific to the source name exists. """
return False
def excluded(self, entry):
""" Finds a specific exclusion function specific to the name or use
the fallback """
func = getattr(self, f'exclude_{self.name}', None)
return func(entry) if func else self.excluded_default(entry)
@property
def default_filters(self):
return [self.default_filter for i in range(len(self.bases))]
@property
def bases_filters_attributes(self):
return tuple(((b, f, self.ldap_attributes) for (b, f) in zip(self.bases, self.filters)))
def map_entry(self, entry):
attrs = entry.entry_attributes_as_dict
user = {column: self.scalar(attrs.get(attr)) for (attr, column) in self.ldap_mapping.items()}
return user
def complete_entry(self, user, **kwargs):
""" Add additional logic after the user is mapped before writing to
the db. """
return user
def map_entries(self, entries, **kwargs):
for e in entries:
if self.excluded(e):
continue
user = self.map_entry(e)
user = self.complete_entry(user, **kwargs)
yield user |
# More About the print Function (Title)
# Reading
# Suppressing the Print Function's Ending Newline
print('one')
print('two')
print('three')
# To print space instead of newline character (new line of output)
print('one', end=' ')
print('two', end=' ')
print('three')
# To print nothing at the end of its output
print('one', end='')
print('two', end='')
print('three', end='')
# Specifiying an Item Separator (section)
print('One', 'Two', 'Three')
# Use sep='' if you want no space printed between items
print('One' , 'Two', 'Three', sep='')
# Special argument to separate multiple items (similar to above)
print('One', 'Two', 'Three', sep='*')
# Additional example
print('One', 'Two', 'Three', sep='~~~')
# Escape Characters (sections)
# Escape Character \n
print('One/nTwo/nThree')
# Escape Character \t
print('Mon\tTues\tWed')
print('Thur\tFri\tSat')
# Escape Character \' and \" to display quotation marks
print("Your assignment is to read \"Hamlet\" by tomorrow.")
print('I\'m ready to being.')
# Escape Character \\ to display a backslash
print('The path is C:\\temp\\data.')
# End
# Checkpoint
# 2.25 How do you supress the print function's ending newline?
# A: Pass special argument end = ' ' to the function
# 2.26 How can you change the character that is automatically
# displayed between multiple items that are passed to the print function?
# A: Pass the argument sep = ' ' to the print function
# 2.27 What is the '/n' escape character?
# A: Newline escape character
# End | print('one')
print('two')
print('three')
print('one', end=' ')
print('two', end=' ')
print('three')
print('one', end='')
print('two', end='')
print('three', end='')
print('One', 'Two', 'Three')
print('One', 'Two', 'Three', sep='')
print('One', 'Two', 'Three', sep='*')
print('One', 'Two', 'Three', sep='~~~')
print('One/nTwo/nThree')
print('Mon\tTues\tWed')
print('Thur\tFri\tSat')
print('Your assignment is to read "Hamlet" by tomorrow.')
print("I'm ready to being.")
print('The path is C:\\temp\\data.') |
# Copyright 2020 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.
PYTHON_VERSION_COMPATIBILITY = "PY2+3"
DEPS = [
'provenance',
'recipe_engine/path',
]
def RunSteps(api):
api.provenance.generate(
'projects/PROJECT/locations/global/keyRings/KEYRING/cryptoKeys/KEY',
api.path['start_dir'].join('input.json'),
api.path['cleanup'].join('output.attestation'),
)
# Generate another attestation; the module shouldn't install provenance again.
api.provenance.generate(
'projects/PROJECT/locations/global/keyRings/KEYRING/cryptoKeys/KEY',
api.path['start_dir'].join('another-input.json'),
api.path['cleanup'].join('another-output.attestation'),
)
def GenTests(api):
yield api.test('simple')
| python_version_compatibility = 'PY2+3'
deps = ['provenance', 'recipe_engine/path']
def run_steps(api):
api.provenance.generate('projects/PROJECT/locations/global/keyRings/KEYRING/cryptoKeys/KEY', api.path['start_dir'].join('input.json'), api.path['cleanup'].join('output.attestation'))
api.provenance.generate('projects/PROJECT/locations/global/keyRings/KEYRING/cryptoKeys/KEY', api.path['start_dir'].join('another-input.json'), api.path['cleanup'].join('another-output.attestation'))
def gen_tests(api):
yield api.test('simple') |
class Solution:
def romanToInt(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
d['I'] = 1
d['IV'] = 4
d['V'] = 5
d['IX'] = 9
d['X'] = 10
d['XL'] = 40
d['L'] = 50
d['XC'] = 90
d['C'] = 100
d['CD'] = 400
d['D'] = 500
d['CM'] = 900
d['M'] = 1000
res = []
for i in range(len(s)):
res.append(d[s[i]])
for i in range(len(res)-2, -1, -1):
if res[i] < res[i+1]:
res[i] *= -1
#print(res)
return sum(res)
| class Solution:
def roman_to_int(self, s):
"""
:type s: str
:rtype: int
"""
d = {}
d['I'] = 1
d['IV'] = 4
d['V'] = 5
d['IX'] = 9
d['X'] = 10
d['XL'] = 40
d['L'] = 50
d['XC'] = 90
d['C'] = 100
d['CD'] = 400
d['D'] = 500
d['CM'] = 900
d['M'] = 1000
res = []
for i in range(len(s)):
res.append(d[s[i]])
for i in range(len(res) - 2, -1, -1):
if res[i] < res[i + 1]:
res[i] *= -1
return sum(res) |
#
# PySNMP MIB module BASIS-GENERIC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BASIS-GENERIC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:34:35 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")
ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion")
cardGeneric, = mibBuilder.importSymbols("BASIS-MIB", "cardGeneric")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, iso, Unsigned32, ModuleIdentity, Integer32, Bits, NotificationType, ObjectIdentity, TimeTicks, Counter64, Gauge32, MibIdentifier, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "iso", "Unsigned32", "ModuleIdentity", "Integer32", "Bits", "NotificationType", "ObjectIdentity", "TimeTicks", "Counter64", "Gauge32", "MibIdentifier", "IpAddress")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
cardInformation = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 1))
cardInterface = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 2))
cardSelfTest = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 3))
moduleSlotNumber = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleSlotNumber.setStatus('mandatory')
if mibBuilder.loadTexts: moduleSlotNumber.setDescription('Slot number this card is present ')
functionModuleType = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36, 37, 40, 41, 50, 51, 52, 53, 60, 61, 70, 71, 72, 73, 80, 90, 91, 100, 101, 110, 111, 120, 121, 130, 131, 132, 133, 134, 135, 136, 137, 140, 141, 150, 151, 563, 564, 787, 1000, 1001, 1002, 1003, 2000, 2001))).clone(namedValues=NamedValues(("other", 1), ("asc", 2), ("bnm-T3", 10), ("bnm-E3", 11), ("bnm-155", 12), ("srm-4T1E1", 20), ("srm-3T3", 21), ("srme-1OC3", 22), ("srme-1STS3", 23), ("srme-NOBC", 24), ("srm-3T3-NOBC", 25), ("frsm-4T1", 30), ("frsm-4E1", 31), ("frsm-4T1-C", 32), ("frsm-4E1-C", 33), ("frsm-hs1", 34), ("frsm-8T1", 35), ("frsm-8E1", 36), ("frsm-hs1b", 37), ("ausm-4T1", 40), ("ausm-4E1", 41), ("ausm-8T1", 50), ("ausm-8E1", 51), ("ausmB-8T1", 52), ("ausmB-8E1", 53), ("cesm-4T1", 60), ("cesm-4E1", 61), ("imatm-T3T1", 70), ("imatm-E3E1", 71), ("imatmB-8T1", 72), ("imatmB-8E1", 73), ("frasm-8T1", 80), ("cesm-8T1", 90), ("cesm-8E1", 91), ("bscsm-2", 100), ("bscsm-4", 101), ("atmt-8T1", 110), ("atmt-8E1", 111), ("frt-8T1", 120), ("frt-8E1", 121), ("frsm-2ct3", 130), ("frsm-2t3", 131), ("frsm-2e3", 132), ("frsm-hs2", 133), ("frsm-2t3b", 134), ("frsm-2e3b", 135), ("frsm-hs2b-hssi", 136), ("frsm-hs2b-12In1", 137), ("cesm-T3", 140), ("cesm-E3", 141), ("vism-8T1", 150), ("vism-8E1", 151), ("vism-pr-8T1", 563), ("vism-pr-8E1", 564), ("cesmB-8T1", 787), ("pxm1", 1000), ("pxm1-2t3e3", 1001), ("pxm1-4oc3", 1002), ("pxm1-oc12", 1003), ("rpm", 2000), ("rpm-pr", 2001))).clone('other')).setMaxAccess("readonly")
if mibBuilder.loadTexts: functionModuleType.setStatus('mandatory')
if mibBuilder.loadTexts: functionModuleType.setDescription('This object holds the type of the card. The card can type is for Processor module as well as service module. ')
functionModuleDescription = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly")
if mibBuilder.loadTexts: functionModuleDescription.setStatus('mandatory')
if mibBuilder.loadTexts: functionModuleDescription.setDescription('Describes the card ')
functionModuleSerialNum = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 11))).setMaxAccess("readonly")
if mibBuilder.loadTexts: functionModuleSerialNum.setStatus('mandatory')
if mibBuilder.loadTexts: functionModuleSerialNum.setDescription('Serial number of the function Module.')
functionModuleHWRev = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 5), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 2))).setMaxAccess("readonly")
if mibBuilder.loadTexts: functionModuleHWRev.setStatus('mandatory')
if mibBuilder.loadTexts: functionModuleHWRev.setDescription('Hardware revision number for function Module.')
functionModuleFWRev = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: functionModuleFWRev.setStatus('mandatory')
if mibBuilder.loadTexts: functionModuleFWRev.setDescription('Firmware revision number of the function Module.')
functionModuleState = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17))).clone(namedValues=NamedValues(("nocard", 1), ("standby", 2), ("active", 3), ("failed", 4), ("selfTest", 5), ("heldInReset", 6), ("boot", 7), ("mismatch", 8), ("unknown", 9), ("coreCardMisMatch", 10), ("blocked", 11), ("reserved", 12), ("hold", 13), ("notResponding", 14), ("cardinit", 17)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: functionModuleState.setStatus('mandatory')
if mibBuilder.loadTexts: functionModuleState.setDescription("This object holds the status of a card in a particular shelf-slot. The possible values are : nocard(1) : card not present. standby(2) : card in standby state. The card is in ready state and will be ready to take over the service if the corresponding active card(redundant) fails. active(3) : card in active state. The card is providing the service. failed(4) : card in failed state. The card can come out of this state only after user intervention (Reset or running some CLI commands). selfTest(5) : online diagnostics is being run in card. heldInReset(6) : The card configuration is being cleared. No requests can be serviced. boot(7) : card in boot state. mismatch(8) : card is not compatible with the current configuration. Card was correctly provisioned earlier, however the card was replaced by an incompatible card. This state can be resolved by clearing the configuration, or replacing with the appropriate card. unknown(9) : could not determine the state coreCardMisMatch(10) : Controller Card(PXM/ASC etc) and SRM(Service Resource Module) combination does not match. blocked(11) : In case of 1:N redundancy configuration the secondary card(backup card) is covering one of the primary card and can not cover any other card in the group if there is a failure. Redundancy is blocked. hold(13) : The standby controller card assumes the hold state during PXM upgrades. In this state, the standby PXM will be running a different software but will be receiving all standby updates(BRAM and Database). This state is applicable only for MGX8250 Platform. notResponding(14): Response from the Service Module has become slow probably due to overloading of CPU. No recovery action is required on user part. At present, this state is applicable only for Router Blade(RPM). cardinit(17) : When the physical presence of card has been detected but the communication hasn't yet been established between the controller card (PXM) and Service Module. ")
functionModuleResetReason = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18))).clone(namedValues=NamedValues(("powerUp", 1), ("parityError", 2), ("watchDog", 3), ("resourceOverflow", 4), ("clrAllCnf", 5), ("missingTask", 6), ("pxmLowVoltage", 7), ("resetByEventLogTask", 8), ("resetFromShell", 9), ("unknown", 10), ("resetFromPXM", 11), ("resetSys", 12), ("switchCC", 13), ("sCacheError", 14), ("swError", 15), ("upgrade", 16), ("restoreAllCnf", 17), ("driverError", 18)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: functionModuleResetReason.setStatus('mandatory')
if mibBuilder.loadTexts: functionModuleResetReason.setDescription('Last reason for card to reset. The possible values are : powerUp(1) : power up parityError(2) : parity error watchDog(3) : watchdog resourceOverflow (4) : resource overflow clrAllCnf (5) : configuration of the shelf is cleared. missingTask (6) : task is missing pxmLowVoltage(7): low voltage detected on PXM resetByEventLogTask(8): resetFromShell(9): command is run from command shell unknown(10) : resetFromPXM(11) : Controller Card(PXM) reset the card. resetSys(12) : due to resetsys CLI Command. switchCC(13) : due to switch over CLI command. sCacheError(14) : swError(15) : software error. upgrade(16) : upgrade restoreAllCnf(17): restore configuration. driverError(18) : driver error. Valid values for VISM: powerUp, watchDog, resetFromShell and resetFromPXM. ')
lineModuleType = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 48, 49, 50, 51, 60, 61, 62, 63, 70, 71, 80, 81, 500, 501, 502, 503, 504, 505, 506, 507, 511, 512, 513, 514, 515, 1006, 1050, 1051, 1052))).clone(namedValues=NamedValues(("other", 1), ("lm-ASC", 2), ("lm-DB15-4T1", 16), ("lm-DB15-4E1", 17), ("lm-BNC-4E1", 18), ("lm-DB15-4T1-R", 19), ("lm-DB15-4E1-R", 20), ("lm-BNC-4E1-R", 21), ("lm-RJ48-8T1", 22), ("lm-RJ48-8E1", 23), ("lm-SMB-8E1", 24), ("lm-RJ48-T3T1", 25), ("lm-RJ48-E3E1", 26), ("lm-RJ48-T3E1", 27), ("lm-SMB-E3E1", 28), ("lm-RJ48-E3T1", 29), ("lm-SMB-T3E1", 30), ("lm-T3E3-D", 32), ("lm-T3E3-B", 33), ("lm-155-SMF", 34), ("lm-155-UTP", 35), ("lm-RJ48-8T1-R", 48), ("lm-RJ48-8E1-R", 49), ("lm-SMB-8E1-R", 50), ("lm-3T3-B", 51), ("lm-HS1-4X21", 60), ("lm-HS1-3HSSI", 61), ("lm-HS1-4V35", 62), ("lm-12In1-8s", 63), ("lm-BSCSM-2", 70), ("lm-BSCSM-4", 71), ("lm-BNC-2T3", 80), ("lm-BNC-2E3", 81), ("pxm-ui", 500), ("smfir-1-622", 501), ("smflr-1-622", 502), ("smfir15-1-622", 503), ("smflr15-1-622", 504), ("mmf-4-155", 505), ("smfir-4-155", 506), ("smflr-4-155", 507), ("rj45-fe", 511), ("mmf-fe", 512), ("mmf-fddi", 513), ("smf-fddi", 514), ("rj45-4e", 515), ("pxm-ui-s3", 1006), ("lm-srme-1OC3-smlr", 1050), ("lm-srme-1OC3-smir", 1051), ("lm-srme-1OC3-smb", 1052))).clone('other')).setMaxAccess("readonly")
if mibBuilder.loadTexts: lineModuleType.setStatus('mandatory')
if mibBuilder.loadTexts: lineModuleType.setDescription('This object contains the Line Module(back card) type. Physically it is behind the backplane, normally with connectors for physical devices. These are specific to the front or functional modules. ')
lineModuleDescription = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly")
if mibBuilder.loadTexts: lineModuleDescription.setStatus('mandatory')
if mibBuilder.loadTexts: lineModuleDescription.setDescription('This object contains description of the line module.')
lineModuleSerialNum = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 11))).setMaxAccess("readonly")
if mibBuilder.loadTexts: lineModuleSerialNum.setStatus('mandatory')
if mibBuilder.loadTexts: lineModuleSerialNum.setDescription('This object contains Serial number of the line module.')
lineModuleHWRev = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 12), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 2))).setMaxAccess("readonly")
if mibBuilder.loadTexts: lineModuleHWRev.setStatus('mandatory')
if mibBuilder.loadTexts: lineModuleHWRev.setDescription('This object contains Hardware revision for line module.')
lineModuleFWRev = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: lineModuleFWRev.setStatus('mandatory')
if mibBuilder.loadTexts: lineModuleFWRev.setDescription('Firmware revision for line module. The current version does not have any firmware, hence will always contains zero length octet string.')
lineModuleState = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notPresent", 1), ("present", 2), ("invalid", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: lineModuleState.setStatus('mandatory')
if mibBuilder.loadTexts: lineModuleState.setDescription('line module status.')
moduleTrapAlarmSeverity = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("minor", 1), ("major", 2), ("dontCare", 3), ("critical", 4), ("error", 5), ("warning", 6), ("notice", 7), ("info", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: moduleTrapAlarmSeverity.setStatus('mandatory')
if mibBuilder.loadTexts: moduleTrapAlarmSeverity.setDescription('This object is sent to managers as part of all Trap PDUs, to determine the module alarm severity. An implementation may not support all the possible values. The Possible values are : major (1) : Major Service has been impacted minor (2) : Minor Service has been lost dontCare (3) : severity is not applicable critical (4) : affects existing data traffic error (5) : error has occurred warning (6) : a threshold has been reached notice (7) : a normal but significant event has occurred info (8) : informational ')
mibVersionNumber = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 16), Integer32().clone(2)).setMaxAccess("readonly")
if mibBuilder.loadTexts: mibVersionNumber.setStatus('mandatory')
if mibBuilder.loadTexts: mibVersionNumber.setDescription('MIB version number. Updated when any part of the MIB changes. ')
configChangeTypeBitMap = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 17), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: configChangeTypeBitMap.setStatus('mandatory')
if mibBuilder.loadTexts: configChangeTypeBitMap.setDescription('Configuration change Type BitMap bit 0 set = Card Configuration Change bit 1 set = Line Configuration Change bit 2 set = Port Configuration Change bit 3 set = Chan Configuration Change bit 4 set = STUN protocol group configuration Change bit 5 set = STUN port configuration Change bit 6 set = STUN route configuration Change bit 7 set = BSTUN protocol configuration Change bit 8 set = BSTUN port configuration Change bit 9 set = BSTUN route configuration Change bit 10 set = FRASBNN route configuration Change bit 11 set = FRASBAN route configuration Change bit 12 set = SDLC port configuration Change bit 13 set = SDLC LS configuration Change bit 14 set = BSC port configuration Change bit 15 set = LLC port configuration Change bit 16 set = card LCN partition change (controller based only) bit 17 set = port resource partition change (under any partition type) bit 18 set = VISM Endpoint Configuration Change bit 19 set = Egress Q configuration change default value is 0, no change This object makes sense only in traps. A GET on this may not return a Useful result. Bit 19 is not applicable for MGX 8850 Release 1.x.x and MGX 8220 ')
configChangeObjectIndex = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: configChangeObjectIndex.setStatus('mandatory')
if mibBuilder.loadTexts: configChangeObjectIndex.setDescription("Configuration change object index, could be line number or port number or channel number depends on the type bitmap, for port resouce partition change (bit 17), this index is actually constructed by (portNum << 16 | controller) because the table has two indices. When the 'Line Configuration Change' bit is set, the configChangeObjectIndex has the following special meanings in IMATM and FRSM-2CT3 cards: IMATM - configChangeObjectIndex range between 1..8 indicates that the configuration change refers to the DS1 line index. A value of 9 indicates that the configuration change refers to the DS3 line index. FRSM-2CT3 - configChangeObjectIndex range between 1..56 indicates that the configuration change refers to the DS1 line index. A value of (128 + n) refers to DS3 line index numbered 'n'. This object makes sense only in traps. A GET on this may not return a Useful result. ")
configChangeStatus = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3))).setMaxAccess("readonly")
if mibBuilder.loadTexts: configChangeStatus.setStatus('mandatory')
if mibBuilder.loadTexts: configChangeStatus.setDescription('This object is applicable only for traps. The SNMP operation may not be meaningful. The value contained in this object is same as the value of the other objects which are used for adding/deleting/modifying the row. The possible values are 0 - No meaning and is not applicable. 1 - add [ Row added ] 2 - delete [ Row deleted ] 3 - mod [ Row modified ] This value and value contained in configChangeTypeBitMap represent the configuration change operation. The default value is 0 and it does not represent any status.')
cardIntegratedAlarmBitMap = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 20), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cardIntegratedAlarmBitMap.setStatus('mandatory')
if mibBuilder.loadTexts: cardIntegratedAlarmBitMap.setDescription('Bit position represents the different types of alarm for ASC: bit 0: ShelfFunctionModuleState (BNM only) (failed/boot/mismatch/heldinReset) bit 1: LineModuleState (BNM only) (notPresent/invalid) bit 2: ASMPhysicalAlarmState (BNM only) bit 3: ATMLMIFailure (ASC only) bit 4: LineAlarmState (BNM only) bit 5: LineStatisticalAlarmState (BNM only) bit 6: PLCPAlarmState (BNM only) bit 7: PLCPStatisticalAlarmState (BNM only) bit 8: SmConnectionFailureAlarm for SM: bit 0: ShelfFunctionModuleState (failed/boot/mismatch/heldinReset) bit 1: LineModuleState (notPresent/invalid) bit 2: PortLMIFailure bit 3: LineAlarmState bit 4: LineStatisticalAlarmState bit 5: FrameRelayPortState (RemoteLoopback/ FailedDueToLine/ FailedDueToSig) bit 6: ChannelState for PXM/SRM Only (MGX8850 Platfrom): Only those marked with SRM are valid for both PXM/SRM. The rest are valid only for PXM. bit 0 : ShelfFunctionModuleState bit 1 : Backcard Line Module (SRM/PXM) This Alarm is generated when the Line Module (Trunk Backcard) is removed or goes to a mismatch state(or backcard type is unknown). bit 2 : Backcard UIModule This Alarm is generated when the UI backcard is removed or goes to a mismatch state (or backcard type is unknown). bit 3 : ASM Physical Alarm This specifies whether any of the environmental monitoring components like Temperature, Voltage Supply, Fan Speed have gone into alarm. bit 4 : ATM LMI Failure bit 5 : Line Alarm (SRM/PXM) bit 6 : Line Statistical Alarm (SRM/PXM) bit 7 : Lines Alarm (SRM/PXM) bit 8 : PLCP Alarm bit 9 : PLCP Statistical Alarm bit 10 : Connections exist on removed SM bit 11 : Disk related Failure on first PXM slot bit 12 : Disk related Failure on second PXM slot The Disk Alarms are generated when any of the file operations on Disk like open,read,write, lseek etc fail. VSM Alarms bit 13 : Port LMI Failure bit 14 : Port State Alarm bit 15 : Channel Shelf Alarm bit 16 : Taskmon Task Suspended bit 17 : Excess Power Consumption bit 30 : bit set(1) major alarm, else (0) minor alarm ')
cleiCode = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 21), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 10))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cleiCode.setStatus('mandatory')
if mibBuilder.loadTexts: cleiCode.setDescription('Common Language Equipment(CLEI) Code. ')
macAddress = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 22), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: macAddress.setStatus('mandatory')
if mibBuilder.loadTexts: macAddress.setDescription('Ethernet address (base address) stored in NVRAM, entered by manfacturing. ')
macAddrBlkSize = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 23), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: macAddrBlkSize.setStatus('mandatory')
if mibBuilder.loadTexts: macAddrBlkSize.setDescription('The MAC address block size, entered by manufacturing. ')
finalTestTechnician = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 24), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 6))).setMaxAccess("readonly")
if mibBuilder.loadTexts: finalTestTechnician.setStatus('mandatory')
if mibBuilder.loadTexts: finalTestTechnician.setDescription('The Final Test Technician Employee Identification Number. ')
hwFailures = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 25), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwFailures.setStatus('mandatory')
if mibBuilder.loadTexts: hwFailures.setDescription('Hardware failure code.')
hwHistory = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 26), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hwHistory.setStatus('mandatory')
if mibBuilder.loadTexts: hwHistory.setDescription('RMA Test History - RMA Failure Code.')
secLineModuleType = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 48, 49, 50, 51, 60, 61, 62, 63, 70, 71, 80, 81, 500, 501, 502, 503, 504, 505, 506, 507, 511, 512, 513, 514, 515, 1006))).clone(namedValues=NamedValues(("other", 1), ("lm-ASC", 2), ("lm-DB15-4T1", 16), ("lm-DB15-4E1", 17), ("lm-BNC-4E1", 18), ("lm-DB15-4T1-R", 19), ("lm-DB15-4E1-R", 20), ("lm-BNC-4E1-R", 21), ("lm-RJ48-8T1", 22), ("lm-RJ48-8E1", 23), ("lm-SMB-8E1", 24), ("lm-RJ48-T3T1", 25), ("lm-RJ48-E3E1", 26), ("lm-RJ48-T3E1", 27), ("lm-SMB-E3E1", 28), ("lm-RJ48-E3T1", 29), ("lm-SMB-T3E1", 30), ("lm-T3E3-D", 32), ("lm-T3E3-B", 33), ("lm-155-SMF", 34), ("lm-155-UTP", 35), ("lm-RJ48-8T1-R", 48), ("lm-RJ48-8E1-R", 49), ("lm-SMB-8E1-R", 50), ("lm-3T3-B", 51), ("lm-HS1-4X21", 60), ("lm-HS1-3HSSI", 61), ("lm-HS1-4V35", 62), ("lm-12In1-8s", 63), ("lm-BSCSM-2", 70), ("lm-BSCSM-4", 71), ("lm-BNC-2T3", 80), ("lm-BNC-2E3", 81), ("pxm-ui", 500), ("smfir-1-622", 501), ("smflr-1-622", 502), ("smfir15-1-622", 503), ("smflr15-1-622", 504), ("mmf-4-155", 505), ("smfir-4-155", 506), ("smflr-4-155", 507), ("rj45-fe", 511), ("mmf-fe", 512), ("mmf-fddi", 513), ("smf-fddi", 514), ("rj45-4e", 515), ("pxm-ui-s3", 1006))).clone('other')).setMaxAccess("readonly")
if mibBuilder.loadTexts: secLineModuleType.setStatus('mandatory')
if mibBuilder.loadTexts: secLineModuleType.setDescription('This object contains the type of secondary line module(back card). Physically it is the bottom card behind the backplane. Normally with connectors for physical devices. These are specific to the front or function modules. This Object is applicable only to selected MGX switches. ')
secLineModuleDescription = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 28), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 20))).setMaxAccess("readonly")
if mibBuilder.loadTexts: secLineModuleDescription.setStatus('mandatory')
if mibBuilder.loadTexts: secLineModuleDescription.setDescription('Description of the Secondary line module. This Object is applicable only to selected MGX switches. ')
secLineModuleSerialNum = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 29), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 11))).setMaxAccess("readonly")
if mibBuilder.loadTexts: secLineModuleSerialNum.setStatus('mandatory')
if mibBuilder.loadTexts: secLineModuleSerialNum.setDescription('Serial number of the secondary(bottom) line module. This object is applicable only to selected MGX switches. ')
secLineModuleHWRev = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 30), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 2))).setMaxAccess("readonly")
if mibBuilder.loadTexts: secLineModuleHWRev.setStatus('mandatory')
if mibBuilder.loadTexts: secLineModuleHWRev.setDescription('Hardware revision for secondary (bottom) line module This object is applicable only to selected MGX switches. ')
secLineModuleFWRev = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 31), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 8))).setMaxAccess("readonly")
if mibBuilder.loadTexts: secLineModuleFWRev.setStatus('mandatory')
if mibBuilder.loadTexts: secLineModuleFWRev.setDescription('Firmware revision for Secondary line module This object is applicable only to selected MGX switches. If there is no Firmware revision, then this object returns 0. ')
secLineModuleState = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("notPresent", 1), ("present", 2), ("invalid", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: secLineModuleState.setStatus('mandatory')
if mibBuilder.loadTexts: secLineModuleState.setDescription('line module status of secondary (bottom) back card. This object is applicable only to selected MGX switches.')
configChangeParentObjectIndex = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 33), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: configChangeParentObjectIndex.setStatus('mandatory')
if mibBuilder.loadTexts: configChangeParentObjectIndex.setDescription(" Parent object index, could be - line index - port index This object will indicate the index of the immediate higher level object (line or port) of configChangeObjectIndex. This object is applicable only when configChangeObjectIndex represents a channel, port, egress Q or resource partition index. Following specifies the mapping between the configChangeObjectIndex and its corresponding configChangeParentObjectIndex. configChangeObjectIndex configChangeParentObjectIndex ----------------------- ----------------------------- Port Index Line Index Egress Q Index Port Index Resource Partition Index Port Index Channel Index Port Index When the 'Port Configuration Change' bit is set, the configChangeParentObjectIndex will represent a 'Line Index' which in turn has the following special meaning in FRSM-2CT3 cards. - configChangeParentObjectIndex range between 1..56 indicates that the configuration change refers to the DS1 line index. A value of (128 + n) refers to DS3 line index numbered 'n'. This object object is applicable only in traps. A GET on this may not return a useful result. This object Object is not applicable to MGX 8850 Release 1.x.x and MGX8220 ")
configChangeGrandParentObjectIndex = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 34), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1024))).setMaxAccess("readonly")
if mibBuilder.loadTexts: configChangeGrandParentObjectIndex.setStatus('mandatory')
if mibBuilder.loadTexts: configChangeGrandParentObjectIndex.setDescription(" Grand Parent object index, could be - line index This object will indicate the index of the immediate higher level object (line) of configChangeParentObjectIndex. This object is applicable only when configChangeParentObjectIndex represents a port index. Following specifies the mapping between the configChangeParentObjectIndex and its corresponding configChangeGrandParentObjectIndex. When the 'Port Configuration Change' bit is set the configChangeGrandParentObjectIndex will represent a 'Line Index' which in turn has the following special meaning in FRSM-2CT3 cards. - configChangeParentObjectIndex range between 1..56 indicates that the configuration change refers to the DS1 line index. A value of (128 + n) refers to DS3 line index numbered 'n'. This object is applicable only in traps. A GET on this may not return a useful result. This object is not applicable to MGX 8850 release 1.x.x and MGX8220.")
configChangeSMSpecificObject = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 35), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 16777215))).setMaxAccess("readonly")
if mibBuilder.loadTexts: configChangeSMSpecificObject.setStatus('mandatory')
if mibBuilder.loadTexts: configChangeSMSpecificObject.setDescription(' configChangeSMSpecificObject is a generic object which is Service Module Specific. It can be used for different purposes in different cards. The usage of the same with regard to very card type is listed below. FRSM-8T1E1 - used to store portDs0ConfigBitMap FRSM-VHS - used to store portDs0ConfigBitMap CESM-8T1E1 - used to store cesPortDs0ConfigBitMap CESM-T3E3 - not used AUSM-8T1E1 - not used This object is not applicable to MGX 8850 Release 1.x.x and MGX8220.')
transId = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 36), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: transId.setStatus('mandatory')
if mibBuilder.loadTexts: transId.setDescription('Per card transaction ID. This object is used to keep track of configuration change on the card. The transId will be incremented by one for every configuration change on the card.')
interfaceNumOfValidEntries = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: interfaceNumOfValidEntries.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceNumOfValidEntries.setDescription('Number of rows in interface Table The number represents the physcial interfaces the module has. ')
interfaceLineTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1), )
if mibBuilder.loadTexts: interfaceLineTable.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceLineTable.setDescription('This table has list of the physical interfaces and the services available on this module. ')
interfaceLineEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1), ).setIndexNames((0, "BASIS-GENERIC-MIB", "interfaceLineNum"))
if mibBuilder.loadTexts: interfaceLineEntry.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceLineEntry.setDescription('An entry for physical interface ')
interfaceLineNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10))).setMaxAccess("readonly")
if mibBuilder.loadTexts: interfaceLineNum.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceLineNum.setDescription('An index to uniquely indentify the physical interface and service. Indices 1..8 are used for VISM-8T1/E1. ')
interfaceLineType = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 18, 19, 26, 30, 33, 45, 46))).clone(namedValues=NamedValues(("other", 1), ("ds1", 18), ("e1", 19), ("ethernet-3Mbit", 26), ("ds3", 30), ("rs232", 33), ("v35", 45), ("hssi", 46)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: interfaceLineType.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceLineType.setDescription('This object indicates the type of interfaces provided by this Module. These numbers are from RFC1700.')
interfaceNumOfPortsPerLine = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)).clone(672)).setMaxAccess("readonly")
if mibBuilder.loadTexts: interfaceNumOfPortsPerLine.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceNumOfPortsPerLine.setDescription('The number of physical ports of the line type. VISM has a port, but is not linked to these physical lines, hence value=0 is returned. ')
interfaceServiceType = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 26, 28, 32, 37, 42))).clone(namedValues=NamedValues(("other", 1), ("ethernet-3Mbit", 26), ("slip", 28), ("frameRelay", 32), ("atm", 37), ("voice", 42)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: interfaceServiceType.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceServiceType.setDescription('The services available on the interfaceLineType object ')
interfaceNumOfPVC = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: interfaceNumOfPVC.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceNumOfPVC.setDescription('The Max number of Permanent Virtual Channels available per physical line (line as defined in interfaceLineType). VISM has a PVC but is not linked to the lines, hence value=0 is returned. ')
interfaceNumOfEgressQueue = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: interfaceNumOfEgressQueue.setStatus('mandatory')
if mibBuilder.loadTexts: interfaceNumOfEgressQueue.setDescription('The Max number of Queues per port. Value=0 is returned for VISM card. ')
selfTestEnable = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2))).clone('disable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: selfTestEnable.setStatus('mandatory')
if mibBuilder.loadTexts: selfTestEnable.setDescription('This object indicates the self test state 1 ==> self test enabled 2 ==> self test disabled ')
selfTestPeriod = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 60)).clone(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: selfTestPeriod.setStatus('mandatory')
if mibBuilder.loadTexts: selfTestPeriod.setDescription('Interval (in minutes) for self test. ')
selfTestState = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("passed", 1), ("failed", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: selfTestState.setStatus('mandatory')
if mibBuilder.loadTexts: selfTestState.setDescription('Self test results for the module. ')
selfTestResultDescription = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 40))).setMaxAccess("readonly")
if mibBuilder.loadTexts: selfTestResultDescription.setStatus('mandatory')
if mibBuilder.loadTexts: selfTestResultDescription.setDescription('Self test Result description ')
selfTestClrResultButton = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("clear", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: selfTestClrResultButton.setStatus('mandatory')
if mibBuilder.loadTexts: selfTestClrResultButton.setDescription('This object is used for clearing the result of an online diagnostics(or other self tests).')
controlMsgCounter = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 4))
riscXmtCtrlMsg = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: riscXmtCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts: riscXmtCtrlMsg.setDescription('The number of control Frames transmitted to SAR (from RISC) maintained by RISC ')
riscRcvCtrlMsg = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: riscRcvCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts: riscRcvCtrlMsg.setDescription('The number of control Frames received from SAR (to RISC) maintained by RISC ')
sarXmtCtrlMsg = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarXmtCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts: sarXmtCtrlMsg.setDescription('The number of control Frames transmitted to RISC from SAR maintained by SAR (should be equal to (riscRcvCtrlMsg) ')
sarRcvCtrlMsg = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarRcvCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts: sarRcvCtrlMsg.setDescription('The number of control Frames received to SAR from RISC maintained by SAR (should be equal to (riscXmtCtrlMsg) ')
sarCtrlMsgDiscLenErr = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarCtrlMsgDiscLenErr.setStatus('mandatory')
if mibBuilder.loadTexts: sarCtrlMsgDiscLenErr.setDescription('Total control (management) frames (for MGX8800) or cells(for MGX8220) discarded due to illegal length error ')
sarCtrlMsgDiscCRCErr = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarCtrlMsgDiscCRCErr.setStatus('mandatory')
if mibBuilder.loadTexts: sarCtrlMsgDiscCRCErr.setDescription('Total control (management) frames (MGX8800) or cells(MGX8220) discard due to illegal CRC error. ')
sarCtrlMsgDiscUnknownChan = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarCtrlMsgDiscUnknownChan.setStatus('mandatory')
if mibBuilder.loadTexts: sarCtrlMsgDiscUnknownChan.setDescription('Count of discarded control message due to unknown channel error.')
sarCtrlMsgLastUnkownChan = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 8), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarCtrlMsgLastUnkownChan.setStatus('mandatory')
if mibBuilder.loadTexts: sarCtrlMsgLastUnkownChan.setDescription('The control cell header Rcvd of the last unknown channel.')
ctrlMsgClrButton = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("clear", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ctrlMsgClrButton.setStatus('mandatory')
if mibBuilder.loadTexts: ctrlMsgClrButton.setDescription('This object is used for clearing the messages in controlMsgCounter group.')
sarChannelCounter = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 5))
chanNumOfValidEntries = MibScalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: chanNumOfValidEntries.setStatus('mandatory')
if mibBuilder.loadTexts: chanNumOfValidEntries.setDescription('Number of entries in the sar channel table ')
sarChannelCounterTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1), )
if mibBuilder.loadTexts: sarChannelCounterTable.setStatus('mandatory')
if mibBuilder.loadTexts: sarChannelCounterTable.setDescription('The table is for logical channels This table contains the counters for cells transmitted on each channel.')
sarChannelCounterEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1), ).setIndexNames((0, "BASIS-GENERIC-MIB", "sarShelfNum"), (0, "BASIS-GENERIC-MIB", "sarSlotNum"), (0, "BASIS-GENERIC-MIB", "sarChanNum"))
if mibBuilder.loadTexts: sarChannelCounterEntry.setStatus('mandatory')
if mibBuilder.loadTexts: sarChannelCounterEntry.setDescription(' An entry for logical channel ')
sarShelfNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarShelfNum.setStatus('mandatory')
if mibBuilder.loadTexts: sarShelfNum.setDescription('Shelf number ')
sarSlotNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarSlotNum.setStatus('mandatory')
if mibBuilder.loadTexts: sarSlotNum.setDescription('Slot number, the slot and shelf info is required here because BSC sends the OAM cells for the FRSM cards that have failed BSC could have upto 4000 connections in this table.')
sarChanNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4015))).setMaxAccess("readonly")
if mibBuilder.loadTexts: sarChanNum.setStatus('mandatory')
if mibBuilder.loadTexts: sarChanNum.setDescription(' BSC could have upto 4000 connections in this table ')
xmtCells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCells.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCells.setDescription('The number of cells transmitted on this channel. ')
xmtCellsCLP = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCellsCLP.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCellsCLP.setDescription('The total number of CLP cells that were transmitted on this channel.')
xmtCellsAIS = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCellsAIS.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCellsAIS.setDescription('The number of AIS cells that were transmitted on this channel. ')
xmtCellsFERF = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCellsFERF.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCellsFERF.setDescription('The number of FERF cells that were transmitted on this channel. ')
xmtCellsBCM = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCellsBCM.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCellsBCM.setDescription('The number of BCM cells that were transmitted on this channel.')
xmtCellsEnd2EndLpBk = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCellsEnd2EndLpBk.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCellsEnd2EndLpBk.setDescription('The number of End2End loop cells that were transmitted on this channel.')
xmtCellsSegmentLpBk = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCellsSegmentLpBk.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCellsSegmentLpBk.setDescription('The number of segment loop cells that were transmitted on this channel.')
xmtCellsDiscShelfAlarm = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: xmtCellsDiscShelfAlarm.setStatus('mandatory')
if mibBuilder.loadTexts: xmtCellsDiscShelfAlarm.setDescription('The number of cells discard due to Shelfalarm on this channel. ')
rcvCells = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCells.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCells.setDescription('The number of cells that were received on this channel. ')
rcvCellsCLP = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCellsCLP.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCellsCLP.setDescription('The number of CLP cells that were received on this channel. ')
rcvCellsAIS = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCellsAIS.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCellsAIS.setDescription('The number of AIS cells that were received on this channel. ')
rcvCellsFERF = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCellsFERF.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCellsFERF.setDescription('The number of FERF cells that were received on this channel. ')
rcvCellsBCM = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCellsBCM.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCellsBCM.setDescription('The number of BCM cells that were received on this channel. ')
rcvCellsEnd2EndLpBk = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCellsEnd2EndLpBk.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCellsEnd2EndLpBk.setDescription('The number of End2End loop cells that were received on this channel.')
rcvCellsSegmentLpBk = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCellsSegmentLpBk.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCellsSegmentLpBk.setDescription('The number of segment loop cells that were received on this channel. ')
rcvCellsDiscOAM = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rcvCellsDiscOAM.setStatus('mandatory')
if mibBuilder.loadTexts: rcvCellsDiscOAM.setDescription('The number of cells that had CRC error on OAM cells ')
sarClrButton = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("other", 1), ("clear", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: sarClrButton.setStatus('mandatory')
if mibBuilder.loadTexts: sarClrButton.setDescription('clear the counters in the table ')
mibBuilder.exportSymbols("BASIS-GENERIC-MIB", configChangeObjectIndex=configChangeObjectIndex, functionModuleFWRev=functionModuleFWRev, interfaceLineNum=interfaceLineNum, cardSelfTest=cardSelfTest, rcvCellsCLP=rcvCellsCLP, sarCtrlMsgDiscLenErr=sarCtrlMsgDiscLenErr, ctrlMsgClrButton=ctrlMsgClrButton, xmtCellsSegmentLpBk=xmtCellsSegmentLpBk, macAddrBlkSize=macAddrBlkSize, interfaceNumOfEgressQueue=interfaceNumOfEgressQueue, moduleTrapAlarmSeverity=moduleTrapAlarmSeverity, chanNumOfValidEntries=chanNumOfValidEntries, interfaceLineType=interfaceLineType, interfaceServiceType=interfaceServiceType, interfaceNumOfPortsPerLine=interfaceNumOfPortsPerLine, lineModuleDescription=lineModuleDescription, lineModuleFWRev=lineModuleFWRev, secLineModuleSerialNum=secLineModuleSerialNum, xmtCellsAIS=xmtCellsAIS, xmtCellsEnd2EndLpBk=xmtCellsEnd2EndLpBk, selfTestResultDescription=selfTestResultDescription, sarSlotNum=sarSlotNum, functionModuleState=functionModuleState, selfTestEnable=selfTestEnable, functionModuleDescription=functionModuleDescription, interfaceLineTable=interfaceLineTable, sarChannelCounterEntry=sarChannelCounterEntry, selfTestPeriod=selfTestPeriod, sarChanNum=sarChanNum, rcvCellsDiscOAM=rcvCellsDiscOAM, sarCtrlMsgDiscUnknownChan=sarCtrlMsgDiscUnknownChan, sarRcvCtrlMsg=sarRcvCtrlMsg, riscXmtCtrlMsg=riscXmtCtrlMsg, functionModuleSerialNum=functionModuleSerialNum, configChangeGrandParentObjectIndex=configChangeGrandParentObjectIndex, xmtCellsCLP=xmtCellsCLP, lineModuleHWRev=lineModuleHWRev, selfTestClrResultButton=selfTestClrResultButton, hwHistory=hwHistory, xmtCells=xmtCells, functionModuleType=functionModuleType, functionModuleResetReason=functionModuleResetReason, selfTestState=selfTestState, xmtCellsBCM=xmtCellsBCM, secLineModuleHWRev=secLineModuleHWRev, interfaceNumOfPVC=interfaceNumOfPVC, rcvCellsEnd2EndLpBk=rcvCellsEnd2EndLpBk, secLineModuleFWRev=secLineModuleFWRev, rcvCells=rcvCells, sarXmtCtrlMsg=sarXmtCtrlMsg, riscRcvCtrlMsg=riscRcvCtrlMsg, cardInformation=cardInformation, controlMsgCounter=controlMsgCounter, sarChannelCounter=sarChannelCounter, configChangeStatus=configChangeStatus, rcvCellsSegmentLpBk=rcvCellsSegmentLpBk, rcvCellsBCM=rcvCellsBCM, cleiCode=cleiCode, secLineModuleState=secLineModuleState, mibVersionNumber=mibVersionNumber, sarCtrlMsgLastUnkownChan=sarCtrlMsgLastUnkownChan, secLineModuleType=secLineModuleType, configChangeParentObjectIndex=configChangeParentObjectIndex, transId=transId, lineModuleState=lineModuleState, rcvCellsFERF=rcvCellsFERF, sarChannelCounterTable=sarChannelCounterTable, functionModuleHWRev=functionModuleHWRev, hwFailures=hwFailures, configChangeSMSpecificObject=configChangeSMSpecificObject, xmtCellsDiscShelfAlarm=xmtCellsDiscShelfAlarm, configChangeTypeBitMap=configChangeTypeBitMap, lineModuleType=lineModuleType, interfaceNumOfValidEntries=interfaceNumOfValidEntries, interfaceLineEntry=interfaceLineEntry, cardInterface=cardInterface, sarClrButton=sarClrButton, lineModuleSerialNum=lineModuleSerialNum, macAddress=macAddress, cardIntegratedAlarmBitMap=cardIntegratedAlarmBitMap, sarCtrlMsgDiscCRCErr=sarCtrlMsgDiscCRCErr, rcvCellsAIS=rcvCellsAIS, sarShelfNum=sarShelfNum, moduleSlotNumber=moduleSlotNumber, secLineModuleDescription=secLineModuleDescription, xmtCellsFERF=xmtCellsFERF, finalTestTechnician=finalTestTechnician)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion')
(card_generic,) = mibBuilder.importSymbols('BASIS-MIB', 'cardGeneric')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, iso, unsigned32, module_identity, integer32, bits, notification_type, object_identity, time_ticks, counter64, gauge32, mib_identifier, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'iso', 'Unsigned32', 'ModuleIdentity', 'Integer32', 'Bits', 'NotificationType', 'ObjectIdentity', 'TimeTicks', 'Counter64', 'Gauge32', 'MibIdentifier', 'IpAddress')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
card_information = mib_identifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 1))
card_interface = mib_identifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 2))
card_self_test = mib_identifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 3))
module_slot_number = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 32))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
moduleSlotNumber.setStatus('mandatory')
if mibBuilder.loadTexts:
moduleSlotNumber.setDescription('Slot number this card is present ')
function_module_type = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36, 37, 40, 41, 50, 51, 52, 53, 60, 61, 70, 71, 72, 73, 80, 90, 91, 100, 101, 110, 111, 120, 121, 130, 131, 132, 133, 134, 135, 136, 137, 140, 141, 150, 151, 563, 564, 787, 1000, 1001, 1002, 1003, 2000, 2001))).clone(namedValues=named_values(('other', 1), ('asc', 2), ('bnm-T3', 10), ('bnm-E3', 11), ('bnm-155', 12), ('srm-4T1E1', 20), ('srm-3T3', 21), ('srme-1OC3', 22), ('srme-1STS3', 23), ('srme-NOBC', 24), ('srm-3T3-NOBC', 25), ('frsm-4T1', 30), ('frsm-4E1', 31), ('frsm-4T1-C', 32), ('frsm-4E1-C', 33), ('frsm-hs1', 34), ('frsm-8T1', 35), ('frsm-8E1', 36), ('frsm-hs1b', 37), ('ausm-4T1', 40), ('ausm-4E1', 41), ('ausm-8T1', 50), ('ausm-8E1', 51), ('ausmB-8T1', 52), ('ausmB-8E1', 53), ('cesm-4T1', 60), ('cesm-4E1', 61), ('imatm-T3T1', 70), ('imatm-E3E1', 71), ('imatmB-8T1', 72), ('imatmB-8E1', 73), ('frasm-8T1', 80), ('cesm-8T1', 90), ('cesm-8E1', 91), ('bscsm-2', 100), ('bscsm-4', 101), ('atmt-8T1', 110), ('atmt-8E1', 111), ('frt-8T1', 120), ('frt-8E1', 121), ('frsm-2ct3', 130), ('frsm-2t3', 131), ('frsm-2e3', 132), ('frsm-hs2', 133), ('frsm-2t3b', 134), ('frsm-2e3b', 135), ('frsm-hs2b-hssi', 136), ('frsm-hs2b-12In1', 137), ('cesm-T3', 140), ('cesm-E3', 141), ('vism-8T1', 150), ('vism-8E1', 151), ('vism-pr-8T1', 563), ('vism-pr-8E1', 564), ('cesmB-8T1', 787), ('pxm1', 1000), ('pxm1-2t3e3', 1001), ('pxm1-4oc3', 1002), ('pxm1-oc12', 1003), ('rpm', 2000), ('rpm-pr', 2001))).clone('other')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
functionModuleType.setStatus('mandatory')
if mibBuilder.loadTexts:
functionModuleType.setDescription('This object holds the type of the card. The card can type is for Processor module as well as service module. ')
function_module_description = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
functionModuleDescription.setStatus('mandatory')
if mibBuilder.loadTexts:
functionModuleDescription.setDescription('Describes the card ')
function_module_serial_num = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 11))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
functionModuleSerialNum.setStatus('mandatory')
if mibBuilder.loadTexts:
functionModuleSerialNum.setDescription('Serial number of the function Module.')
function_module_hw_rev = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 5), display_string().subtype(subtypeSpec=value_size_constraint(0, 2))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
functionModuleHWRev.setStatus('mandatory')
if mibBuilder.loadTexts:
functionModuleHWRev.setDescription('Hardware revision number for function Module.')
function_module_fw_rev = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 8))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
functionModuleFWRev.setStatus('mandatory')
if mibBuilder.loadTexts:
functionModuleFWRev.setDescription('Firmware revision number of the function Module.')
function_module_state = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 17))).clone(namedValues=named_values(('nocard', 1), ('standby', 2), ('active', 3), ('failed', 4), ('selfTest', 5), ('heldInReset', 6), ('boot', 7), ('mismatch', 8), ('unknown', 9), ('coreCardMisMatch', 10), ('blocked', 11), ('reserved', 12), ('hold', 13), ('notResponding', 14), ('cardinit', 17)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
functionModuleState.setStatus('mandatory')
if mibBuilder.loadTexts:
functionModuleState.setDescription("This object holds the status of a card in a particular shelf-slot. The possible values are : nocard(1) : card not present. standby(2) : card in standby state. The card is in ready state and will be ready to take over the service if the corresponding active card(redundant) fails. active(3) : card in active state. The card is providing the service. failed(4) : card in failed state. The card can come out of this state only after user intervention (Reset or running some CLI commands). selfTest(5) : online diagnostics is being run in card. heldInReset(6) : The card configuration is being cleared. No requests can be serviced. boot(7) : card in boot state. mismatch(8) : card is not compatible with the current configuration. Card was correctly provisioned earlier, however the card was replaced by an incompatible card. This state can be resolved by clearing the configuration, or replacing with the appropriate card. unknown(9) : could not determine the state coreCardMisMatch(10) : Controller Card(PXM/ASC etc) and SRM(Service Resource Module) combination does not match. blocked(11) : In case of 1:N redundancy configuration the secondary card(backup card) is covering one of the primary card and can not cover any other card in the group if there is a failure. Redundancy is blocked. hold(13) : The standby controller card assumes the hold state during PXM upgrades. In this state, the standby PXM will be running a different software but will be receiving all standby updates(BRAM and Database). This state is applicable only for MGX8250 Platform. notResponding(14): Response from the Service Module has become slow probably due to overloading of CPU. No recovery action is required on user part. At present, this state is applicable only for Router Blade(RPM). cardinit(17) : When the physical presence of card has been detected but the communication hasn't yet been established between the controller card (PXM) and Service Module. ")
function_module_reset_reason = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18))).clone(namedValues=named_values(('powerUp', 1), ('parityError', 2), ('watchDog', 3), ('resourceOverflow', 4), ('clrAllCnf', 5), ('missingTask', 6), ('pxmLowVoltage', 7), ('resetByEventLogTask', 8), ('resetFromShell', 9), ('unknown', 10), ('resetFromPXM', 11), ('resetSys', 12), ('switchCC', 13), ('sCacheError', 14), ('swError', 15), ('upgrade', 16), ('restoreAllCnf', 17), ('driverError', 18)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
functionModuleResetReason.setStatus('mandatory')
if mibBuilder.loadTexts:
functionModuleResetReason.setDescription('Last reason for card to reset. The possible values are : powerUp(1) : power up parityError(2) : parity error watchDog(3) : watchdog resourceOverflow (4) : resource overflow clrAllCnf (5) : configuration of the shelf is cleared. missingTask (6) : task is missing pxmLowVoltage(7): low voltage detected on PXM resetByEventLogTask(8): resetFromShell(9): command is run from command shell unknown(10) : resetFromPXM(11) : Controller Card(PXM) reset the card. resetSys(12) : due to resetsys CLI Command. switchCC(13) : due to switch over CLI command. sCacheError(14) : swError(15) : software error. upgrade(16) : upgrade restoreAllCnf(17): restore configuration. driverError(18) : driver error. Valid values for VISM: powerUp, watchDog, resetFromShell and resetFromPXM. ')
line_module_type = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 48, 49, 50, 51, 60, 61, 62, 63, 70, 71, 80, 81, 500, 501, 502, 503, 504, 505, 506, 507, 511, 512, 513, 514, 515, 1006, 1050, 1051, 1052))).clone(namedValues=named_values(('other', 1), ('lm-ASC', 2), ('lm-DB15-4T1', 16), ('lm-DB15-4E1', 17), ('lm-BNC-4E1', 18), ('lm-DB15-4T1-R', 19), ('lm-DB15-4E1-R', 20), ('lm-BNC-4E1-R', 21), ('lm-RJ48-8T1', 22), ('lm-RJ48-8E1', 23), ('lm-SMB-8E1', 24), ('lm-RJ48-T3T1', 25), ('lm-RJ48-E3E1', 26), ('lm-RJ48-T3E1', 27), ('lm-SMB-E3E1', 28), ('lm-RJ48-E3T1', 29), ('lm-SMB-T3E1', 30), ('lm-T3E3-D', 32), ('lm-T3E3-B', 33), ('lm-155-SMF', 34), ('lm-155-UTP', 35), ('lm-RJ48-8T1-R', 48), ('lm-RJ48-8E1-R', 49), ('lm-SMB-8E1-R', 50), ('lm-3T3-B', 51), ('lm-HS1-4X21', 60), ('lm-HS1-3HSSI', 61), ('lm-HS1-4V35', 62), ('lm-12In1-8s', 63), ('lm-BSCSM-2', 70), ('lm-BSCSM-4', 71), ('lm-BNC-2T3', 80), ('lm-BNC-2E3', 81), ('pxm-ui', 500), ('smfir-1-622', 501), ('smflr-1-622', 502), ('smfir15-1-622', 503), ('smflr15-1-622', 504), ('mmf-4-155', 505), ('smfir-4-155', 506), ('smflr-4-155', 507), ('rj45-fe', 511), ('mmf-fe', 512), ('mmf-fddi', 513), ('smf-fddi', 514), ('rj45-4e', 515), ('pxm-ui-s3', 1006), ('lm-srme-1OC3-smlr', 1050), ('lm-srme-1OC3-smir', 1051), ('lm-srme-1OC3-smb', 1052))).clone('other')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lineModuleType.setStatus('mandatory')
if mibBuilder.loadTexts:
lineModuleType.setDescription('This object contains the Line Module(back card) type. Physically it is behind the backplane, normally with connectors for physical devices. These are specific to the front or functional modules. ')
line_module_description = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 10), display_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lineModuleDescription.setStatus('mandatory')
if mibBuilder.loadTexts:
lineModuleDescription.setDescription('This object contains description of the line module.')
line_module_serial_num = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 11), display_string().subtype(subtypeSpec=value_size_constraint(0, 11))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lineModuleSerialNum.setStatus('mandatory')
if mibBuilder.loadTexts:
lineModuleSerialNum.setDescription('This object contains Serial number of the line module.')
line_module_hw_rev = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 12), display_string().subtype(subtypeSpec=value_size_constraint(0, 2))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lineModuleHWRev.setStatus('mandatory')
if mibBuilder.loadTexts:
lineModuleHWRev.setDescription('This object contains Hardware revision for line module.')
line_module_fw_rev = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 13), display_string().subtype(subtypeSpec=value_size_constraint(0, 8))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lineModuleFWRev.setStatus('mandatory')
if mibBuilder.loadTexts:
lineModuleFWRev.setDescription('Firmware revision for line module. The current version does not have any firmware, hence will always contains zero length octet string.')
line_module_state = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('notPresent', 1), ('present', 2), ('invalid', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
lineModuleState.setStatus('mandatory')
if mibBuilder.loadTexts:
lineModuleState.setDescription('line module status.')
module_trap_alarm_severity = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 15), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=named_values(('minor', 1), ('major', 2), ('dontCare', 3), ('critical', 4), ('error', 5), ('warning', 6), ('notice', 7), ('info', 8)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
moduleTrapAlarmSeverity.setStatus('mandatory')
if mibBuilder.loadTexts:
moduleTrapAlarmSeverity.setDescription('This object is sent to managers as part of all Trap PDUs, to determine the module alarm severity. An implementation may not support all the possible values. The Possible values are : major (1) : Major Service has been impacted minor (2) : Minor Service has been lost dontCare (3) : severity is not applicable critical (4) : affects existing data traffic error (5) : error has occurred warning (6) : a threshold has been reached notice (7) : a normal but significant event has occurred info (8) : informational ')
mib_version_number = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 16), integer32().clone(2)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mibVersionNumber.setStatus('mandatory')
if mibBuilder.loadTexts:
mibVersionNumber.setDescription('MIB version number. Updated when any part of the MIB changes. ')
config_change_type_bit_map = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 17), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
configChangeTypeBitMap.setStatus('mandatory')
if mibBuilder.loadTexts:
configChangeTypeBitMap.setDescription('Configuration change Type BitMap bit 0 set = Card Configuration Change bit 1 set = Line Configuration Change bit 2 set = Port Configuration Change bit 3 set = Chan Configuration Change bit 4 set = STUN protocol group configuration Change bit 5 set = STUN port configuration Change bit 6 set = STUN route configuration Change bit 7 set = BSTUN protocol configuration Change bit 8 set = BSTUN port configuration Change bit 9 set = BSTUN route configuration Change bit 10 set = FRASBNN route configuration Change bit 11 set = FRASBAN route configuration Change bit 12 set = SDLC port configuration Change bit 13 set = SDLC LS configuration Change bit 14 set = BSC port configuration Change bit 15 set = LLC port configuration Change bit 16 set = card LCN partition change (controller based only) bit 17 set = port resource partition change (under any partition type) bit 18 set = VISM Endpoint Configuration Change bit 19 set = Egress Q configuration change default value is 0, no change This object makes sense only in traps. A GET on this may not return a Useful result. Bit 19 is not applicable for MGX 8850 Release 1.x.x and MGX 8220 ')
config_change_object_index = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 18), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
configChangeObjectIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
configChangeObjectIndex.setDescription("Configuration change object index, could be line number or port number or channel number depends on the type bitmap, for port resouce partition change (bit 17), this index is actually constructed by (portNum << 16 | controller) because the table has two indices. When the 'Line Configuration Change' bit is set, the configChangeObjectIndex has the following special meanings in IMATM and FRSM-2CT3 cards: IMATM - configChangeObjectIndex range between 1..8 indicates that the configuration change refers to the DS1 line index. A value of 9 indicates that the configuration change refers to the DS3 line index. FRSM-2CT3 - configChangeObjectIndex range between 1..56 indicates that the configuration change refers to the DS1 line index. A value of (128 + n) refers to DS3 line index numbered 'n'. This object makes sense only in traps. A GET on this may not return a Useful result. ")
config_change_status = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 19), integer32().subtype(subtypeSpec=value_range_constraint(0, 3))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
configChangeStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
configChangeStatus.setDescription('This object is applicable only for traps. The SNMP operation may not be meaningful. The value contained in this object is same as the value of the other objects which are used for adding/deleting/modifying the row. The possible values are 0 - No meaning and is not applicable. 1 - add [ Row added ] 2 - delete [ Row deleted ] 3 - mod [ Row modified ] This value and value contained in configChangeTypeBitMap represent the configuration change operation. The default value is 0 and it does not represent any status.')
card_integrated_alarm_bit_map = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 20), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cardIntegratedAlarmBitMap.setStatus('mandatory')
if mibBuilder.loadTexts:
cardIntegratedAlarmBitMap.setDescription('Bit position represents the different types of alarm for ASC: bit 0: ShelfFunctionModuleState (BNM only) (failed/boot/mismatch/heldinReset) bit 1: LineModuleState (BNM only) (notPresent/invalid) bit 2: ASMPhysicalAlarmState (BNM only) bit 3: ATMLMIFailure (ASC only) bit 4: LineAlarmState (BNM only) bit 5: LineStatisticalAlarmState (BNM only) bit 6: PLCPAlarmState (BNM only) bit 7: PLCPStatisticalAlarmState (BNM only) bit 8: SmConnectionFailureAlarm for SM: bit 0: ShelfFunctionModuleState (failed/boot/mismatch/heldinReset) bit 1: LineModuleState (notPresent/invalid) bit 2: PortLMIFailure bit 3: LineAlarmState bit 4: LineStatisticalAlarmState bit 5: FrameRelayPortState (RemoteLoopback/ FailedDueToLine/ FailedDueToSig) bit 6: ChannelState for PXM/SRM Only (MGX8850 Platfrom): Only those marked with SRM are valid for both PXM/SRM. The rest are valid only for PXM. bit 0 : ShelfFunctionModuleState bit 1 : Backcard Line Module (SRM/PXM) This Alarm is generated when the Line Module (Trunk Backcard) is removed or goes to a mismatch state(or backcard type is unknown). bit 2 : Backcard UIModule This Alarm is generated when the UI backcard is removed or goes to a mismatch state (or backcard type is unknown). bit 3 : ASM Physical Alarm This specifies whether any of the environmental monitoring components like Temperature, Voltage Supply, Fan Speed have gone into alarm. bit 4 : ATM LMI Failure bit 5 : Line Alarm (SRM/PXM) bit 6 : Line Statistical Alarm (SRM/PXM) bit 7 : Lines Alarm (SRM/PXM) bit 8 : PLCP Alarm bit 9 : PLCP Statistical Alarm bit 10 : Connections exist on removed SM bit 11 : Disk related Failure on first PXM slot bit 12 : Disk related Failure on second PXM slot The Disk Alarms are generated when any of the file operations on Disk like open,read,write, lseek etc fail. VSM Alarms bit 13 : Port LMI Failure bit 14 : Port State Alarm bit 15 : Channel Shelf Alarm bit 16 : Taskmon Task Suspended bit 17 : Excess Power Consumption bit 30 : bit set(1) major alarm, else (0) minor alarm ')
clei_code = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 21), display_string().subtype(subtypeSpec=value_size_constraint(0, 10))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
cleiCode.setStatus('mandatory')
if mibBuilder.loadTexts:
cleiCode.setDescription('Common Language Equipment(CLEI) Code. ')
mac_address = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 22), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
macAddress.setStatus('mandatory')
if mibBuilder.loadTexts:
macAddress.setDescription('Ethernet address (base address) stored in NVRAM, entered by manfacturing. ')
mac_addr_blk_size = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 23), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
macAddrBlkSize.setStatus('mandatory')
if mibBuilder.loadTexts:
macAddrBlkSize.setDescription('The MAC address block size, entered by manufacturing. ')
final_test_technician = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 24), display_string().subtype(subtypeSpec=value_size_constraint(0, 6))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
finalTestTechnician.setStatus('mandatory')
if mibBuilder.loadTexts:
finalTestTechnician.setDescription('The Final Test Technician Employee Identification Number. ')
hw_failures = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 25), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hwFailures.setStatus('mandatory')
if mibBuilder.loadTexts:
hwFailures.setDescription('Hardware failure code.')
hw_history = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 26), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hwHistory.setStatus('mandatory')
if mibBuilder.loadTexts:
hwHistory.setDescription('RMA Test History - RMA Failure Code.')
sec_line_module_type = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 27), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 48, 49, 50, 51, 60, 61, 62, 63, 70, 71, 80, 81, 500, 501, 502, 503, 504, 505, 506, 507, 511, 512, 513, 514, 515, 1006))).clone(namedValues=named_values(('other', 1), ('lm-ASC', 2), ('lm-DB15-4T1', 16), ('lm-DB15-4E1', 17), ('lm-BNC-4E1', 18), ('lm-DB15-4T1-R', 19), ('lm-DB15-4E1-R', 20), ('lm-BNC-4E1-R', 21), ('lm-RJ48-8T1', 22), ('lm-RJ48-8E1', 23), ('lm-SMB-8E1', 24), ('lm-RJ48-T3T1', 25), ('lm-RJ48-E3E1', 26), ('lm-RJ48-T3E1', 27), ('lm-SMB-E3E1', 28), ('lm-RJ48-E3T1', 29), ('lm-SMB-T3E1', 30), ('lm-T3E3-D', 32), ('lm-T3E3-B', 33), ('lm-155-SMF', 34), ('lm-155-UTP', 35), ('lm-RJ48-8T1-R', 48), ('lm-RJ48-8E1-R', 49), ('lm-SMB-8E1-R', 50), ('lm-3T3-B', 51), ('lm-HS1-4X21', 60), ('lm-HS1-3HSSI', 61), ('lm-HS1-4V35', 62), ('lm-12In1-8s', 63), ('lm-BSCSM-2', 70), ('lm-BSCSM-4', 71), ('lm-BNC-2T3', 80), ('lm-BNC-2E3', 81), ('pxm-ui', 500), ('smfir-1-622', 501), ('smflr-1-622', 502), ('smfir15-1-622', 503), ('smflr15-1-622', 504), ('mmf-4-155', 505), ('smfir-4-155', 506), ('smflr-4-155', 507), ('rj45-fe', 511), ('mmf-fe', 512), ('mmf-fddi', 513), ('smf-fddi', 514), ('rj45-4e', 515), ('pxm-ui-s3', 1006))).clone('other')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
secLineModuleType.setStatus('mandatory')
if mibBuilder.loadTexts:
secLineModuleType.setDescription('This object contains the type of secondary line module(back card). Physically it is the bottom card behind the backplane. Normally with connectors for physical devices. These are specific to the front or function modules. This Object is applicable only to selected MGX switches. ')
sec_line_module_description = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 28), display_string().subtype(subtypeSpec=value_size_constraint(0, 20))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
secLineModuleDescription.setStatus('mandatory')
if mibBuilder.loadTexts:
secLineModuleDescription.setDescription('Description of the Secondary line module. This Object is applicable only to selected MGX switches. ')
sec_line_module_serial_num = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 29), display_string().subtype(subtypeSpec=value_size_constraint(0, 11))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
secLineModuleSerialNum.setStatus('mandatory')
if mibBuilder.loadTexts:
secLineModuleSerialNum.setDescription('Serial number of the secondary(bottom) line module. This object is applicable only to selected MGX switches. ')
sec_line_module_hw_rev = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 30), display_string().subtype(subtypeSpec=value_size_constraint(0, 2))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
secLineModuleHWRev.setStatus('mandatory')
if mibBuilder.loadTexts:
secLineModuleHWRev.setDescription('Hardware revision for secondary (bottom) line module This object is applicable only to selected MGX switches. ')
sec_line_module_fw_rev = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 31), display_string().subtype(subtypeSpec=value_size_constraint(0, 8))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
secLineModuleFWRev.setStatus('mandatory')
if mibBuilder.loadTexts:
secLineModuleFWRev.setDescription('Firmware revision for Secondary line module This object is applicable only to selected MGX switches. If there is no Firmware revision, then this object returns 0. ')
sec_line_module_state = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 32), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('notPresent', 1), ('present', 2), ('invalid', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
secLineModuleState.setStatus('mandatory')
if mibBuilder.loadTexts:
secLineModuleState.setDescription('line module status of secondary (bottom) back card. This object is applicable only to selected MGX switches.')
config_change_parent_object_index = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 33), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
configChangeParentObjectIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
configChangeParentObjectIndex.setDescription(" Parent object index, could be - line index - port index This object will indicate the index of the immediate higher level object (line or port) of configChangeObjectIndex. This object is applicable only when configChangeObjectIndex represents a channel, port, egress Q or resource partition index. Following specifies the mapping between the configChangeObjectIndex and its corresponding configChangeParentObjectIndex. configChangeObjectIndex configChangeParentObjectIndex ----------------------- ----------------------------- Port Index Line Index Egress Q Index Port Index Resource Partition Index Port Index Channel Index Port Index When the 'Port Configuration Change' bit is set, the configChangeParentObjectIndex will represent a 'Line Index' which in turn has the following special meaning in FRSM-2CT3 cards. - configChangeParentObjectIndex range between 1..56 indicates that the configuration change refers to the DS1 line index. A value of (128 + n) refers to DS3 line index numbered 'n'. This object object is applicable only in traps. A GET on this may not return a useful result. This object Object is not applicable to MGX 8850 Release 1.x.x and MGX8220 ")
config_change_grand_parent_object_index = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 34), integer32().subtype(subtypeSpec=value_range_constraint(1, 1024))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
configChangeGrandParentObjectIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
configChangeGrandParentObjectIndex.setDescription(" Grand Parent object index, could be - line index This object will indicate the index of the immediate higher level object (line) of configChangeParentObjectIndex. This object is applicable only when configChangeParentObjectIndex represents a port index. Following specifies the mapping between the configChangeParentObjectIndex and its corresponding configChangeGrandParentObjectIndex. When the 'Port Configuration Change' bit is set the configChangeGrandParentObjectIndex will represent a 'Line Index' which in turn has the following special meaning in FRSM-2CT3 cards. - configChangeParentObjectIndex range between 1..56 indicates that the configuration change refers to the DS1 line index. A value of (128 + n) refers to DS3 line index numbered 'n'. This object is applicable only in traps. A GET on this may not return a useful result. This object is not applicable to MGX 8850 release 1.x.x and MGX8220.")
config_change_sm_specific_object = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 35), integer32().subtype(subtypeSpec=value_range_constraint(0, 16777215))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
configChangeSMSpecificObject.setStatus('mandatory')
if mibBuilder.loadTexts:
configChangeSMSpecificObject.setDescription(' configChangeSMSpecificObject is a generic object which is Service Module Specific. It can be used for different purposes in different cards. The usage of the same with regard to very card type is listed below. FRSM-8T1E1 - used to store portDs0ConfigBitMap FRSM-VHS - used to store portDs0ConfigBitMap CESM-8T1E1 - used to store cesPortDs0ConfigBitMap CESM-T3E3 - not used AUSM-8T1E1 - not used This object is not applicable to MGX 8850 Release 1.x.x and MGX8220.')
trans_id = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 1, 36), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
transId.setStatus('mandatory')
if mibBuilder.loadTexts:
transId.setDescription('Per card transaction ID. This object is used to keep track of configuration change on the card. The transId will be incremented by one for every configuration change on the card.')
interface_num_of_valid_entries = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
interfaceNumOfValidEntries.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceNumOfValidEntries.setDescription('Number of rows in interface Table The number represents the physcial interfaces the module has. ')
interface_line_table = mib_table((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1))
if mibBuilder.loadTexts:
interfaceLineTable.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceLineTable.setDescription('This table has list of the physical interfaces and the services available on this module. ')
interface_line_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1)).setIndexNames((0, 'BASIS-GENERIC-MIB', 'interfaceLineNum'))
if mibBuilder.loadTexts:
interfaceLineEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceLineEntry.setDescription('An entry for physical interface ')
interface_line_num = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 10))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
interfaceLineNum.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceLineNum.setDescription('An index to uniquely indentify the physical interface and service. Indices 1..8 are used for VISM-8T1/E1. ')
interface_line_type = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 18, 19, 26, 30, 33, 45, 46))).clone(namedValues=named_values(('other', 1), ('ds1', 18), ('e1', 19), ('ethernet-3Mbit', 26), ('ds3', 30), ('rs232', 33), ('v35', 45), ('hssi', 46)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
interfaceLineType.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceLineType.setDescription('This object indicates the type of interfaces provided by this Module. These numbers are from RFC1700.')
interface_num_of_ports_per_line = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 65535)).clone(672)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
interfaceNumOfPortsPerLine.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceNumOfPortsPerLine.setDescription('The number of physical ports of the line type. VISM has a port, but is not linked to these physical lines, hence value=0 is returned. ')
interface_service_type = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 26, 28, 32, 37, 42))).clone(namedValues=named_values(('other', 1), ('ethernet-3Mbit', 26), ('slip', 28), ('frameRelay', 32), ('atm', 37), ('voice', 42)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
interfaceServiceType.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceServiceType.setDescription('The services available on the interfaceLineType object ')
interface_num_of_pvc = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 5), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
interfaceNumOfPVC.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceNumOfPVC.setDescription('The Max number of Permanent Virtual Channels available per physical line (line as defined in interfaceLineType). VISM has a PVC but is not linked to the lines, hence value=0 is returned. ')
interface_num_of_egress_queue = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 2, 1, 1, 6), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
interfaceNumOfEgressQueue.setStatus('mandatory')
if mibBuilder.loadTexts:
interfaceNumOfEgressQueue.setDescription('The Max number of Queues per port. Value=0 is returned for VISM card. ')
self_test_enable = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disable', 1), ('enable', 2))).clone('disable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
selfTestEnable.setStatus('mandatory')
if mibBuilder.loadTexts:
selfTestEnable.setDescription('This object indicates the self test state 1 ==> self test enabled 2 ==> self test disabled ')
self_test_period = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 60)).clone(1)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
selfTestPeriod.setStatus('mandatory')
if mibBuilder.loadTexts:
selfTestPeriod.setDescription('Interval (in minutes) for self test. ')
self_test_state = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('passed', 1), ('failed', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
selfTestState.setStatus('mandatory')
if mibBuilder.loadTexts:
selfTestState.setDescription('Self test results for the module. ')
self_test_result_description = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 40))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
selfTestResultDescription.setStatus('mandatory')
if mibBuilder.loadTexts:
selfTestResultDescription.setDescription('Self test Result description ')
self_test_clr_result_button = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 3, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('other', 1), ('clear', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
selfTestClrResultButton.setStatus('mandatory')
if mibBuilder.loadTexts:
selfTestClrResultButton.setDescription('This object is used for clearing the result of an online diagnostics(or other self tests).')
control_msg_counter = mib_identifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 4))
risc_xmt_ctrl_msg = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
riscXmtCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts:
riscXmtCtrlMsg.setDescription('The number of control Frames transmitted to SAR (from RISC) maintained by RISC ')
risc_rcv_ctrl_msg = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
riscRcvCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts:
riscRcvCtrlMsg.setDescription('The number of control Frames received from SAR (to RISC) maintained by RISC ')
sar_xmt_ctrl_msg = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarXmtCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts:
sarXmtCtrlMsg.setDescription('The number of control Frames transmitted to RISC from SAR maintained by SAR (should be equal to (riscRcvCtrlMsg) ')
sar_rcv_ctrl_msg = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarRcvCtrlMsg.setStatus('mandatory')
if mibBuilder.loadTexts:
sarRcvCtrlMsg.setDescription('The number of control Frames received to SAR from RISC maintained by SAR (should be equal to (riscXmtCtrlMsg) ')
sar_ctrl_msg_disc_len_err = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarCtrlMsgDiscLenErr.setStatus('mandatory')
if mibBuilder.loadTexts:
sarCtrlMsgDiscLenErr.setDescription('Total control (management) frames (for MGX8800) or cells(for MGX8220) discarded due to illegal length error ')
sar_ctrl_msg_disc_crc_err = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarCtrlMsgDiscCRCErr.setStatus('mandatory')
if mibBuilder.loadTexts:
sarCtrlMsgDiscCRCErr.setDescription('Total control (management) frames (MGX8800) or cells(MGX8220) discard due to illegal CRC error. ')
sar_ctrl_msg_disc_unknown_chan = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarCtrlMsgDiscUnknownChan.setStatus('mandatory')
if mibBuilder.loadTexts:
sarCtrlMsgDiscUnknownChan.setDescription('Count of discarded control message due to unknown channel error.')
sar_ctrl_msg_last_unkown_chan = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 8), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarCtrlMsgLastUnkownChan.setStatus('mandatory')
if mibBuilder.loadTexts:
sarCtrlMsgLastUnkownChan.setDescription('The control cell header Rcvd of the last unknown channel.')
ctrl_msg_clr_button = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 4, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('other', 1), ('clear', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ctrlMsgClrButton.setStatus('mandatory')
if mibBuilder.loadTexts:
ctrlMsgClrButton.setDescription('This object is used for clearing the messages in controlMsgCounter group.')
sar_channel_counter = mib_identifier((1, 3, 6, 1, 4, 1, 351, 110, 2, 5))
chan_num_of_valid_entries = mib_scalar((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
chanNumOfValidEntries.setStatus('mandatory')
if mibBuilder.loadTexts:
chanNumOfValidEntries.setDescription('Number of entries in the sar channel table ')
sar_channel_counter_table = mib_table((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1))
if mibBuilder.loadTexts:
sarChannelCounterTable.setStatus('mandatory')
if mibBuilder.loadTexts:
sarChannelCounterTable.setDescription('The table is for logical channels This table contains the counters for cells transmitted on each channel.')
sar_channel_counter_entry = mib_table_row((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1)).setIndexNames((0, 'BASIS-GENERIC-MIB', 'sarShelfNum'), (0, 'BASIS-GENERIC-MIB', 'sarSlotNum'), (0, 'BASIS-GENERIC-MIB', 'sarChanNum'))
if mibBuilder.loadTexts:
sarChannelCounterEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
sarChannelCounterEntry.setDescription(' An entry for logical channel ')
sar_shelf_num = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 4))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarShelfNum.setStatus('mandatory')
if mibBuilder.loadTexts:
sarShelfNum.setDescription('Shelf number ')
sar_slot_num = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 16))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarSlotNum.setStatus('mandatory')
if mibBuilder.loadTexts:
sarSlotNum.setDescription('Slot number, the slot and shelf info is required here because BSC sends the OAM cells for the FRSM cards that have failed BSC could have upto 4000 connections in this table.')
sar_chan_num = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 4015))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
sarChanNum.setStatus('mandatory')
if mibBuilder.loadTexts:
sarChanNum.setDescription(' BSC could have upto 4000 connections in this table ')
xmt_cells = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCells.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCells.setDescription('The number of cells transmitted on this channel. ')
xmt_cells_clp = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCellsCLP.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCellsCLP.setDescription('The total number of CLP cells that were transmitted on this channel.')
xmt_cells_ais = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCellsAIS.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCellsAIS.setDescription('The number of AIS cells that were transmitted on this channel. ')
xmt_cells_ferf = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCellsFERF.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCellsFERF.setDescription('The number of FERF cells that were transmitted on this channel. ')
xmt_cells_bcm = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCellsBCM.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCellsBCM.setDescription('The number of BCM cells that were transmitted on this channel.')
xmt_cells_end2_end_lp_bk = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCellsEnd2EndLpBk.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCellsEnd2EndLpBk.setDescription('The number of End2End loop cells that were transmitted on this channel.')
xmt_cells_segment_lp_bk = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCellsSegmentLpBk.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCellsSegmentLpBk.setDescription('The number of segment loop cells that were transmitted on this channel.')
xmt_cells_disc_shelf_alarm = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
xmtCellsDiscShelfAlarm.setStatus('mandatory')
if mibBuilder.loadTexts:
xmtCellsDiscShelfAlarm.setDescription('The number of cells discard due to Shelfalarm on this channel. ')
rcv_cells = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 12), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCells.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCells.setDescription('The number of cells that were received on this channel. ')
rcv_cells_clp = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 13), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCellsCLP.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCellsCLP.setDescription('The number of CLP cells that were received on this channel. ')
rcv_cells_ais = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 14), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCellsAIS.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCellsAIS.setDescription('The number of AIS cells that were received on this channel. ')
rcv_cells_ferf = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 15), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCellsFERF.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCellsFERF.setDescription('The number of FERF cells that were received on this channel. ')
rcv_cells_bcm = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 16), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCellsBCM.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCellsBCM.setDescription('The number of BCM cells that were received on this channel. ')
rcv_cells_end2_end_lp_bk = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 17), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCellsEnd2EndLpBk.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCellsEnd2EndLpBk.setDescription('The number of End2End loop cells that were received on this channel.')
rcv_cells_segment_lp_bk = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 18), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCellsSegmentLpBk.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCellsSegmentLpBk.setDescription('The number of segment loop cells that were received on this channel. ')
rcv_cells_disc_oam = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 19), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rcvCellsDiscOAM.setStatus('mandatory')
if mibBuilder.loadTexts:
rcvCellsDiscOAM.setDescription('The number of cells that had CRC error on OAM cells ')
sar_clr_button = mib_table_column((1, 3, 6, 1, 4, 1, 351, 110, 2, 5, 1, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('other', 1), ('clear', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
sarClrButton.setStatus('mandatory')
if mibBuilder.loadTexts:
sarClrButton.setDescription('clear the counters in the table ')
mibBuilder.exportSymbols('BASIS-GENERIC-MIB', configChangeObjectIndex=configChangeObjectIndex, functionModuleFWRev=functionModuleFWRev, interfaceLineNum=interfaceLineNum, cardSelfTest=cardSelfTest, rcvCellsCLP=rcvCellsCLP, sarCtrlMsgDiscLenErr=sarCtrlMsgDiscLenErr, ctrlMsgClrButton=ctrlMsgClrButton, xmtCellsSegmentLpBk=xmtCellsSegmentLpBk, macAddrBlkSize=macAddrBlkSize, interfaceNumOfEgressQueue=interfaceNumOfEgressQueue, moduleTrapAlarmSeverity=moduleTrapAlarmSeverity, chanNumOfValidEntries=chanNumOfValidEntries, interfaceLineType=interfaceLineType, interfaceServiceType=interfaceServiceType, interfaceNumOfPortsPerLine=interfaceNumOfPortsPerLine, lineModuleDescription=lineModuleDescription, lineModuleFWRev=lineModuleFWRev, secLineModuleSerialNum=secLineModuleSerialNum, xmtCellsAIS=xmtCellsAIS, xmtCellsEnd2EndLpBk=xmtCellsEnd2EndLpBk, selfTestResultDescription=selfTestResultDescription, sarSlotNum=sarSlotNum, functionModuleState=functionModuleState, selfTestEnable=selfTestEnable, functionModuleDescription=functionModuleDescription, interfaceLineTable=interfaceLineTable, sarChannelCounterEntry=sarChannelCounterEntry, selfTestPeriod=selfTestPeriod, sarChanNum=sarChanNum, rcvCellsDiscOAM=rcvCellsDiscOAM, sarCtrlMsgDiscUnknownChan=sarCtrlMsgDiscUnknownChan, sarRcvCtrlMsg=sarRcvCtrlMsg, riscXmtCtrlMsg=riscXmtCtrlMsg, functionModuleSerialNum=functionModuleSerialNum, configChangeGrandParentObjectIndex=configChangeGrandParentObjectIndex, xmtCellsCLP=xmtCellsCLP, lineModuleHWRev=lineModuleHWRev, selfTestClrResultButton=selfTestClrResultButton, hwHistory=hwHistory, xmtCells=xmtCells, functionModuleType=functionModuleType, functionModuleResetReason=functionModuleResetReason, selfTestState=selfTestState, xmtCellsBCM=xmtCellsBCM, secLineModuleHWRev=secLineModuleHWRev, interfaceNumOfPVC=interfaceNumOfPVC, rcvCellsEnd2EndLpBk=rcvCellsEnd2EndLpBk, secLineModuleFWRev=secLineModuleFWRev, rcvCells=rcvCells, sarXmtCtrlMsg=sarXmtCtrlMsg, riscRcvCtrlMsg=riscRcvCtrlMsg, cardInformation=cardInformation, controlMsgCounter=controlMsgCounter, sarChannelCounter=sarChannelCounter, configChangeStatus=configChangeStatus, rcvCellsSegmentLpBk=rcvCellsSegmentLpBk, rcvCellsBCM=rcvCellsBCM, cleiCode=cleiCode, secLineModuleState=secLineModuleState, mibVersionNumber=mibVersionNumber, sarCtrlMsgLastUnkownChan=sarCtrlMsgLastUnkownChan, secLineModuleType=secLineModuleType, configChangeParentObjectIndex=configChangeParentObjectIndex, transId=transId, lineModuleState=lineModuleState, rcvCellsFERF=rcvCellsFERF, sarChannelCounterTable=sarChannelCounterTable, functionModuleHWRev=functionModuleHWRev, hwFailures=hwFailures, configChangeSMSpecificObject=configChangeSMSpecificObject, xmtCellsDiscShelfAlarm=xmtCellsDiscShelfAlarm, configChangeTypeBitMap=configChangeTypeBitMap, lineModuleType=lineModuleType, interfaceNumOfValidEntries=interfaceNumOfValidEntries, interfaceLineEntry=interfaceLineEntry, cardInterface=cardInterface, sarClrButton=sarClrButton, lineModuleSerialNum=lineModuleSerialNum, macAddress=macAddress, cardIntegratedAlarmBitMap=cardIntegratedAlarmBitMap, sarCtrlMsgDiscCRCErr=sarCtrlMsgDiscCRCErr, rcvCellsAIS=rcvCellsAIS, sarShelfNum=sarShelfNum, moduleSlotNumber=moduleSlotNumber, secLineModuleDescription=secLineModuleDescription, xmtCellsFERF=xmtCellsFERF, finalTestTechnician=finalTestTechnician) |
# -*- coding: utf-8 -*-
"""
In this module will be defined all constanst about Beauty & Pics
"""
class project_constants(object):
# contest status {{{
CONTEST_OPENING = "opening"
CONTEST_ACTIVE = "active"
CONTEST_CLOSED = "closed"
# contest status }}}
# contest types {{{
MAN_CONTEST = "man-contest"
WOMAN_CONTEST = "woman-contest"
# contest types }}}
# account gender {{{
MAN_GENDER = "man"
WOMAN_GENDER = "woman"
# account gender }}}
# prize consts {{{
PRIZE_CANNOT_BE_REDEEMED = 0
PRIZE_CAN_BE_REDEEMED = 1
PRIZE_ALREADY_REDEEMED = 2
# prize consts }}}
# contest details {{{
# see here -> http://www.epochconverter.com/epoch/daynumbers.php
# CONTEST_OPENING_DAYS = 35
# XXX: debug, use this instead --^
CONTEST_OPENING_DAYS = 30
CONTEST_EXPIRING_DAYS = 165
# contest details }}}
# catwalk user group name
CATWALK_GROUP_NAME = "catwalk_user"
# votations {{{
# vote seconds min limit
SECONDS_BETWEEN_VOTATION = 604800 # 604800 seconds = 7 days
VOTE_METRICS_LIST = {"smile_metric": "smile", "look_metric": "look", "global_metric": "global", "style_metric": "style"}
IMAGE_TYPE = {"profile": "profile_image", "book": "book_image"}
# votations }}}
# newsletters bitmask {{{
WEEKLY_REPORT_EMAIL_BITMASK = 1
CONTEST_REPORT_EMAIL_BITMASK = 2
SITE_NAME = "Beauty and Pics"
# cookie naming: _bp_firstletter_
USER_ALREADY_VOTED_COOKIE_NAME = "_uav_"
USER_NOTIFY_POPUP_SHOWN_COOKIE_NAME = "_bp_unpsk_"
USER_NOTIFY_POPUP_SHOWN_COOKIE_EXPIRING_SECONDS = 60*60 # cookie expiring in seconds (60s * 60m = 1 hour)
# newsletters bitmask }}}
| """
In this module will be defined all constanst about Beauty & Pics
"""
class Project_Constants(object):
contest_opening = 'opening'
contest_active = 'active'
contest_closed = 'closed'
man_contest = 'man-contest'
woman_contest = 'woman-contest'
man_gender = 'man'
woman_gender = 'woman'
prize_cannot_be_redeemed = 0
prize_can_be_redeemed = 1
prize_already_redeemed = 2
contest_opening_days = 30
contest_expiring_days = 165
catwalk_group_name = 'catwalk_user'
seconds_between_votation = 604800
vote_metrics_list = {'smile_metric': 'smile', 'look_metric': 'look', 'global_metric': 'global', 'style_metric': 'style'}
image_type = {'profile': 'profile_image', 'book': 'book_image'}
weekly_report_email_bitmask = 1
contest_report_email_bitmask = 2
site_name = 'Beauty and Pics'
user_already_voted_cookie_name = '_uav_'
user_notify_popup_shown_cookie_name = '_bp_unpsk_'
user_notify_popup_shown_cookie_expiring_seconds = 60 * 60 |
def sort_012(input_arr):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Time Complexity O(n)
Space Complexity O(n)
Where n is the array size.
Args:
input_arr(array): Array to be sorted
Returns:
sorted_arr(array): Sorted array
"""
# Test that input_arr consists of digits between 0 and 9
for element in input_arr:
if element < 0 or element > 2:
return (-1, -1)
bin_zeros = []
bin_ones = []
bin_twos = []
for element in input_arr:
if element == 0:
bin_zeros.append(element)
elif element == 1:
bin_ones.append(element)
elif element == 2:
bin_twos.append(element)
sorted_arr = bin_zeros + bin_ones + bin_twos
return sorted_arr
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print("Pass")
else:
print("Fail")
def test_function_edge(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == (-1, -1):
print("Pass")
else:
print("Fail")
print ("=== Test cases ===:")
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
print ("=== Edge test cases ===:")
# test that -1 will be returned for provided invalid input with not allowed value 3
test_function_edge([1, 2, 3])
# test that -1 will be returned for provided invalid input with not allowed negative values
test_function_edge([0, -1, -2]) | def sort_012(input_arr):
"""
Given an input array consisting on only 0, 1, and 2, sort the array in a single traversal.
Time Complexity O(n)
Space Complexity O(n)
Where n is the array size.
Args:
input_arr(array): Array to be sorted
Returns:
sorted_arr(array): Sorted array
"""
for element in input_arr:
if element < 0 or element > 2:
return (-1, -1)
bin_zeros = []
bin_ones = []
bin_twos = []
for element in input_arr:
if element == 0:
bin_zeros.append(element)
elif element == 1:
bin_ones.append(element)
elif element == 2:
bin_twos.append(element)
sorted_arr = bin_zeros + bin_ones + bin_twos
return sorted_arr
def test_function(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == sorted(test_case):
print('Pass')
else:
print('Fail')
def test_function_edge(test_case):
sorted_array = sort_012(test_case)
print(sorted_array)
if sorted_array == (-1, -1):
print('Pass')
else:
print('Fail')
print('=== Test cases ===:')
test_function([0, 0, 2, 2, 2, 1, 1, 1, 2, 0, 2])
test_function([2, 1, 2, 0, 0, 2, 1, 0, 1, 0, 0, 2, 2, 2, 1, 2, 0, 0, 0, 2, 1, 0, 2, 0, 0, 1])
test_function([0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])
print('=== Edge test cases ===:')
test_function_edge([1, 2, 3])
test_function_edge([0, -1, -2]) |
class Solution:
def XXX(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
temp = 0
for i in range(len(nums)):
if temp:
i -= temp
if nums[i] == 0:
nums.pop(i)
nums.insert(0, 0)
elif nums[i] == 2:
temp += 1
nums.pop(i)
nums.append(2)
| class Solution:
def xxx(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
temp = 0
for i in range(len(nums)):
if temp:
i -= temp
if nums[i] == 0:
nums.pop(i)
nums.insert(0, 0)
elif nums[i] == 2:
temp += 1
nums.pop(i)
nums.append(2) |
"""
#!/usr/bin/python
#Author: Suraj Patil
#Version: 2.0
#Date: 27th March 2014
input:
1. this is a dummy text
2. another dummy text
3. this is dummy
4. this is also dummy
output:
this is a dummy text
another dummy text
this is dummy
this is also dummy
"""
f = open('text', 'r')
f1= open('textModified', 'w')
i=0
lines = f.readlines()
for i in lines:
lines[i] = lines[1:]
f1.write(lines[i])
f.close()
f1.close()
| """
#!/usr/bin/python
#Author: Suraj Patil
#Version: 2.0
#Date: 27th March 2014
input:
1. this is a dummy text
2. another dummy text
3. this is dummy
4. this is also dummy
output:
this is a dummy text
another dummy text
this is dummy
this is also dummy
"""
f = open('text', 'r')
f1 = open('textModified', 'w')
i = 0
lines = f.readlines()
for i in lines:
lines[i] = lines[1:]
f1.write(lines[i])
f.close()
f1.close() |
class MinStack(object):
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append((x, min(self.getMin(), x)))
def pop(self):
self.stack.pop()
def top(self):
return self.stack[-1][0]
def getMin(self):
return self.stack[-1][1] if self.stack else float('inf')
| class Minstack(object):
def __init__(self):
self.stack = []
def push(self, x):
self.stack.append((x, min(self.getMin(), x)))
def pop(self):
self.stack.pop()
def top(self):
return self.stack[-1][0]
def get_min(self):
return self.stack[-1][1] if self.stack else float('inf') |
graph = {"A": ["B", "C"], "B": ["D", "E"], "C": ["F"], "D": [], "E": ["F"], "F": []}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
if __name__ == "__main__":
"""
from timeit import timeit
print(timeit(lambda: dfs(visited, graph, "A"), number=10000)) # 0.001466015000914922
"""
| graph = {'A': ['B', 'C'], 'B': ['D', 'E'], 'C': ['F'], 'D': [], 'E': ['F'], 'F': []}
visited = set()
def dfs(visited, graph, node):
if node not in visited:
print(node)
visited.add(node)
for neighbour in graph[node]:
dfs(visited, graph, neighbour)
if __name__ == '__main__':
'\n from timeit import timeit\n\n print(timeit(lambda: dfs(visited, graph, "A"), number=10000)) # 0.001466015000914922\n ' |
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
class Solution:
# @param intervals, a list of Intervals
# @param newInterval, a Interval
# @return a list of Interval
def insert(self, intervals, newInterval):
res = []
if len(intervals) == 0:
res.append(newInterval)
return res
# insert the new interval
intervals.append(newInterval)
# sort list according to the start value
intervals.sort(key=lambda x: x.start)
res.append(intervals[0])
# scan the list
for i in range(1, len(intervals)):
cur = intervals[i]
pre = res[-1]
# check if current interval intersects with previous one
if cur.start <= pre.end:
res[-1].end = max(pre.end, cur.end) # merge
else:
res.append(cur) # insert
return res
| class Solution:
def insert(self, intervals, newInterval):
res = []
if len(intervals) == 0:
res.append(newInterval)
return res
intervals.append(newInterval)
intervals.sort(key=lambda x: x.start)
res.append(intervals[0])
for i in range(1, len(intervals)):
cur = intervals[i]
pre = res[-1]
if cur.start <= pre.end:
res[-1].end = max(pre.end, cur.end)
else:
res.append(cur)
return res |
class dotIFC2X3_Application_t(object):
# no doc
ApplicationFullName=None
ApplicationIdentifier=None
Version=None
| class Dotifc2X3_Application_T(object):
application_full_name = None
application_identifier = None
version = None |
class LaunchAPIException(Exception):
def __init__(self, message, status_code):
super(Exception, self).__init__(message)
self.status_code = status_code
class ClientException(LaunchAPIException):
pass
| class Launchapiexception(Exception):
def __init__(self, message, status_code):
super(Exception, self).__init__(message)
self.status_code = status_code
class Clientexception(LaunchAPIException):
pass |
def main():
OnFwd(OUT_AB, 80)
TextOut(0, LCD_LINE1, 20)
Wait(2000)
| def main():
on_fwd(OUT_AB, 80)
text_out(0, LCD_LINE1, 20)
wait(2000) |
FreeMonoOblique9pt7bBitmaps = [
0x11, 0x22, 0x24, 0x40, 0x00, 0xC0, 0xDE, 0xE5, 0x29, 0x00, 0x09, 0x05,
0x02, 0x82, 0x47, 0xF8, 0xA0, 0x51, 0xFE, 0x28, 0x14, 0x0A, 0x09, 0x00,
0x08, 0x1D, 0x23, 0x40, 0x70, 0x1C, 0x02, 0x82, 0x84, 0x78, 0x20, 0x20,
0x1C, 0x11, 0x08, 0x83, 0x80, 0x18, 0x71, 0xC0, 0x1C, 0x11, 0x08, 0x83,
0x80, 0x1E, 0x60, 0x81, 0x03, 0x0A, 0x65, 0x46, 0x88, 0xE8, 0xFA, 0x80,
0x12, 0x24, 0x48, 0x88, 0x88, 0x88, 0x80, 0x01, 0x11, 0x11, 0x11, 0x22,
0x44, 0x80, 0x10, 0x22, 0x5B, 0xC3, 0x0A, 0x22, 0x00, 0x04, 0x02, 0x02,
0x1F, 0xF0, 0x80, 0x40, 0x20, 0x00, 0x36, 0x4C, 0x80, 0xFF, 0x80, 0xF0,
0x00, 0x80, 0x80, 0x40, 0x40, 0x40, 0x20, 0x20, 0x20, 0x10, 0x10, 0x10,
0x08, 0x08, 0x00, 0x1C, 0x45, 0x0A, 0x18, 0x30, 0x61, 0x42, 0x85, 0x11,
0xC0, 0x04, 0x38, 0x90, 0x20, 0x81, 0x02, 0x04, 0x08, 0x23, 0xF8, 0x07,
0x04, 0xC4, 0x20, 0x10, 0x10, 0x30, 0x20, 0x20, 0x60, 0x40, 0x3F, 0x80,
0x0F, 0x00, 0x40, 0x20, 0x20, 0x60, 0x18, 0x04, 0x02, 0x01, 0x43, 0x1E,
0x00, 0x03, 0x05, 0x0A, 0x12, 0x22, 0x22, 0x42, 0x7F, 0x04, 0x04, 0x1E,
0x1F, 0x88, 0x08, 0x05, 0xC3, 0x30, 0x08, 0x04, 0x02, 0x02, 0x42, 0x1E,
0x00, 0x07, 0x18, 0x20, 0x40, 0x5C, 0xA6, 0xC2, 0x82, 0x82, 0xC4, 0x78,
0xFF, 0x04, 0x10, 0x20, 0x82, 0x04, 0x10, 0x20, 0x81, 0x00, 0x1E, 0x23,
0x41, 0x41, 0x62, 0x1C, 0x66, 0x82, 0x82, 0x84, 0x78, 0x1E, 0x23, 0x41,
0x41, 0x43, 0x65, 0x3A, 0x02, 0x04, 0x18, 0xE0, 0x6C, 0x00, 0x36, 0x18,
0xC0, 0x00, 0x19, 0x8C, 0xC4, 0x00, 0x01, 0x83, 0x06, 0x0C, 0x06, 0x00,
0x80, 0x30, 0x04, 0xFF, 0x80, 0x00, 0x1F, 0xF0, 0x20, 0x0C, 0x01, 0x00,
0x60, 0x20, 0x60, 0xC1, 0x80, 0x3D, 0x8E, 0x08, 0x10, 0xC6, 0x08, 0x00,
0x01, 0x80, 0x1C, 0x45, 0x0A, 0x79, 0x34, 0x69, 0x4E, 0x81, 0x03, 0x03,
0xC0, 0x0F, 0x00, 0x60, 0x12, 0x02, 0x40, 0x88, 0x21, 0x07, 0xE1, 0x04,
0x20, 0x5E, 0x3C, 0x3F, 0x84, 0x11, 0x04, 0x82, 0x3F, 0x88, 0x32, 0x04,
0x81, 0x60, 0xBF, 0xC0, 0x1E, 0x98, 0xD0, 0x28, 0x08, 0x04, 0x02, 0x01,
0x00, 0x41, 0x1F, 0x00, 0x3F, 0x0C, 0x22, 0x04, 0x81, 0x20, 0x48, 0x12,
0x09, 0x02, 0x43, 0x3F, 0x00, 0x3F, 0xC4, 0x11, 0x00, 0x88, 0x3E, 0x08,
0x82, 0x00, 0x82, 0x60, 0xBF, 0xE0, 0x3F, 0xE2, 0x08, 0x40, 0x11, 0x03,
0xE0, 0x44, 0x08, 0x01, 0x00, 0x60, 0x1F, 0x00, 0x1E, 0x98, 0xD0, 0x08,
0x08, 0x04, 0x7A, 0x05, 0x02, 0x41, 0x1F, 0x00, 0x3D, 0xE2, 0x18, 0x42,
0x08, 0x43, 0xF8, 0x41, 0x08, 0x21, 0x08, 0x21, 0x1E, 0xF0, 0x3F, 0x82,
0x02, 0x01, 0x00, 0x80, 0x40, 0x20, 0x20, 0x10, 0x7F, 0x00, 0x0F, 0xE0,
0x20, 0x04, 0x00, 0x80, 0x10, 0x02, 0x20, 0x84, 0x10, 0x84, 0x0F, 0x00,
0x3C, 0xE2, 0x10, 0x44, 0x11, 0x02, 0xC0, 0x64, 0x08, 0x81, 0x08, 0x61,
0x1E, 0x38, 0x3E, 0x02, 0x00, 0x80, 0x20, 0x10, 0x04, 0x01, 0x04, 0x42,
0x10, 0xBF, 0xE0, 0x38, 0x38, 0xC3, 0x05, 0x28, 0x29, 0x42, 0x52, 0x13,
0x10, 0x99, 0x84, 0x08, 0x20, 0x47, 0x8F, 0x00, 0x70, 0xE6, 0x08, 0xA1,
0x14, 0x22, 0x48, 0x49, 0x11, 0x22, 0x14, 0x43, 0x1E, 0x20, 0x1E, 0x18,
0x90, 0x28, 0x18, 0x0C, 0x06, 0x05, 0x02, 0x46, 0x1E, 0x00, 0x3F, 0x84,
0x31, 0x04, 0x81, 0x20, 0x8F, 0xC2, 0x00, 0x80, 0x60, 0x3E, 0x00, 0x1E,
0x18, 0x90, 0x28, 0x18, 0x0C, 0x06, 0x05, 0x02, 0x46, 0x1E, 0x08, 0x0F,
0x44, 0x60, 0x3F, 0x84, 0x31, 0x04, 0x81, 0x20, 0x8F, 0xC2, 0x10, 0x84,
0x60, 0xBC, 0x10, 0x0F, 0x88, 0xC8, 0x24, 0x01, 0x80, 0x38, 0x05, 0x02,
0xC2, 0x5E, 0x00, 0xFF, 0xC4, 0x44, 0x02, 0x01, 0x00, 0x80, 0x40, 0x60,
0x20, 0x7E, 0x00, 0xF1, 0xD0, 0x24, 0x09, 0x02, 0x41, 0xA0, 0x48, 0x12,
0x04, 0xC6, 0x1F, 0x00, 0xF1, 0xE8, 0x11, 0x02, 0x20, 0x82, 0x20, 0x44,
0x09, 0x01, 0x40, 0x28, 0x02, 0x00, 0xF1, 0xE8, 0x09, 0x12, 0x26, 0x45,
0x48, 0xAA, 0x29, 0x45, 0x28, 0xC6, 0x18, 0xC0, 0x38, 0xE2, 0x08, 0x26,
0x05, 0x00, 0x40, 0x18, 0x04, 0x81, 0x08, 0x41, 0x1C, 0x70, 0xE3, 0xA0,
0x90, 0x84, 0x81, 0x80, 0x80, 0x40, 0x20, 0x20, 0x7E, 0x00, 0x3F, 0x90,
0x88, 0x80, 0x80, 0x80, 0x80, 0x80, 0x82, 0x82, 0x7F, 0x00, 0x39, 0x08,
0x44, 0x21, 0x08, 0x42, 0x21, 0x0E, 0x00, 0x88, 0x44, 0x44, 0x22, 0x22,
0x11, 0x11, 0x38, 0x42, 0x11, 0x08, 0x42, 0x10, 0x84, 0x2E, 0x00, 0x08,
0x28, 0x92, 0x18, 0x20, 0xFF, 0xC0, 0xA4, 0x3E, 0x00, 0x80, 0x47, 0xA4,
0x34, 0x12, 0x18, 0xF7, 0x38, 0x01, 0x00, 0x40, 0x09, 0xE1, 0xC6, 0x20,
0x44, 0x09, 0x01, 0x30, 0x46, 0x13, 0xBC, 0x00, 0x1F, 0x48, 0x74, 0x0A,
0x00, 0x80, 0x20, 0x0C, 0x18, 0xF8, 0x01, 0x80, 0x40, 0x23, 0x96, 0x32,
0x0A, 0x05, 0x02, 0x81, 0x61, 0x1F, 0xE0, 0x1F, 0x30, 0xD0, 0x3F, 0xF8,
0x04, 0x01, 0x00, 0x7C, 0x07, 0xC3, 0x00, 0x80, 0xFE, 0x10, 0x04, 0x01,
0x00, 0x40, 0x10, 0x08, 0x0F, 0xE0, 0x1D, 0xD8, 0xC4, 0x12, 0x04, 0x82,
0x20, 0x8C, 0x61, 0xE8, 0x02, 0x01, 0x07, 0x80, 0x30, 0x04, 0x01, 0x00,
0x5C, 0x38, 0x88, 0x22, 0x08, 0x82, 0x21, 0x18, 0x4F, 0x3C, 0x04, 0x04,
0x00, 0x38, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10, 0xFF, 0x01, 0x00, 0x80,
0x03, 0xF0, 0x10, 0x08, 0x04, 0x02, 0x02, 0x01, 0x00, 0x80, 0x40, 0x47,
0xC0, 0x38, 0x08, 0x04, 0x02, 0x71, 0x20, 0xA0, 0xA0, 0x68, 0x24, 0x11,
0x38, 0xE0, 0x3C, 0x04, 0x04, 0x08, 0x08, 0x08, 0x08, 0x08, 0x10, 0x10,
0xFF, 0x3E, 0xE2, 0x64, 0x88, 0x91, 0x12, 0x24, 0x48, 0x91, 0x17, 0x33,
0x37, 0x14, 0x4C, 0x24, 0x12, 0x09, 0x08, 0x85, 0xE3, 0x1E, 0x10, 0x90,
0x30, 0x18, 0x0C, 0x0B, 0x08, 0x78, 0x33, 0xC3, 0x8C, 0x40, 0x88, 0x12,
0x02, 0x60, 0x8C, 0x31, 0x78, 0x20, 0x08, 0x03, 0xE0, 0x00, 0x1C, 0xD8,
0xC4, 0x12, 0x04, 0x81, 0x20, 0x4C, 0x21, 0xF8, 0x02, 0x00, 0x81, 0xF0,
0x73, 0x8E, 0x04, 0x04, 0x02, 0x01, 0x00, 0x81, 0xFC, 0x1F, 0x61, 0x40,
0x3C, 0x03, 0x81, 0x82, 0xFC, 0x10, 0x63, 0xF9, 0x02, 0x04, 0x10, 0x20,
0x40, 0x7C, 0xE3, 0x10, 0x90, 0x48, 0x24, 0x22, 0x11, 0x18, 0xF6, 0xF3,
0xD0, 0x44, 0x10, 0x88, 0x24, 0x09, 0x02, 0x80, 0x40, 0xE1, 0xD0, 0x24,
0x91, 0x24, 0x55, 0x19, 0x86, 0x61, 0x10, 0x39, 0xC4, 0x20, 0xB0, 0x30,
0x0C, 0x04, 0x86, 0x13, 0x8E, 0x3C, 0x71, 0x04, 0x10, 0x40, 0x88, 0x09,
0x00, 0xA0, 0x06, 0x00, 0x40, 0x08, 0x01, 0x00, 0xFC, 0x00, 0x7F, 0x42,
0x04, 0x08, 0x10, 0x20, 0x42, 0xFE, 0x0C, 0x41, 0x04, 0x30, 0x8C, 0x08,
0x21, 0x04, 0x10, 0x60, 0x24, 0x94, 0x92, 0x52, 0x40, 0x18, 0x20, 0x82,
0x10, 0x40, 0xC4, 0x10, 0x82, 0x08, 0xC0, 0x61, 0x24, 0x30 ]
FreeMonoOblique9pt7bGlyphs = [
[ 0, 0, 0, 11, 0, 1 ], # 0x20 ' '
[ 0, 4, 11, 11, 4, -10 ], # 0x21 '!'
[ 6, 5, 5, 11, 4, -10 ], # 0x22 '"'
[ 10, 9, 12, 11, 2, -10 ], # 0x23 '#'
[ 24, 8, 12, 11, 3, -10 ], # 0x24 '$'
[ 36, 9, 11, 11, 2, -10 ], # 0x25 '%'
[ 49, 7, 10, 11, 2, -9 ], # 0x26 '&'
[ 58, 2, 5, 11, 6, -10 ], # 0x27 '''
[ 60, 4, 13, 11, 6, -10 ], # 0x28 '('
[ 67, 4, 13, 11, 3, -10 ], # 0x29 ')'
[ 74, 7, 7, 11, 4, -10 ], # 0x2A '#'
[ 81, 9, 8, 11, 2, -8 ], # 0x2B '+'
[ 90, 4, 5, 11, 2, -1 ], # 0x2C ','
[ 93, 9, 1, 11, 2, -5 ], # 0x2D '-'
[ 95, 2, 2, 11, 4, -1 ], # 0x2E '.'
[ 96, 9, 13, 11, 2, -11 ], # 0x2F '/'
[ 111, 7, 11, 11, 3, -10 ], # 0x30 '0'
[ 121, 7, 11, 11, 2, -10 ], # 0x31 '1'
[ 131, 9, 11, 11, 2, -10 ], # 0x32 '2'
[ 144, 9, 11, 11, 2, -10 ], # 0x33 '3'
[ 157, 8, 11, 11, 2, -10 ], # 0x34 '4'
[ 168, 9, 11, 11, 2, -10 ], # 0x35 '5'
[ 181, 8, 11, 11, 3, -10 ], # 0x36 '6'
[ 192, 7, 11, 11, 4, -10 ], # 0x37 '7'
[ 202, 8, 11, 11, 3, -10 ], # 0x38 '8'
[ 213, 8, 11, 11, 3, -10 ], # 0x39 '9'
[ 224, 3, 8, 11, 4, -7 ], # 0x3A ':'
[ 227, 5, 11, 11, 2, -7 ], # 0x3B ''
[ 234, 9, 8, 11, 2, -8 ], # 0x3C '<'
[ 243, 9, 4, 11, 2, -6 ], # 0x3D '='
[ 248, 9, 8, 11, 2, -8 ], # 0x3E '>'
[ 257, 7, 10, 11, 4, -9 ], # 0x3F '?'
[ 266, 7, 12, 11, 3, -10 ], # 0x40 '@'
[ 277, 11, 10, 11, 0, -9 ], # 0x41 'A'
[ 291, 10, 10, 11, 1, -9 ], # 0x42 'B'
[ 304, 9, 10, 11, 2, -9 ], # 0x43 'C'
[ 316, 10, 10, 11, 1, -9 ], # 0x44 'D'
[ 329, 10, 10, 11, 1, -9 ], # 0x45 'E'
[ 342, 11, 10, 11, 1, -9 ], # 0x46 'F'
[ 356, 9, 10, 11, 2, -9 ], # 0x47 'G'
[ 368, 11, 10, 11, 1, -9 ], # 0x48 'H'
[ 382, 9, 10, 11, 2, -9 ], # 0x49 'I'
[ 394, 11, 10, 11, 2, -9 ], # 0x4A 'J'
[ 408, 11, 10, 11, 1, -9 ], # 0x4B 'K'
[ 422, 10, 10, 11, 1, -9 ], # 0x4C 'L'
[ 435, 13, 10, 11, 0, -9 ], # 0x4D 'M'
[ 452, 11, 10, 11, 1, -9 ], # 0x4E 'N'
[ 466, 9, 10, 11, 2, -9 ], # 0x4F 'O'
[ 478, 10, 10, 11, 1, -9 ], # 0x50 'P'
[ 491, 9, 13, 11, 2, -9 ], # 0x51 'Q'
[ 506, 10, 10, 11, 1, -9 ], # 0x52 'R'
[ 519, 9, 10, 11, 2, -9 ], # 0x53 'S'
[ 531, 9, 10, 11, 3, -9 ], # 0x54 'T'
[ 543, 10, 10, 11, 2, -9 ], # 0x55 'U'
[ 556, 11, 10, 11, 2, -9 ], # 0x56 'V'
[ 570, 11, 10, 11, 2, -9 ], # 0x57 'W'
[ 584, 11, 10, 11, 1, -9 ], # 0x58 'X'
[ 598, 9, 10, 11, 3, -9 ], # 0x59 'Y'
[ 610, 9, 10, 11, 2, -9 ], # 0x5A 'Z'
[ 622, 5, 13, 11, 5, -10 ], # 0x5B '['
[ 631, 4, 14, 11, 4, -11 ], # 0x5C '\'
[ 638, 5, 13, 11, 2, -10 ], # 0x5D ']'
[ 647, 7, 5, 11, 3, -10 ], # 0x5E '^'
[ 652, 11, 1, 11, 0, 2 ], # 0x5F '_'
[ 654, 2, 3, 11, 5, -11 ], # 0x60 '`'
[ 655, 9, 8, 11, 2, -7 ], # 0x61 'a'
[ 664, 11, 11, 11, 0, -10 ], # 0x62 'b'
[ 680, 10, 8, 11, 2, -7 ], # 0x63 'c'
[ 690, 9, 11, 11, 2, -10 ], # 0x64 'd'
[ 703, 9, 8, 11, 2, -7 ], # 0x65 'e'
[ 712, 10, 11, 11, 2, -10 ], # 0x66 'f'
[ 726, 10, 11, 11, 2, -7 ], # 0x67 'g'
[ 740, 10, 11, 11, 1, -10 ], # 0x68 'h'
[ 754, 8, 11, 11, 2, -10 ], # 0x69 'i'
[ 765, 9, 14, 11, 1, -10 ], # 0x6A 'j'
[ 781, 9, 11, 11, 1, -10 ], # 0x6B 'k'
[ 794, 8, 11, 11, 2, -10 ], # 0x6C 'l'
[ 805, 11, 8, 11, 0, -7 ], # 0x6D 'm'
[ 816, 9, 8, 11, 1, -7 ], # 0x6E 'n'
[ 825, 9, 8, 11, 2, -7 ], # 0x6F 'o'
[ 834, 11, 11, 11, 0, -7 ], # 0x70 'p'
[ 850, 10, 11, 11, 2, -7 ], # 0x71 'q'
[ 864, 9, 8, 11, 2, -7 ], # 0x72 'r'
[ 873, 8, 8, 11, 2, -7 ], # 0x73 's'
[ 881, 7, 10, 11, 2, -9 ], # 0x74 't'
[ 890, 9, 8, 11, 2, -7 ], # 0x75 'u'
[ 899, 10, 8, 11, 2, -7 ], # 0x76 'v'
[ 909, 10, 8, 11, 2, -7 ], # 0x77 'w'
[ 919, 10, 8, 11, 1, -7 ], # 0x78 'x'
[ 929, 12, 11, 11, 0, -7 ], # 0x79 'y'
[ 946, 8, 8, 11, 2, -7 ], # 0x7A 'z'
[ 954, 6, 13, 11, 4, -10 ], # 0x7B '['
[ 964, 3, 12, 11, 5, -9 ], # 0x7C '|'
[ 969, 6, 13, 11, 3, -10 ], # 0x7D ']'
[ 979, 7, 3, 11, 3, -6 ] ] # 0x7E '~'
FreeMonoOblique9pt7b = [
FreeMonoOblique9pt7bBitmaps,
FreeMonoOblique9pt7bGlyphs,
0x20, 0x7E, 18 ]
# Approx. 1654 bytes
| free_mono_oblique9pt7b_bitmaps = [17, 34, 36, 64, 0, 192, 222, 229, 41, 0, 9, 5, 2, 130, 71, 248, 160, 81, 254, 40, 20, 10, 9, 0, 8, 29, 35, 64, 112, 28, 2, 130, 132, 120, 32, 32, 28, 17, 8, 131, 128, 24, 113, 192, 28, 17, 8, 131, 128, 30, 96, 129, 3, 10, 101, 70, 136, 232, 250, 128, 18, 36, 72, 136, 136, 136, 128, 1, 17, 17, 17, 34, 68, 128, 16, 34, 91, 195, 10, 34, 0, 4, 2, 2, 31, 240, 128, 64, 32, 0, 54, 76, 128, 255, 128, 240, 0, 128, 128, 64, 64, 64, 32, 32, 32, 16, 16, 16, 8, 8, 0, 28, 69, 10, 24, 48, 97, 66, 133, 17, 192, 4, 56, 144, 32, 129, 2, 4, 8, 35, 248, 7, 4, 196, 32, 16, 16, 48, 32, 32, 96, 64, 63, 128, 15, 0, 64, 32, 32, 96, 24, 4, 2, 1, 67, 30, 0, 3, 5, 10, 18, 34, 34, 66, 127, 4, 4, 30, 31, 136, 8, 5, 195, 48, 8, 4, 2, 2, 66, 30, 0, 7, 24, 32, 64, 92, 166, 194, 130, 130, 196, 120, 255, 4, 16, 32, 130, 4, 16, 32, 129, 0, 30, 35, 65, 65, 98, 28, 102, 130, 130, 132, 120, 30, 35, 65, 65, 67, 101, 58, 2, 4, 24, 224, 108, 0, 54, 24, 192, 0, 25, 140, 196, 0, 1, 131, 6, 12, 6, 0, 128, 48, 4, 255, 128, 0, 31, 240, 32, 12, 1, 0, 96, 32, 96, 193, 128, 61, 142, 8, 16, 198, 8, 0, 1, 128, 28, 69, 10, 121, 52, 105, 78, 129, 3, 3, 192, 15, 0, 96, 18, 2, 64, 136, 33, 7, 225, 4, 32, 94, 60, 63, 132, 17, 4, 130, 63, 136, 50, 4, 129, 96, 191, 192, 30, 152, 208, 40, 8, 4, 2, 1, 0, 65, 31, 0, 63, 12, 34, 4, 129, 32, 72, 18, 9, 2, 67, 63, 0, 63, 196, 17, 0, 136, 62, 8, 130, 0, 130, 96, 191, 224, 63, 226, 8, 64, 17, 3, 224, 68, 8, 1, 0, 96, 31, 0, 30, 152, 208, 8, 8, 4, 122, 5, 2, 65, 31, 0, 61, 226, 24, 66, 8, 67, 248, 65, 8, 33, 8, 33, 30, 240, 63, 130, 2, 1, 0, 128, 64, 32, 32, 16, 127, 0, 15, 224, 32, 4, 0, 128, 16, 2, 32, 132, 16, 132, 15, 0, 60, 226, 16, 68, 17, 2, 192, 100, 8, 129, 8, 97, 30, 56, 62, 2, 0, 128, 32, 16, 4, 1, 4, 66, 16, 191, 224, 56, 56, 195, 5, 40, 41, 66, 82, 19, 16, 153, 132, 8, 32, 71, 143, 0, 112, 230, 8, 161, 20, 34, 72, 73, 17, 34, 20, 67, 30, 32, 30, 24, 144, 40, 24, 12, 6, 5, 2, 70, 30, 0, 63, 132, 49, 4, 129, 32, 143, 194, 0, 128, 96, 62, 0, 30, 24, 144, 40, 24, 12, 6, 5, 2, 70, 30, 8, 15, 68, 96, 63, 132, 49, 4, 129, 32, 143, 194, 16, 132, 96, 188, 16, 15, 136, 200, 36, 1, 128, 56, 5, 2, 194, 94, 0, 255, 196, 68, 2, 1, 0, 128, 64, 96, 32, 126, 0, 241, 208, 36, 9, 2, 65, 160, 72, 18, 4, 198, 31, 0, 241, 232, 17, 2, 32, 130, 32, 68, 9, 1, 64, 40, 2, 0, 241, 232, 9, 18, 38, 69, 72, 170, 41, 69, 40, 198, 24, 192, 56, 226, 8, 38, 5, 0, 64, 24, 4, 129, 8, 65, 28, 112, 227, 160, 144, 132, 129, 128, 128, 64, 32, 32, 126, 0, 63, 144, 136, 128, 128, 128, 128, 128, 130, 130, 127, 0, 57, 8, 68, 33, 8, 66, 33, 14, 0, 136, 68, 68, 34, 34, 17, 17, 56, 66, 17, 8, 66, 16, 132, 46, 0, 8, 40, 146, 24, 32, 255, 192, 164, 62, 0, 128, 71, 164, 52, 18, 24, 247, 56, 1, 0, 64, 9, 225, 198, 32, 68, 9, 1, 48, 70, 19, 188, 0, 31, 72, 116, 10, 0, 128, 32, 12, 24, 248, 1, 128, 64, 35, 150, 50, 10, 5, 2, 129, 97, 31, 224, 31, 48, 208, 63, 248, 4, 1, 0, 124, 7, 195, 0, 128, 254, 16, 4, 1, 0, 64, 16, 8, 15, 224, 29, 216, 196, 18, 4, 130, 32, 140, 97, 232, 2, 1, 7, 128, 48, 4, 1, 0, 92, 56, 136, 34, 8, 130, 33, 24, 79, 60, 4, 4, 0, 56, 8, 8, 8, 8, 16, 16, 255, 1, 0, 128, 3, 240, 16, 8, 4, 2, 2, 1, 0, 128, 64, 71, 192, 56, 8, 4, 2, 113, 32, 160, 160, 104, 36, 17, 56, 224, 60, 4, 4, 8, 8, 8, 8, 8, 16, 16, 255, 62, 226, 100, 136, 145, 18, 36, 72, 145, 23, 51, 55, 20, 76, 36, 18, 9, 8, 133, 227, 30, 16, 144, 48, 24, 12, 11, 8, 120, 51, 195, 140, 64, 136, 18, 2, 96, 140, 49, 120, 32, 8, 3, 224, 0, 28, 216, 196, 18, 4, 129, 32, 76, 33, 248, 2, 0, 129, 240, 115, 142, 4, 4, 2, 1, 0, 129, 252, 31, 97, 64, 60, 3, 129, 130, 252, 16, 99, 249, 2, 4, 16, 32, 64, 124, 227, 16, 144, 72, 36, 34, 17, 24, 246, 243, 208, 68, 16, 136, 36, 9, 2, 128, 64, 225, 208, 36, 145, 36, 85, 25, 134, 97, 16, 57, 196, 32, 176, 48, 12, 4, 134, 19, 142, 60, 113, 4, 16, 64, 136, 9, 0, 160, 6, 0, 64, 8, 1, 0, 252, 0, 127, 66, 4, 8, 16, 32, 66, 254, 12, 65, 4, 48, 140, 8, 33, 4, 16, 96, 36, 148, 146, 82, 64, 24, 32, 130, 16, 64, 196, 16, 130, 8, 192, 97, 36, 48]
free_mono_oblique9pt7b_glyphs = [[0, 0, 0, 11, 0, 1], [0, 4, 11, 11, 4, -10], [6, 5, 5, 11, 4, -10], [10, 9, 12, 11, 2, -10], [24, 8, 12, 11, 3, -10], [36, 9, 11, 11, 2, -10], [49, 7, 10, 11, 2, -9], [58, 2, 5, 11, 6, -10], [60, 4, 13, 11, 6, -10], [67, 4, 13, 11, 3, -10], [74, 7, 7, 11, 4, -10], [81, 9, 8, 11, 2, -8], [90, 4, 5, 11, 2, -1], [93, 9, 1, 11, 2, -5], [95, 2, 2, 11, 4, -1], [96, 9, 13, 11, 2, -11], [111, 7, 11, 11, 3, -10], [121, 7, 11, 11, 2, -10], [131, 9, 11, 11, 2, -10], [144, 9, 11, 11, 2, -10], [157, 8, 11, 11, 2, -10], [168, 9, 11, 11, 2, -10], [181, 8, 11, 11, 3, -10], [192, 7, 11, 11, 4, -10], [202, 8, 11, 11, 3, -10], [213, 8, 11, 11, 3, -10], [224, 3, 8, 11, 4, -7], [227, 5, 11, 11, 2, -7], [234, 9, 8, 11, 2, -8], [243, 9, 4, 11, 2, -6], [248, 9, 8, 11, 2, -8], [257, 7, 10, 11, 4, -9], [266, 7, 12, 11, 3, -10], [277, 11, 10, 11, 0, -9], [291, 10, 10, 11, 1, -9], [304, 9, 10, 11, 2, -9], [316, 10, 10, 11, 1, -9], [329, 10, 10, 11, 1, -9], [342, 11, 10, 11, 1, -9], [356, 9, 10, 11, 2, -9], [368, 11, 10, 11, 1, -9], [382, 9, 10, 11, 2, -9], [394, 11, 10, 11, 2, -9], [408, 11, 10, 11, 1, -9], [422, 10, 10, 11, 1, -9], [435, 13, 10, 11, 0, -9], [452, 11, 10, 11, 1, -9], [466, 9, 10, 11, 2, -9], [478, 10, 10, 11, 1, -9], [491, 9, 13, 11, 2, -9], [506, 10, 10, 11, 1, -9], [519, 9, 10, 11, 2, -9], [531, 9, 10, 11, 3, -9], [543, 10, 10, 11, 2, -9], [556, 11, 10, 11, 2, -9], [570, 11, 10, 11, 2, -9], [584, 11, 10, 11, 1, -9], [598, 9, 10, 11, 3, -9], [610, 9, 10, 11, 2, -9], [622, 5, 13, 11, 5, -10], [631, 4, 14, 11, 4, -11], [638, 5, 13, 11, 2, -10], [647, 7, 5, 11, 3, -10], [652, 11, 1, 11, 0, 2], [654, 2, 3, 11, 5, -11], [655, 9, 8, 11, 2, -7], [664, 11, 11, 11, 0, -10], [680, 10, 8, 11, 2, -7], [690, 9, 11, 11, 2, -10], [703, 9, 8, 11, 2, -7], [712, 10, 11, 11, 2, -10], [726, 10, 11, 11, 2, -7], [740, 10, 11, 11, 1, -10], [754, 8, 11, 11, 2, -10], [765, 9, 14, 11, 1, -10], [781, 9, 11, 11, 1, -10], [794, 8, 11, 11, 2, -10], [805, 11, 8, 11, 0, -7], [816, 9, 8, 11, 1, -7], [825, 9, 8, 11, 2, -7], [834, 11, 11, 11, 0, -7], [850, 10, 11, 11, 2, -7], [864, 9, 8, 11, 2, -7], [873, 8, 8, 11, 2, -7], [881, 7, 10, 11, 2, -9], [890, 9, 8, 11, 2, -7], [899, 10, 8, 11, 2, -7], [909, 10, 8, 11, 2, -7], [919, 10, 8, 11, 1, -7], [929, 12, 11, 11, 0, -7], [946, 8, 8, 11, 2, -7], [954, 6, 13, 11, 4, -10], [964, 3, 12, 11, 5, -9], [969, 6, 13, 11, 3, -10], [979, 7, 3, 11, 3, -6]]
free_mono_oblique9pt7b = [FreeMonoOblique9pt7bBitmaps, FreeMonoOblique9pt7bGlyphs, 32, 126, 18] |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of easy-drf.
# https://github.com/talp101/easy-drf.git
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2015, Tal Peretz <13@1500.co.il>
__version__ = '0.1.2' # NOQA
| __version__ = '0.1.2' |
class Solution:
# @param dictionary: a list of strings
# @return: a list of strings
def longestWords(self, dictionary):
def word_len_list(dictionary):
wd_list =[]
for word in dictionary:
wd_list.append(len(word))
return max(wd_list)
def find_word(dictionary):
result = []
for word in dictionary:
if len(word) == word_len_list(dictionary):
result.append(word)
return result
return find_word(dictionary)
print(Solution().longestWords(["apped","apdoap","pajdnd","adjdnd"]))
| class Solution:
def longest_words(self, dictionary):
def word_len_list(dictionary):
wd_list = []
for word in dictionary:
wd_list.append(len(word))
return max(wd_list)
def find_word(dictionary):
result = []
for word in dictionary:
if len(word) == word_len_list(dictionary):
result.append(word)
return result
return find_word(dictionary)
print(solution().longestWords(['apped', 'apdoap', 'pajdnd', 'adjdnd'])) |
def normalize(s: str) -> str:
"""
Filter out '\n' and translate multiple ' ' into one ' '
:param s: String to normalize
:return: normalized str
"""
s = list(filter(lambda x: x != '\n', s))
ret_s = ""
i = 0
while i < len(s):
ret_s += s[i]
if s[i] == ' ':
while s[i] == ' ':
i += 1
else:
i += 1
return ret_s
| def normalize(s: str) -> str:
"""
Filter out '
' and translate multiple ' ' into one ' '
:param s: String to normalize
:return: normalized str
"""
s = list(filter(lambda x: x != '\n', s))
ret_s = ''
i = 0
while i < len(s):
ret_s += s[i]
if s[i] == ' ':
while s[i] == ' ':
i += 1
else:
i += 1
return ret_s |
@jit(nopython=True)
def pressure_poisson(p, b, l2_target):
I, J = b.shape
iter_diff = l2_target + 1
n = 0
while iter_diff > l2_target and n <= 500:
pn = p.copy()
for i in range(1, I - 1):
for j in range(1, J - 1):
p[i, j] = (.25 * (pn[i, j + 1] +
pn[i, j - 1] +
pn[i + 1, j] +
pn[i - 1, j]) -
b[i, j])
for i in range(I):
p[i, 0] = p[i, 1]
p[i, -1] = 0
for j in range(J):
p[0, j] = p[1, j]
p[-1, j] = p[-2, j]
if n % 10 == 0:
iter_diff = numpy.sqrt(numpy.sum((p - pn)**2)/numpy.sum(pn**2))
n += 1
return p
| @jit(nopython=True)
def pressure_poisson(p, b, l2_target):
(i, j) = b.shape
iter_diff = l2_target + 1
n = 0
while iter_diff > l2_target and n <= 500:
pn = p.copy()
for i in range(1, I - 1):
for j in range(1, J - 1):
p[i, j] = 0.25 * (pn[i, j + 1] + pn[i, j - 1] + pn[i + 1, j] + pn[i - 1, j]) - b[i, j]
for i in range(I):
p[i, 0] = p[i, 1]
p[i, -1] = 0
for j in range(J):
p[0, j] = p[1, j]
p[-1, j] = p[-2, j]
if n % 10 == 0:
iter_diff = numpy.sqrt(numpy.sum((p - pn) ** 2) / numpy.sum(pn ** 2))
n += 1
return p |
'''
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Example 1:
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1
Output: [["Q"]]
Constraints:
1 <= n <= 9
'''
class Solution(object):
def solveNQueens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
self.output = []
self.n = n
matrix = [['.'] * n for i in range(n)]
self.col_index = []
col_key = {}
for i in range(n):
col_key[i] = 1
self.onemap = [col_key.copy() for i in range(n)]
self.backtracking(matrix, 0)
return self.output
def backtracking(self, matrix, row):
if row == self.n:
out = [''.join(matrix[i]) for i in range(self.n)]
self.output.append(out)
return
x = row
for y in self.onemap[x].keys():
matrix[x][y] = 'Q'
self.col_index.append(y)
index = self.del_index(x + 1)
self.backtracking(matrix, x + 1)
matrix[x][y] = '.'
self.col_index.pop()
for one in index:
self.onemap[x + 1][one] = 1
return
def del_index(self, row):
if row == self.n:
return []
out_index = []
for i in range(0, row):
col = self.col_index[i]
cur_col = [col, col - (row - i), col + (row - i)]
for one in cur_col:
if one in self.onemap[row]:
self.onemap[row].pop(one)
out_index.append(one)
return out_index | """
The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Example 1:
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1
Output: [["Q"]]
Constraints:
1 <= n <= 9
"""
class Solution(object):
def solve_n_queens(self, n):
"""
:type n: int
:rtype: List[List[str]]
"""
self.output = []
self.n = n
matrix = [['.'] * n for i in range(n)]
self.col_index = []
col_key = {}
for i in range(n):
col_key[i] = 1
self.onemap = [col_key.copy() for i in range(n)]
self.backtracking(matrix, 0)
return self.output
def backtracking(self, matrix, row):
if row == self.n:
out = [''.join(matrix[i]) for i in range(self.n)]
self.output.append(out)
return
x = row
for y in self.onemap[x].keys():
matrix[x][y] = 'Q'
self.col_index.append(y)
index = self.del_index(x + 1)
self.backtracking(matrix, x + 1)
matrix[x][y] = '.'
self.col_index.pop()
for one in index:
self.onemap[x + 1][one] = 1
return
def del_index(self, row):
if row == self.n:
return []
out_index = []
for i in range(0, row):
col = self.col_index[i]
cur_col = [col, col - (row - i), col + (row - i)]
for one in cur_col:
if one in self.onemap[row]:
self.onemap[row].pop(one)
out_index.append(one)
return out_index |
def findAllDuplicates(nums):
d = dict()
for i in nums:
d[i] = d.get(i, 0) + 1
dup = list()
print(d)
for i in d:
if d[i] == 2:
dup.append(i)
return dup
nums = [4, 3, 2, 7, 8, 2, 3, 1]
dup = findAllDuplicates(nums)
print(dup) | def find_all_duplicates(nums):
d = dict()
for i in nums:
d[i] = d.get(i, 0) + 1
dup = list()
print(d)
for i in d:
if d[i] == 2:
dup.append(i)
return dup
nums = [4, 3, 2, 7, 8, 2, 3, 1]
dup = find_all_duplicates(nums)
print(dup) |
##sq=lambda x:x**2
##res=sq(5)
##print("square is:",res)
##
##
##
##add=lambda x,y,z:x+y+z
##
##
##print("sum is:",add(2,3,4))
##
##l=[1,2,3,4,5]
##li=list(map(lambda x:x**3,l))
##print(li)
t=(1,2,3,4,5)
def sum(x):
return x+10
a=list(map(sum,t))
print(a)
| t = (1, 2, 3, 4, 5)
def sum(x):
return x + 10
a = list(map(sum, t))
print(a) |
def iterative(array, element, sort=False):
"""
Perform Binary Search by Iterative Method.
:param array: Iterable of elements.
:param element: element to search.
:param sort: True will sort the array first then search. By default = False.
:return: returns value of index of element (if found) else return None.
"""
if sort:
array.sort()
left = 0
right = len(array) - 1
while left <= right:
mid = (right + left) // 2
# indices of a list must be integer
if array[mid] == element:
return mid
elif array[mid] > element:
right = mid - 1
else:
left = mid + 1
return None
def recursive(array, element, left=0, right=None, sort=False):
"""
Perform Binary Search by Iterative Method.
:param array: Iterable of elements.
:param left: start limit of array.
:param right: end limit of array.
:param element: element to be searched.
:param sort: True will sort the array first then search, By default = False.
:return: returns value of index of element (if found) else return None.
"""
if sort:
array.sort()
right = len(array) - 1 if right is None else right
if right >= left:
mid = (right + left) // 2
if array[mid] == element:
return mid
elif array[mid] > element:
return recursive(array, element, left, mid - 1)
else:
return recursive(array, element, mid + 1, right)
else:
return None
def main():
array = [1, 9, 11, 13, 5, 7, 8, 5, 17, 1156, 114]
array.sort()
element = 13
result = recursive(array, element)
if result is None:
print('Recursive Binary Search : Element not present in array')
else:
print('Recursive Binary Search : Element is present at index', result)
result = iterative(array, element)
if result is None:
print('Iterative Binary Search : Element not present in array')
else:
print('Iterative Binary Search : Element is present at index', result)
if __name__ == '__main__':
main() | def iterative(array, element, sort=False):
"""
Perform Binary Search by Iterative Method.
:param array: Iterable of elements.
:param element: element to search.
:param sort: True will sort the array first then search. By default = False.
:return: returns value of index of element (if found) else return None.
"""
if sort:
array.sort()
left = 0
right = len(array) - 1
while left <= right:
mid = (right + left) // 2
if array[mid] == element:
return mid
elif array[mid] > element:
right = mid - 1
else:
left = mid + 1
return None
def recursive(array, element, left=0, right=None, sort=False):
"""
Perform Binary Search by Iterative Method.
:param array: Iterable of elements.
:param left: start limit of array.
:param right: end limit of array.
:param element: element to be searched.
:param sort: True will sort the array first then search, By default = False.
:return: returns value of index of element (if found) else return None.
"""
if sort:
array.sort()
right = len(array) - 1 if right is None else right
if right >= left:
mid = (right + left) // 2
if array[mid] == element:
return mid
elif array[mid] > element:
return recursive(array, element, left, mid - 1)
else:
return recursive(array, element, mid + 1, right)
else:
return None
def main():
array = [1, 9, 11, 13, 5, 7, 8, 5, 17, 1156, 114]
array.sort()
element = 13
result = recursive(array, element)
if result is None:
print('Recursive Binary Search : Element not present in array')
else:
print('Recursive Binary Search : Element is present at index', result)
result = iterative(array, element)
if result is None:
print('Iterative Binary Search : Element not present in array')
else:
print('Iterative Binary Search : Element is present at index', result)
if __name__ == '__main__':
main() |
class WordDistanceFinder:
"""
This class will be given a list of words (such as might be tokenized
from a paragraph of text), and will provide a method that takes two
words and returns the shortest distance (in words) between those two
words in the provided text.
::
finder = WordDistanceFinder(["the", "quick", "brown", "fox", "quick", "junk", "fox"])
assert finder.distance("fox", "the") == 3
assert finder.distance("quick", "fox") == 1
"quick" appears twice in the input. There are two possible distance values for "quick" and "fox":
(3 - 1) = 2 and (4 - 3) = 1.
Since we have to return the shortest distance between the two words we return 1.
"""
def __init__(self, words):
# Implementation here
self.words = words
self.words_index_dict = {}
for idx, word in enumerate(words): # O(n)
self.words_index_dict.setdefault(word, [])
self.words_index_dict[word].append(idx)
def distance(self, wordOne, wordTwo):
# Implementation here
word_one_list = self.words_index_dict.get(wordOne, []) # [1, 4] # k elements < n
word_two_list = self.words_index_dict.get(wordTwo, []) # [3, 6, 8, 10, 12, 14, 20, 100, 200] # m elements < n-1 5 7
min_dist = None
# 1 3 4
for each_one in word_one_list: # O(k*m)
for each_two in word_two_list:
curr_dist = abs(each_one-each_two)
if not min_dist or min_dist > curr_dist:
min_dist = curr_dist
return min_dist
def distance_2(self, wordOne, wordTwo):
word_one_idx = -1
word_two_idx = -1
min_dist = None
for idx, each_word in enumerate(self.words): # O(n)
if each_word == wordOne:
word_one_idx = idx # 4
if each_word == wordTwo:
word_two_idx = idx # 6
if word_one_idx > -1 and word_two_idx > -1:
curr_dist = abs(word_one_idx-word_two_idx)
if not min_dist or min_dist > curr_dist:
min_dist = curr_dist
return min_dist
def distance_3(self, wordOne, wordTwo):
try:
min_one_idx = self.words_index_dict[wordOne][0]
max_one_idx = self.words_index_dict[wordOne][-1]
except Exception:
return 'Not applicable'
try:
min_two_idx = self.words_index_dict[wordTwo][0]
max_two_idx = self.words_index_dict[wordTwo][-1]
except Exception:
return 'Not applicable'
global_min = min_one_idx if min_one_idx <= min_two_idx else min_two_idx
global_max = max_one_idx if max_one_idx >= max_two_idx else max_two_idx
min_dist = None
for idx, each_word in self.words[global_min, global_max]: # O(n)
if each_word == wordOne:
word_one_idx = idx # 4
if each_word == wordTwo:
word_two_idx = idx # 6
if word_one_idx > -1 and word_two_idx > -1:
curr_dist = abs(word_one_idx-word_two_idx)
if not min_dist or min_dist > curr_dist:
min_dist = curr_dist
return min_dist
| class Worddistancefinder:
"""
This class will be given a list of words (such as might be tokenized
from a paragraph of text), and will provide a method that takes two
words and returns the shortest distance (in words) between those two
words in the provided text.
::
finder = WordDistanceFinder(["the", "quick", "brown", "fox", "quick", "junk", "fox"])
assert finder.distance("fox", "the") == 3
assert finder.distance("quick", "fox") == 1
"quick" appears twice in the input. There are two possible distance values for "quick" and "fox":
(3 - 1) = 2 and (4 - 3) = 1.
Since we have to return the shortest distance between the two words we return 1.
"""
def __init__(self, words):
self.words = words
self.words_index_dict = {}
for (idx, word) in enumerate(words):
self.words_index_dict.setdefault(word, [])
self.words_index_dict[word].append(idx)
def distance(self, wordOne, wordTwo):
word_one_list = self.words_index_dict.get(wordOne, [])
word_two_list = self.words_index_dict.get(wordTwo, [])
min_dist = None
for each_one in word_one_list:
for each_two in word_two_list:
curr_dist = abs(each_one - each_two)
if not min_dist or min_dist > curr_dist:
min_dist = curr_dist
return min_dist
def distance_2(self, wordOne, wordTwo):
word_one_idx = -1
word_two_idx = -1
min_dist = None
for (idx, each_word) in enumerate(self.words):
if each_word == wordOne:
word_one_idx = idx
if each_word == wordTwo:
word_two_idx = idx
if word_one_idx > -1 and word_two_idx > -1:
curr_dist = abs(word_one_idx - word_two_idx)
if not min_dist or min_dist > curr_dist:
min_dist = curr_dist
return min_dist
def distance_3(self, wordOne, wordTwo):
try:
min_one_idx = self.words_index_dict[wordOne][0]
max_one_idx = self.words_index_dict[wordOne][-1]
except Exception:
return 'Not applicable'
try:
min_two_idx = self.words_index_dict[wordTwo][0]
max_two_idx = self.words_index_dict[wordTwo][-1]
except Exception:
return 'Not applicable'
global_min = min_one_idx if min_one_idx <= min_two_idx else min_two_idx
global_max = max_one_idx if max_one_idx >= max_two_idx else max_two_idx
min_dist = None
for (idx, each_word) in self.words[global_min, global_max]:
if each_word == wordOne:
word_one_idx = idx
if each_word == wordTwo:
word_two_idx = idx
if word_one_idx > -1 and word_two_idx > -1:
curr_dist = abs(word_one_idx - word_two_idx)
if not min_dist or min_dist > curr_dist:
min_dist = curr_dist
return min_dist |
# Title : TODO
# Objective : TODO
# Created by: Wenzurk
# Created on: 2018/2/3
transportation = ['bicycle', 'motorcycle', 'car', 'airplane']
message = 'I would like to own a '
print(message + transportation[0] + ".")
print(message + transportation[1] + ".")
print(message + transportation[2] + ".")
print(message + transportation[3] + ".") | transportation = ['bicycle', 'motorcycle', 'car', 'airplane']
message = 'I would like to own a '
print(message + transportation[0] + '.')
print(message + transportation[1] + '.')
print(message + transportation[2] + '.')
print(message + transportation[3] + '.') |
def solution(x, y):
x = int(x)
y = int(y)
numCycles = 0
while (x > 1 or y > 1):
if (x == y or x < 1 or y < 1):
return "impossible"
elif (x > y):
factor = int(x/y)
numCycles+=factor
if (y == 1):
numCycles-=1
x = x-y*(factor-1)
else:
x = x-y*factor
elif (x < y):
factor = int(y/x)
numCycles+=factor
if (x == 1):
numCycles-=1
y = y-x*(factor-1)
else:
y = y-x*factor
return str(numCycles)
| def solution(x, y):
x = int(x)
y = int(y)
num_cycles = 0
while x > 1 or y > 1:
if x == y or x < 1 or y < 1:
return 'impossible'
elif x > y:
factor = int(x / y)
num_cycles += factor
if y == 1:
num_cycles -= 1
x = x - y * (factor - 1)
else:
x = x - y * factor
elif x < y:
factor = int(y / x)
num_cycles += factor
if x == 1:
num_cycles -= 1
y = y - x * (factor - 1)
else:
y = y - x * factor
return str(numCycles) |
valores = [1, 2, 3, 4, 5, 6, 7, 8, 9]
pares = list(filter(lambda x : x % 2 == 0, valores))
impares = list(filter(lambda x : x % 2 != 0, valores))
print(pares)
print(impares)
| valores = [1, 2, 3, 4, 5, 6, 7, 8, 9]
pares = list(filter(lambda x: x % 2 == 0, valores))
impares = list(filter(lambda x: x % 2 != 0, valores))
print(pares)
print(impares) |
# -*- coding: utf-8 -*-
"""Library for components to support modularity."""
MESSAGE_CLASSES = {}
SEGMENT_CLASSES = {}
| """Library for components to support modularity."""
message_classes = {}
segment_classes = {} |
cpf = '04045683941'
novo_cpf = cpf[:-2]#selecionando os 9 primeiros e deixando os dois ultimos #040456839
reverso = 10
total = 0
for index in range(19):
if index > 8:
index -= 9
total += int(novo_cpf[index]) * reverso
print(cpf [index], index), reverso
reverso -= 1
if reverso < 2:
reverso = 11 | cpf = '04045683941'
novo_cpf = cpf[:-2]
reverso = 10
total = 0
for index in range(19):
if index > 8:
index -= 9
total += int(novo_cpf[index]) * reverso
(print(cpf[index], index), reverso)
reverso -= 1
if reverso < 2:
reverso = 11 |
# -*- coding: utf-8 -*-
""" Manifest App Information
Some codes used in this project is collected
from several open source projects, such as;
Django: https://github.com/django/django
django-rest-framework: https://github.com/encode/django-rest-framework
django-rest-auth: https://github.com/Tivix/django-rest-auth
django-userena-ce: https://github.com/django-userena-ce/django-userena-ce
and others...
"""
| """ Manifest App Information
Some codes used in this project is collected
from several open source projects, such as;
Django: https://github.com/django/django
django-rest-framework: https://github.com/encode/django-rest-framework
django-rest-auth: https://github.com/Tivix/django-rest-auth
django-userena-ce: https://github.com/django-userena-ce/django-userena-ce
and others...
""" |
# Angold4 20200620 4.1
def normal_max(S):
Max = S[0]
for i in S:
if i > Max:
Max = i
return Max
def find_max(S):
"""answer"""
if len(S) == 1:
return S[0]
Max = S.pop()
return max(Max, find_max(S))
if __name__ == "__main__":
s = [1, 4, 4, 7, 3, 2, 20, 34, 90, 133, 113, 123, 5, 9, 293, 1]
print(normal_max(s))
print(find_max(s))
"""
293
293
"""
| def normal_max(S):
max = S[0]
for i in S:
if i > Max:
max = i
return Max
def find_max(S):
"""answer"""
if len(S) == 1:
return S[0]
max = S.pop()
return max(Max, find_max(S))
if __name__ == '__main__':
s = [1, 4, 4, 7, 3, 2, 20, 34, 90, 133, 113, 123, 5, 9, 293, 1]
print(normal_max(s))
print(find_max(s))
'\n 293\n 293\n ' |
class StubSoundPlayer:
def __init__(self):
pass
def play_once(self, filename):
pass
def set_music_volume(self, new_volume):
pass
def change_music(self):
pass
def play_sound_event(self, sound_event):
pass
def process_events(self, sound_event_list):
pass
| class Stubsoundplayer:
def __init__(self):
pass
def play_once(self, filename):
pass
def set_music_volume(self, new_volume):
pass
def change_music(self):
pass
def play_sound_event(self, sound_event):
pass
def process_events(self, sound_event_list):
pass |
t = int(input())
for i in range(t):
n, m = input().split()
n = int(n)
m = int(m)
print((n-1)*(m-1)) | t = int(input())
for i in range(t):
(n, m) = input().split()
n = int(n)
m = int(m)
print((n - 1) * (m - 1)) |
class Solution:
def maximalSquare(self, matrix: List[List[str]]) -> int:
if len(matrix)<1:
return 0
dp=[[0 for i in range(len(matrix[0])+1)] for j in range(len(matrix)+1)]
max1=0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j]=='1':
dp[i+1][j+1]=min(dp[i][j],dp[i][j+1],dp[i+1][j])+1
max1=max(max1,dp[i+1][j+1])
return max1**2
| class Solution:
def maximal_square(self, matrix: List[List[str]]) -> int:
if len(matrix) < 1:
return 0
dp = [[0 for i in range(len(matrix[0]) + 1)] for j in range(len(matrix) + 1)]
max1 = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == '1':
dp[i + 1][j + 1] = min(dp[i][j], dp[i][j + 1], dp[i + 1][j]) + 1
max1 = max(max1, dp[i + 1][j + 1])
return max1 ** 2 |
#
# Common constants
#
APP_NAME = 'autonom'
DEFAULT_CONFIG_FILE = 'autonom.ini'
DEFAULT_SESSMGR = 'ticket'
# We do this to convert run-time errors into compile time errors
CF_DEFAULT = 'DEFAULT'
CF_LISTEN = 'listen'
CF_PORT = 'port'
CF_PROVIDERS = 'providers'
CF_FIXED_IP_LIST = 'fixed_ip_list'
CF_LOG = 'log'
CF_LOG_EX = 'log_data'
CF_PROVIDER = 'provider'
CF_ID = 'id'
CF_HREF = 'href'
CF_DESC = 'desc'
CF_ROUTE = 'route'
CF_VIEW = 'view'
CF_PWCK = 'pwck'
CF_COOKIE_NAME = 'cookie_name'
CF_SESSION_SIG = 'session_sig'
CF_TICKET_MAXAGE = 'ticket_maxage'
CF_COOKIE_MAXAGE = 'cookie_maxage'
CF_COOKIE_RENEW = 'cookie_renew'
CF_ATIME_MIN = 'ticket_min_atime'
CF_PROXY_LIST = 'proxy_list'
CF_PROXY_PSK = 'proxy_secret'
CF_IPLOGIN_MAXAGE = 'iplogin_maxage'
CF_MODULE = 'module'
CF_TEMPLATE_PATH = 'template_path'
CF_DOCROOT = 'docroot'
CF_TICKET_DB = 'ticket_db_path'
CF_AUTH_REALM = 'http_auth_realm'
RT_SESSION_MGR = 'session_mgr'
CF_BACKENDS = 'backends'
CF_BACKEND = 'backend'
LOG_SYSLOG = 1
LOG_STDIO = 2
LOG_FILE = 3
CF_PWTYPE = 'style'
CF_PASSWD = 'passwd'
CF_GROUPS = 'groups'
CF_DIGEST = 'digest'
FF_APACHE2 = 'apache'
FF_UNIX = 'unix'
FF_DEFAULT = FF_APACHE2
CF_TLREALMS_DATA = 'tlrealms_data'
| app_name = 'autonom'
default_config_file = 'autonom.ini'
default_sessmgr = 'ticket'
cf_default = 'DEFAULT'
cf_listen = 'listen'
cf_port = 'port'
cf_providers = 'providers'
cf_fixed_ip_list = 'fixed_ip_list'
cf_log = 'log'
cf_log_ex = 'log_data'
cf_provider = 'provider'
cf_id = 'id'
cf_href = 'href'
cf_desc = 'desc'
cf_route = 'route'
cf_view = 'view'
cf_pwck = 'pwck'
cf_cookie_name = 'cookie_name'
cf_session_sig = 'session_sig'
cf_ticket_maxage = 'ticket_maxage'
cf_cookie_maxage = 'cookie_maxage'
cf_cookie_renew = 'cookie_renew'
cf_atime_min = 'ticket_min_atime'
cf_proxy_list = 'proxy_list'
cf_proxy_psk = 'proxy_secret'
cf_iplogin_maxage = 'iplogin_maxage'
cf_module = 'module'
cf_template_path = 'template_path'
cf_docroot = 'docroot'
cf_ticket_db = 'ticket_db_path'
cf_auth_realm = 'http_auth_realm'
rt_session_mgr = 'session_mgr'
cf_backends = 'backends'
cf_backend = 'backend'
log_syslog = 1
log_stdio = 2
log_file = 3
cf_pwtype = 'style'
cf_passwd = 'passwd'
cf_groups = 'groups'
cf_digest = 'digest'
ff_apache2 = 'apache'
ff_unix = 'unix'
ff_default = FF_APACHE2
cf_tlrealms_data = 'tlrealms_data' |
class BudgetNotFound(Exception):
pass
class WrongPushException(Exception):
def __init__(self, expected_delta, delta):
self.expected_delta = expected_delta
self.delta = delta
string = 'tried to push a changed_entities with %d entities while we expected %d entities'
@property
def msg(self):
return self.string % (self.delta, self.expected_delta)
def __repr__(self):
return self.msg
class NoBudgetNameException(ValueError):
def __init__(self):
super(NoBudgetNameException,self).__init__('you should pass a budget_name ')
class NoCredentialsException(BaseException):
def __init__(self):
super(NoCredentialsException,self).__init__('you should pass email and password if you don\'t pass a Connection')
| class Budgetnotfound(Exception):
pass
class Wrongpushexception(Exception):
def __init__(self, expected_delta, delta):
self.expected_delta = expected_delta
self.delta = delta
string = 'tried to push a changed_entities with %d entities while we expected %d entities'
@property
def msg(self):
return self.string % (self.delta, self.expected_delta)
def __repr__(self):
return self.msg
class Nobudgetnameexception(ValueError):
def __init__(self):
super(NoBudgetNameException, self).__init__('you should pass a budget_name ')
class Nocredentialsexception(BaseException):
def __init__(self):
super(NoCredentialsException, self).__init__("you should pass email and password if you don't pass a Connection") |
#Source : https://leetcode.com/problems/insertion-sort-list/
#Author : Yuan Wang
#Date : 2021-02-01
'''
**********************************************************************************
*Sort a linked list using insertion sort.
*
*Example1 :
*Input: 4->2->1->3
*Output: 1->2->3->4
**********************************************************************************/
'''
#time complexity : O(n) space complexity : O(1)
def insertionSortList(self, head: ListNode) -> ListNode:
p = ListNode(0)
dummy = p
dummy.next = head
current = head
while current and current.next:
val = current.next.val
if current.val < val:
current = current.next
continue
if p.next.val > val:
p = dummy
while p.next.val < val:
p = p.next
temp = current.next
current.next = temp.next
temp.next = p.next
p.next = temp
return dummy.next | """
**********************************************************************************
*Sort a linked list using insertion sort.
*
*Example1 :
*Input: 4->2->1->3
*Output: 1->2->3->4
**********************************************************************************/
"""
def insertion_sort_list(self, head: ListNode) -> ListNode:
p = list_node(0)
dummy = p
dummy.next = head
current = head
while current and current.next:
val = current.next.val
if current.val < val:
current = current.next
continue
if p.next.val > val:
p = dummy
while p.next.val < val:
p = p.next
temp = current.next
current.next = temp.next
temp.next = p.next
p.next = temp
return dummy.next |
class ScoreCache:
def __init__(self):
self.parent_cache = dict()
self.child_cache = dict()
self.joint_cache = dict()
def print(self):
print("____CACHE_____")
print("parents->(parent_states,parent_states_counts)")
print(self.parent_cache)
print("child->child_states_counts")
print(self.child_cache)
print("(child,hashed(parents)->k2")
print(self.joint_cache) | class Scorecache:
def __init__(self):
self.parent_cache = dict()
self.child_cache = dict()
self.joint_cache = dict()
def print(self):
print('____CACHE_____')
print('parents->(parent_states,parent_states_counts)')
print(self.parent_cache)
print('child->child_states_counts')
print(self.child_cache)
print('(child,hashed(parents)->k2')
print(self.joint_cache) |
Config = {
'game': {
'height': 640,
'width': 800,
'tile_width': 32
},
'resources': {
'sprites': {
'player': "src/res/char.png"
}
}
}
| config = {'game': {'height': 640, 'width': 800, 'tile_width': 32}, 'resources': {'sprites': {'player': 'src/res/char.png'}}} |
def find_binary_partitioned_seat(seat_range, input_text):
for letter in input_text:
difference = abs(seat_range[0] - seat_range[1]) // 2
if (letter == "F") or (letter == "L"):
seat_range = [seat_range[0], seat_range[0] + difference]
else:
seat_range = [seat_range[1] - difference, seat_range[1]]
assert seat_range[0] == seat_range[1]
return(seat_range[0])
with open("input.txt", "r") as puzzle_input:
seat_ids = []
for line in puzzle_input:
line = line.strip()
vertical_seat_input = line[:-3]
horizontal_seat_input = line[-3:]
vertical_seat = find_binary_partitioned_seat([0, 127], vertical_seat_input)
horizontal_seat = find_binary_partitioned_seat([0, 7], horizontal_seat_input)
seat_ids.append(vertical_seat * 8 + horizontal_seat)
seat_ids.sort()
for seat_id_index in range(len(seat_ids) - 1):
if seat_ids[seat_id_index + 1] == seat_ids[seat_id_index] + 2:
print(seat_ids[seat_id_index] + 1, "is open")
| def find_binary_partitioned_seat(seat_range, input_text):
for letter in input_text:
difference = abs(seat_range[0] - seat_range[1]) // 2
if letter == 'F' or letter == 'L':
seat_range = [seat_range[0], seat_range[0] + difference]
else:
seat_range = [seat_range[1] - difference, seat_range[1]]
assert seat_range[0] == seat_range[1]
return seat_range[0]
with open('input.txt', 'r') as puzzle_input:
seat_ids = []
for line in puzzle_input:
line = line.strip()
vertical_seat_input = line[:-3]
horizontal_seat_input = line[-3:]
vertical_seat = find_binary_partitioned_seat([0, 127], vertical_seat_input)
horizontal_seat = find_binary_partitioned_seat([0, 7], horizontal_seat_input)
seat_ids.append(vertical_seat * 8 + horizontal_seat)
seat_ids.sort()
for seat_id_index in range(len(seat_ids) - 1):
if seat_ids[seat_id_index + 1] == seat_ids[seat_id_index] + 2:
print(seat_ids[seat_id_index] + 1, 'is open') |
f = open('input.txt', 'r')
row = f.read()
data = row.split()
result = 0
children = {0: 1}
metadata = {}
deep = 1
slot = 2
for i in data:
i = int(i)
if slot == 2 and children[deep - 1] > 0 and (deep not in metadata or metadata[deep] == 0):
children[deep] = i
children[deep - 1] -= 1
slot = 1
continue
if slot == 2 and deep in children and children[deep] == 0 and deep in metadata and metadata[deep] > 0:
result += i
metadata[deep] -= 1
if metadata[deep] == 0 and children[deep - 1] == 0:
while deep in metadata and metadata[deep] == 0:
deep -= 1
continue
elif slot == 1:
metadata[deep] = i
slot = 2
if children[deep] > 0:
deep += 1
continue
print('Result:', result)
| f = open('input.txt', 'r')
row = f.read()
data = row.split()
result = 0
children = {0: 1}
metadata = {}
deep = 1
slot = 2
for i in data:
i = int(i)
if slot == 2 and children[deep - 1] > 0 and (deep not in metadata or metadata[deep] == 0):
children[deep] = i
children[deep - 1] -= 1
slot = 1
continue
if slot == 2 and deep in children and (children[deep] == 0) and (deep in metadata) and (metadata[deep] > 0):
result += i
metadata[deep] -= 1
if metadata[deep] == 0 and children[deep - 1] == 0:
while deep in metadata and metadata[deep] == 0:
deep -= 1
continue
elif slot == 1:
metadata[deep] = i
slot = 2
if children[deep] > 0:
deep += 1
continue
print('Result:', result) |
class Event:
def __init__(self, time):
self.time = time
def __lt__(self, other):
return self.time < other.time
def __le__(self, other):
return self < other or self.time == other.time
class InjectEvent(Event):
def __init__(self, time, packet):
super(InjectEvent, self).__init__(time)
self.packet = packet
def fromLine(line):
time, packet = line.split()
return InjectEvent(float(time), float(packet))
def __str__(self):
return "{} inject {}".format(self.time, self.packet)
class SentEvent(Event):
def __init__(self, time, algorithm):
super(SentEvent, self).__init__(time)
self.algorithm = algorithm
def __lt__(self, other):
if isinstance(other, SentEvent):
return self.time < other.time or self.time == other.time and self.algorithm < other.algorithm
return super(SentEvent, self).__lt__(other)
def __str__(self):
return "{} sent {}".format(self.time, self.algorithm.algorithmType)
class ErrorEvent(Event):
def __init__(self, time):
super(ErrorEvent, self).__init__(time)
def __str__(self):
return "{} error".format(self.time)
class ScheduleEvent(SentEvent):
def __init__(self, time, algorithm, packet):
super(ScheduleEvent, self).__init__(time, algorithm)
self.packet = packet
def __str__(self):
return "{} schedule {} {}".format(self.time, self.algorithm.algorithmType, self.packet)
class WaitEvent:
pass
| class Event:
def __init__(self, time):
self.time = time
def __lt__(self, other):
return self.time < other.time
def __le__(self, other):
return self < other or self.time == other.time
class Injectevent(Event):
def __init__(self, time, packet):
super(InjectEvent, self).__init__(time)
self.packet = packet
def from_line(line):
(time, packet) = line.split()
return inject_event(float(time), float(packet))
def __str__(self):
return '{} inject {}'.format(self.time, self.packet)
class Sentevent(Event):
def __init__(self, time, algorithm):
super(SentEvent, self).__init__(time)
self.algorithm = algorithm
def __lt__(self, other):
if isinstance(other, SentEvent):
return self.time < other.time or (self.time == other.time and self.algorithm < other.algorithm)
return super(SentEvent, self).__lt__(other)
def __str__(self):
return '{} sent {}'.format(self.time, self.algorithm.algorithmType)
class Errorevent(Event):
def __init__(self, time):
super(ErrorEvent, self).__init__(time)
def __str__(self):
return '{} error'.format(self.time)
class Scheduleevent(SentEvent):
def __init__(self, time, algorithm, packet):
super(ScheduleEvent, self).__init__(time, algorithm)
self.packet = packet
def __str__(self):
return '{} schedule {} {}'.format(self.time, self.algorithm.algorithmType, self.packet)
class Waitevent:
pass |
problems = input().split(";")
count = 0
for problem in problems:
if "-" in problem:
upper = problem.split("-")[1]
lower = problem.split("-")[0]
count += int(upper) - int(lower) + 1
else:
count += 1
print(count)
| problems = input().split(';')
count = 0
for problem in problems:
if '-' in problem:
upper = problem.split('-')[1]
lower = problem.split('-')[0]
count += int(upper) - int(lower) + 1
else:
count += 1
print(count) |
# game states
IN_PROGRESS = 0
PLAYER1 = 1
PLAYER2 = 2
DRAW = 3
GAME_STATES = {"IN_PROGRESS": IN_PROGRESS,
"PLAYER1": PLAYER1,
"PLAYER2": PLAYER2,
"DRAW": DRAW}
| in_progress = 0
player1 = 1
player2 = 2
draw = 3
game_states = {'IN_PROGRESS': IN_PROGRESS, 'PLAYER1': PLAYER1, 'PLAYER2': PLAYER2, 'DRAW': DRAW} |
# Do not edit. bazel-deps autogenerates this file from maven_deps.yaml.
def declare_maven(hash):
native.maven_jar(
name = hash["name"],
artifact = hash["artifact"],
sha1 = hash["sha1"],
repository = hash["repository"]
)
native.bind(
name = hash["bind"],
actual = hash["actual"]
)
def maven_dependencies(callback = declare_maven):
callback({"artifact": "args4j:args4j:2.33", "lang": "java", "sha1": "bd87a75374a6d6523de82fef51fc3cfe9baf9fc9", "repository": "https://repo.maven.apache.org/maven2/", "name": "args4j_args4j", "actual": "@args4j_args4j//jar", "bind": "jar/args4j/args4j"})
callback({"artifact": "com.google.api.grpc:proto-google-common-protos:1.0.0", "lang": "java", "sha1": "86f070507e28b930e50d218ee5b6788ef0dd05e6", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_api_grpc_proto_google_common_protos", "actual": "@com_google_api_grpc_proto_google_common_protos//jar", "bind": "jar/com/google/api/grpc/proto_google_common_protos"})
# duplicates in com.google.code.findbugs:jsr305 fixed to 3.0.2
# - com.google.guava:guava:23.0 wanted version 1.3.9
# - io.grpc:grpc-core:1.10.0 wanted version 3.0.0
# - com.google.instrumentation:instrumentation-api:0.4.3 wanted version 3.0.0
callback({"artifact": "com.google.code.findbugs:jsr305:3.0.2", "lang": "java", "sha1": "25ea2e8b0c338a877313bd4672d3fe056ea78f0d", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_code_findbugs_jsr305", "actual": "@com_google_code_findbugs_jsr305//jar", "bind": "jar/com/google/code/findbugs/jsr305"})
callback({"artifact": "com.google.code.gson:gson:2.8.2", "lang": "java", "sha1": "3edcfe49d2c6053a70a2a47e4e1c2f94998a49cf", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_code_gson_gson", "actual": "@com_google_code_gson_gson//jar", "bind": "jar/com/google/code/gson/gson"})
# duplicates in com.google.errorprone:error_prone_annotations promoted to 2.1.2
# - com.google.guava:guava:23.0 wanted version 2.0.18
# - io.grpc:grpc-core:1.10.0 wanted version 2.1.2
# - com.google.truth:truth:0.35 wanted version 2.0.19
callback({"artifact": "com.google.errorprone:error_prone_annotations:2.1.2", "lang": "java", "sha1": "6dcc08f90f678ac33e5ef78c3c752b6f59e63e0c", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_errorprone_error_prone_annotations", "actual": "@com_google_errorprone_error_prone_annotations//jar", "bind": "jar/com/google/errorprone/error_prone_annotations"})
# duplicates in com.google.guava:guava fixed to 23.0
# - io.grpc:grpc-core:1.10.0 wanted version 19.0
# - io.grpc:grpc-protobuf:1.10.0 wanted version 19.0
# - com.google.truth:truth:0.35 wanted version 22.0-android
callback({"artifact": "com.google.guava:guava:23.0", "lang": "java", "sha1": "c947004bb13d18182be60077ade044099e4f26f1", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_guava_guava", "actual": "@com_google_guava_guava//jar", "bind": "jar/com/google/guava/guava"})
callback({"artifact": "com.google.instrumentation:instrumentation-api:0.4.3", "lang": "java", "sha1": "41614af3429573dc02645d541638929d877945a2", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_instrumentation_instrumentation_api", "actual": "@com_google_instrumentation_instrumentation_api//jar", "bind": "jar/com/google/instrumentation/instrumentation_api"})
callback({"artifact": "com.google.j2objc:j2objc-annotations:1.1", "lang": "java", "sha1": "ed28ded51a8b1c6b112568def5f4b455e6809019", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_j2objc_j2objc_annotations", "actual": "@com_google_j2objc_j2objc_annotations//jar", "bind": "jar/com/google/j2objc/j2objc_annotations"})
callback({"artifact": "com.google.protobuf:protobuf-java-util:3.5.1", "lang": "java", "sha1": "6e40a6a3f52455bd633aa2a0dba1a416e62b4575", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_protobuf_protobuf_java_util", "actual": "@com_google_protobuf_protobuf_java_util//jar", "bind": "jar/com/google/protobuf/protobuf_java_util"})
callback({"artifact": "com.google.protobuf:protobuf-java:3.5.1", "lang": "java", "sha1": "8c3492f7662fa1cbf8ca76a0f5eb1146f7725acd", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_protobuf_protobuf_java", "actual": "@com_google_protobuf_protobuf_java//jar", "bind": "jar/com/google/protobuf/protobuf_java"})
callback({"artifact": "com.google.truth:truth:0.35", "lang": "java", "sha1": "c08a7fde45e058323bcfa3f510d4fe1e2b028f37", "repository": "https://repo.maven.apache.org/maven2/", "name": "com_google_truth_truth", "actual": "@com_google_truth_truth//jar", "bind": "jar/com/google/truth/truth"})
callback({"artifact": "io.grpc:grpc-context:1.10.0", "lang": "java", "sha1": "da0a701be6ba04aff0bd54ca3db8248d8f2eaafc", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_grpc_grpc_context", "actual": "@io_grpc_grpc_context//jar", "bind": "jar/io/grpc/grpc_context"})
callback({"artifact": "io.grpc:grpc-core:1.10.0", "lang": "java", "sha1": "8976afebf2a6530574a71bc1260920ce910c2292", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_grpc_grpc_core", "actual": "@io_grpc_grpc_core//jar", "bind": "jar/io/grpc/grpc_core"})
callback({"artifact": "io.grpc:grpc-netty:1.10.0", "lang": "java", "sha1": "a1056d69003c9b46d1c4aa4a9167c6e8a714d152", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_grpc_grpc_netty", "actual": "@io_grpc_grpc_netty//jar", "bind": "jar/io/grpc/grpc_netty"})
callback({"artifact": "io.grpc:grpc-protobuf-lite:1.10.0", "lang": "java", "sha1": "b8e40dd308dc370e64bd2c337bb2761a03299a7f", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_grpc_grpc_protobuf_lite", "actual": "@io_grpc_grpc_protobuf_lite//jar", "bind": "jar/io/grpc/grpc_protobuf_lite"})
callback({"artifact": "io.grpc:grpc-protobuf:1.10.0", "lang": "java", "sha1": "64098f046f227b47238bc747e3cee6c7fc087bb8", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_grpc_grpc_protobuf", "actual": "@io_grpc_grpc_protobuf//jar", "bind": "jar/io/grpc/grpc_protobuf"})
callback({"artifact": "io.grpc:grpc-services:1.10.0", "lang": "java", "sha1": "ae898f12418429c9d1396aaf5ac2377bf8ecb25b", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_grpc_grpc_services", "actual": "@io_grpc_grpc_services//jar", "bind": "jar/io/grpc/grpc_services"})
callback({"artifact": "io.grpc:grpc-stub:1.10.0", "lang": "java", "sha1": "d022706796b0820d388f83571da160fb8d280ded", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_grpc_grpc_stub", "actual": "@io_grpc_grpc_stub//jar", "bind": "jar/io/grpc/grpc_stub"})
callback({"artifact": "io.netty:netty-all:4.1.22.Final", "lang": "java", "sha1": "c1cea5d30025e4d584d2b287d177c31aea4ae629", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_all", "actual": "@io_netty_netty_all//jar", "bind": "jar/io/netty/netty_all"})
callback({"artifact": "io.netty:netty-buffer:4.1.17.Final", "lang": "java", "sha1": "fdd68fb3defd7059a7392b9395ee941ef9bacc25", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_buffer", "actual": "@io_netty_netty_buffer//jar", "bind": "jar/io/netty/netty_buffer"})
callback({"artifact": "io.netty:netty-codec-http2:4.1.17.Final", "lang": "java", "sha1": "f9844005869c6d9049f4b677228a89fee4c6eab3", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_codec_http2", "actual": "@io_netty_netty_codec_http2//jar", "bind": "jar/io/netty/netty_codec_http2"})
callback({"artifact": "io.netty:netty-codec-http:4.1.17.Final", "lang": "java", "sha1": "251d7edcb897122b9b23f24ff793cd0739056b9e", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_codec_http", "actual": "@io_netty_netty_codec_http//jar", "bind": "jar/io/netty/netty_codec_http"})
callback({"artifact": "io.netty:netty-codec-socks:4.1.17.Final", "lang": "java", "sha1": "a159bf1f3d5019e0d561c92fbbec8400967471fa", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_codec_socks", "actual": "@io_netty_netty_codec_socks//jar", "bind": "jar/io/netty/netty_codec_socks"})
callback({"artifact": "io.netty:netty-codec:4.1.17.Final", "lang": "java", "sha1": "1d00f56dc9e55203a4bde5aae3d0828fdeb818e7", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_codec", "actual": "@io_netty_netty_codec//jar", "bind": "jar/io/netty/netty_codec"})
callback({"artifact": "io.netty:netty-common:4.1.17.Final", "lang": "java", "sha1": "581c8ee239e4dc0976c2405d155f475538325098", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_common", "actual": "@io_netty_netty_common//jar", "bind": "jar/io/netty/netty_common"})
callback({"artifact": "io.netty:netty-handler-proxy:4.1.17.Final", "lang": "java", "sha1": "9330ee60c4e48ca60aac89b7bc5ec2567e84f28e", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_handler_proxy", "actual": "@io_netty_netty_handler_proxy//jar", "bind": "jar/io/netty/netty_handler_proxy"})
callback({"artifact": "io.netty:netty-handler:4.1.17.Final", "lang": "java", "sha1": "18c40ffb61a1d1979eca024087070762fdc4664a", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_handler", "actual": "@io_netty_netty_handler//jar", "bind": "jar/io/netty/netty_handler"})
callback({"artifact": "io.netty:netty-resolver:4.1.17.Final", "lang": "java", "sha1": "8f386c80821e200f542da282ae1d3cde5cad8368", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_resolver", "actual": "@io_netty_netty_resolver//jar", "bind": "jar/io/netty/netty_resolver"})
callback({"artifact": "io.netty:netty-transport:4.1.17.Final", "lang": "java", "sha1": "9585776b0a8153182412b5d5366061ff486914c1", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_netty_netty_transport", "actual": "@io_netty_netty_transport//jar", "bind": "jar/io/netty/netty_transport"})
callback({"artifact": "io.opencensus:opencensus-api:0.11.0", "lang": "java", "sha1": "c1ff1f0d737a689d900a3e2113ddc29847188c64", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_opencensus_opencensus_api", "actual": "@io_opencensus_opencensus_api//jar", "bind": "jar/io/opencensus/opencensus_api"})
callback({"artifact": "io.opencensus:opencensus-contrib-grpc-metrics:0.11.0", "lang": "java", "sha1": "d57b877f1a28a613452d45e35c7faae5af585258", "repository": "https://repo.maven.apache.org/maven2/", "name": "io_opencensus_opencensus_contrib_grpc_metrics", "actual": "@io_opencensus_opencensus_contrib_grpc_metrics//jar", "bind": "jar/io/opencensus/opencensus_contrib_grpc_metrics"})
callback({"artifact": "junit:junit:4.12", "lang": "java", "sha1": "2973d150c0dc1fefe998f834810d68f278ea58ec", "repository": "https://repo.maven.apache.org/maven2/", "name": "junit_junit", "actual": "@junit_junit//jar", "bind": "jar/junit/junit"})
callback({"artifact": "org.codehaus.mojo:animal-sniffer-annotations:1.14", "lang": "java", "sha1": "775b7e22fb10026eed3f86e8dc556dfafe35f2d5", "repository": "https://repo.maven.apache.org/maven2/", "name": "org_codehaus_mojo_animal_sniffer_annotations", "actual": "@org_codehaus_mojo_animal_sniffer_annotations//jar", "bind": "jar/org/codehaus/mojo/animal_sniffer_annotations"})
callback({"artifact": "org.hamcrest:hamcrest-core:1.3", "lang": "java", "sha1": "42a25dc3219429f0e5d060061f71acb49bf010a0", "repository": "https://repo.maven.apache.org/maven2/", "name": "org_hamcrest_hamcrest_core", "actual": "@org_hamcrest_hamcrest_core//jar", "bind": "jar/org/hamcrest/hamcrest_core"})
callback({"artifact": "org.textmapper:lapg:0.9.18", "lang": "java", "sha1": "9d480589d5770d75c4401f38c3cfd22a7139a397", "repository": "https://repo.maven.apache.org/maven2/", "name": "org_textmapper_lapg", "actual": "@org_textmapper_lapg//jar", "bind": "jar/org/textmapper/lapg"})
callback({"artifact": "org.textmapper:templates:0.9.18", "lang": "java", "sha1": "1979db4fe5d0581639d3ace891a7abeaf95f8220", "repository": "https://repo.maven.apache.org/maven2/", "name": "org_textmapper_templates", "actual": "@org_textmapper_templates//jar", "bind": "jar/org/textmapper/templates"})
callback({"artifact": "org.textmapper:textmapper:0.9.18", "lang": "java", "sha1": "80ffa6ce9f7f3250fcc62419c0898ffeedbd5902", "repository": "https://repo.maven.apache.org/maven2/", "name": "org_textmapper_textmapper", "actual": "@org_textmapper_textmapper//jar", "bind": "jar/org/textmapper/textmapper"})
| def declare_maven(hash):
native.maven_jar(name=hash['name'], artifact=hash['artifact'], sha1=hash['sha1'], repository=hash['repository'])
native.bind(name=hash['bind'], actual=hash['actual'])
def maven_dependencies(callback=declare_maven):
callback({'artifact': 'args4j:args4j:2.33', 'lang': 'java', 'sha1': 'bd87a75374a6d6523de82fef51fc3cfe9baf9fc9', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'args4j_args4j', 'actual': '@args4j_args4j//jar', 'bind': 'jar/args4j/args4j'})
callback({'artifact': 'com.google.api.grpc:proto-google-common-protos:1.0.0', 'lang': 'java', 'sha1': '86f070507e28b930e50d218ee5b6788ef0dd05e6', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_api_grpc_proto_google_common_protos', 'actual': '@com_google_api_grpc_proto_google_common_protos//jar', 'bind': 'jar/com/google/api/grpc/proto_google_common_protos'})
callback({'artifact': 'com.google.code.findbugs:jsr305:3.0.2', 'lang': 'java', 'sha1': '25ea2e8b0c338a877313bd4672d3fe056ea78f0d', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_code_findbugs_jsr305', 'actual': '@com_google_code_findbugs_jsr305//jar', 'bind': 'jar/com/google/code/findbugs/jsr305'})
callback({'artifact': 'com.google.code.gson:gson:2.8.2', 'lang': 'java', 'sha1': '3edcfe49d2c6053a70a2a47e4e1c2f94998a49cf', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_code_gson_gson', 'actual': '@com_google_code_gson_gson//jar', 'bind': 'jar/com/google/code/gson/gson'})
callback({'artifact': 'com.google.errorprone:error_prone_annotations:2.1.2', 'lang': 'java', 'sha1': '6dcc08f90f678ac33e5ef78c3c752b6f59e63e0c', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_errorprone_error_prone_annotations', 'actual': '@com_google_errorprone_error_prone_annotations//jar', 'bind': 'jar/com/google/errorprone/error_prone_annotations'})
callback({'artifact': 'com.google.guava:guava:23.0', 'lang': 'java', 'sha1': 'c947004bb13d18182be60077ade044099e4f26f1', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_guava_guava', 'actual': '@com_google_guava_guava//jar', 'bind': 'jar/com/google/guava/guava'})
callback({'artifact': 'com.google.instrumentation:instrumentation-api:0.4.3', 'lang': 'java', 'sha1': '41614af3429573dc02645d541638929d877945a2', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_instrumentation_instrumentation_api', 'actual': '@com_google_instrumentation_instrumentation_api//jar', 'bind': 'jar/com/google/instrumentation/instrumentation_api'})
callback({'artifact': 'com.google.j2objc:j2objc-annotations:1.1', 'lang': 'java', 'sha1': 'ed28ded51a8b1c6b112568def5f4b455e6809019', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_j2objc_j2objc_annotations', 'actual': '@com_google_j2objc_j2objc_annotations//jar', 'bind': 'jar/com/google/j2objc/j2objc_annotations'})
callback({'artifact': 'com.google.protobuf:protobuf-java-util:3.5.1', 'lang': 'java', 'sha1': '6e40a6a3f52455bd633aa2a0dba1a416e62b4575', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_protobuf_protobuf_java_util', 'actual': '@com_google_protobuf_protobuf_java_util//jar', 'bind': 'jar/com/google/protobuf/protobuf_java_util'})
callback({'artifact': 'com.google.protobuf:protobuf-java:3.5.1', 'lang': 'java', 'sha1': '8c3492f7662fa1cbf8ca76a0f5eb1146f7725acd', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_protobuf_protobuf_java', 'actual': '@com_google_protobuf_protobuf_java//jar', 'bind': 'jar/com/google/protobuf/protobuf_java'})
callback({'artifact': 'com.google.truth:truth:0.35', 'lang': 'java', 'sha1': 'c08a7fde45e058323bcfa3f510d4fe1e2b028f37', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'com_google_truth_truth', 'actual': '@com_google_truth_truth//jar', 'bind': 'jar/com/google/truth/truth'})
callback({'artifact': 'io.grpc:grpc-context:1.10.0', 'lang': 'java', 'sha1': 'da0a701be6ba04aff0bd54ca3db8248d8f2eaafc', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_grpc_grpc_context', 'actual': '@io_grpc_grpc_context//jar', 'bind': 'jar/io/grpc/grpc_context'})
callback({'artifact': 'io.grpc:grpc-core:1.10.0', 'lang': 'java', 'sha1': '8976afebf2a6530574a71bc1260920ce910c2292', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_grpc_grpc_core', 'actual': '@io_grpc_grpc_core//jar', 'bind': 'jar/io/grpc/grpc_core'})
callback({'artifact': 'io.grpc:grpc-netty:1.10.0', 'lang': 'java', 'sha1': 'a1056d69003c9b46d1c4aa4a9167c6e8a714d152', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_grpc_grpc_netty', 'actual': '@io_grpc_grpc_netty//jar', 'bind': 'jar/io/grpc/grpc_netty'})
callback({'artifact': 'io.grpc:grpc-protobuf-lite:1.10.0', 'lang': 'java', 'sha1': 'b8e40dd308dc370e64bd2c337bb2761a03299a7f', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_grpc_grpc_protobuf_lite', 'actual': '@io_grpc_grpc_protobuf_lite//jar', 'bind': 'jar/io/grpc/grpc_protobuf_lite'})
callback({'artifact': 'io.grpc:grpc-protobuf:1.10.0', 'lang': 'java', 'sha1': '64098f046f227b47238bc747e3cee6c7fc087bb8', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_grpc_grpc_protobuf', 'actual': '@io_grpc_grpc_protobuf//jar', 'bind': 'jar/io/grpc/grpc_protobuf'})
callback({'artifact': 'io.grpc:grpc-services:1.10.0', 'lang': 'java', 'sha1': 'ae898f12418429c9d1396aaf5ac2377bf8ecb25b', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_grpc_grpc_services', 'actual': '@io_grpc_grpc_services//jar', 'bind': 'jar/io/grpc/grpc_services'})
callback({'artifact': 'io.grpc:grpc-stub:1.10.0', 'lang': 'java', 'sha1': 'd022706796b0820d388f83571da160fb8d280ded', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_grpc_grpc_stub', 'actual': '@io_grpc_grpc_stub//jar', 'bind': 'jar/io/grpc/grpc_stub'})
callback({'artifact': 'io.netty:netty-all:4.1.22.Final', 'lang': 'java', 'sha1': 'c1cea5d30025e4d584d2b287d177c31aea4ae629', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_all', 'actual': '@io_netty_netty_all//jar', 'bind': 'jar/io/netty/netty_all'})
callback({'artifact': 'io.netty:netty-buffer:4.1.17.Final', 'lang': 'java', 'sha1': 'fdd68fb3defd7059a7392b9395ee941ef9bacc25', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_buffer', 'actual': '@io_netty_netty_buffer//jar', 'bind': 'jar/io/netty/netty_buffer'})
callback({'artifact': 'io.netty:netty-codec-http2:4.1.17.Final', 'lang': 'java', 'sha1': 'f9844005869c6d9049f4b677228a89fee4c6eab3', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_codec_http2', 'actual': '@io_netty_netty_codec_http2//jar', 'bind': 'jar/io/netty/netty_codec_http2'})
callback({'artifact': 'io.netty:netty-codec-http:4.1.17.Final', 'lang': 'java', 'sha1': '251d7edcb897122b9b23f24ff793cd0739056b9e', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_codec_http', 'actual': '@io_netty_netty_codec_http//jar', 'bind': 'jar/io/netty/netty_codec_http'})
callback({'artifact': 'io.netty:netty-codec-socks:4.1.17.Final', 'lang': 'java', 'sha1': 'a159bf1f3d5019e0d561c92fbbec8400967471fa', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_codec_socks', 'actual': '@io_netty_netty_codec_socks//jar', 'bind': 'jar/io/netty/netty_codec_socks'})
callback({'artifact': 'io.netty:netty-codec:4.1.17.Final', 'lang': 'java', 'sha1': '1d00f56dc9e55203a4bde5aae3d0828fdeb818e7', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_codec', 'actual': '@io_netty_netty_codec//jar', 'bind': 'jar/io/netty/netty_codec'})
callback({'artifact': 'io.netty:netty-common:4.1.17.Final', 'lang': 'java', 'sha1': '581c8ee239e4dc0976c2405d155f475538325098', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_common', 'actual': '@io_netty_netty_common//jar', 'bind': 'jar/io/netty/netty_common'})
callback({'artifact': 'io.netty:netty-handler-proxy:4.1.17.Final', 'lang': 'java', 'sha1': '9330ee60c4e48ca60aac89b7bc5ec2567e84f28e', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_handler_proxy', 'actual': '@io_netty_netty_handler_proxy//jar', 'bind': 'jar/io/netty/netty_handler_proxy'})
callback({'artifact': 'io.netty:netty-handler:4.1.17.Final', 'lang': 'java', 'sha1': '18c40ffb61a1d1979eca024087070762fdc4664a', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_handler', 'actual': '@io_netty_netty_handler//jar', 'bind': 'jar/io/netty/netty_handler'})
callback({'artifact': 'io.netty:netty-resolver:4.1.17.Final', 'lang': 'java', 'sha1': '8f386c80821e200f542da282ae1d3cde5cad8368', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_resolver', 'actual': '@io_netty_netty_resolver//jar', 'bind': 'jar/io/netty/netty_resolver'})
callback({'artifact': 'io.netty:netty-transport:4.1.17.Final', 'lang': 'java', 'sha1': '9585776b0a8153182412b5d5366061ff486914c1', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_netty_netty_transport', 'actual': '@io_netty_netty_transport//jar', 'bind': 'jar/io/netty/netty_transport'})
callback({'artifact': 'io.opencensus:opencensus-api:0.11.0', 'lang': 'java', 'sha1': 'c1ff1f0d737a689d900a3e2113ddc29847188c64', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_opencensus_opencensus_api', 'actual': '@io_opencensus_opencensus_api//jar', 'bind': 'jar/io/opencensus/opencensus_api'})
callback({'artifact': 'io.opencensus:opencensus-contrib-grpc-metrics:0.11.0', 'lang': 'java', 'sha1': 'd57b877f1a28a613452d45e35c7faae5af585258', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'io_opencensus_opencensus_contrib_grpc_metrics', 'actual': '@io_opencensus_opencensus_contrib_grpc_metrics//jar', 'bind': 'jar/io/opencensus/opencensus_contrib_grpc_metrics'})
callback({'artifact': 'junit:junit:4.12', 'lang': 'java', 'sha1': '2973d150c0dc1fefe998f834810d68f278ea58ec', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'junit_junit', 'actual': '@junit_junit//jar', 'bind': 'jar/junit/junit'})
callback({'artifact': 'org.codehaus.mojo:animal-sniffer-annotations:1.14', 'lang': 'java', 'sha1': '775b7e22fb10026eed3f86e8dc556dfafe35f2d5', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'org_codehaus_mojo_animal_sniffer_annotations', 'actual': '@org_codehaus_mojo_animal_sniffer_annotations//jar', 'bind': 'jar/org/codehaus/mojo/animal_sniffer_annotations'})
callback({'artifact': 'org.hamcrest:hamcrest-core:1.3', 'lang': 'java', 'sha1': '42a25dc3219429f0e5d060061f71acb49bf010a0', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'org_hamcrest_hamcrest_core', 'actual': '@org_hamcrest_hamcrest_core//jar', 'bind': 'jar/org/hamcrest/hamcrest_core'})
callback({'artifact': 'org.textmapper:lapg:0.9.18', 'lang': 'java', 'sha1': '9d480589d5770d75c4401f38c3cfd22a7139a397', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'org_textmapper_lapg', 'actual': '@org_textmapper_lapg//jar', 'bind': 'jar/org/textmapper/lapg'})
callback({'artifact': 'org.textmapper:templates:0.9.18', 'lang': 'java', 'sha1': '1979db4fe5d0581639d3ace891a7abeaf95f8220', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'org_textmapper_templates', 'actual': '@org_textmapper_templates//jar', 'bind': 'jar/org/textmapper/templates'})
callback({'artifact': 'org.textmapper:textmapper:0.9.18', 'lang': 'java', 'sha1': '80ffa6ce9f7f3250fcc62419c0898ffeedbd5902', 'repository': 'https://repo.maven.apache.org/maven2/', 'name': 'org_textmapper_textmapper', 'actual': '@org_textmapper_textmapper//jar', 'bind': 'jar/org/textmapper/textmapper'}) |
# Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.
# Example 1:
# Input:
# [
# [1,1,1],
# [1,0,1],
# [1,1,1]
# ]
# Output:
# [
# [1,0,1],
# [0,0,0],
# [1,0,1]
# ]
class Solution:
def setZeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
n,m = len(matrix),len(matrix[0])
row, col = set(), set()
for i in range(n):
for j in range(m):
if matrix[i][j] == 0:
row.add(i)
col.add(j)
for i1 in row:
for j in range(m):
matrix[i1][j] = 0
for j1 in col:
for i in range(n):
matrix[i][j1] = 0
# Time: O(m*n)
# Space: O(1)
# Difficulty: medium | class Solution:
def set_zeroes(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
(n, m) = (len(matrix), len(matrix[0]))
(row, col) = (set(), set())
for i in range(n):
for j in range(m):
if matrix[i][j] == 0:
row.add(i)
col.add(j)
for i1 in row:
for j in range(m):
matrix[i1][j] = 0
for j1 in col:
for i in range(n):
matrix[i][j1] = 0 |
class Function(object):
"""Data-class to hold meta information about a registered back-end function.
"""
def __init__(self, rule, f):
self.rule = rule
self.f = f
| class Function(object):
"""Data-class to hold meta information about a registered back-end function.
"""
def __init__(self, rule, f):
self.rule = rule
self.f = f |
class Location(object):
"""docstring for Location"""
def __init__(self, lat=0, lon=0):
self._lat = lat
self._lon = lon
def __str__(self):
return "Location(%s,%s)" % (self._lat, self._lon)
def __unicode__(self):
return u"Location(%s,%s)" % (self._lat, self._lon)
@property
def lat(self):
return self._lat
@lat.setter
def lat(self, value):
self._lat = value
@property
def lon(self):
return self._lon
@lon.setter
def lon(self, value):
self._lon = value
class Antipodal(Location):
"""docstring for Antipodal"""
def __init__(self, lat, lon):
Location.__init__(self, 0, 0)
self.calcLat(lat)
self.calcLon(lon)
def calcLat(self, lat):
self._lat = -lat
def calcLon(self, lon):
self._lon = 180-lon | class Location(object):
"""docstring for Location"""
def __init__(self, lat=0, lon=0):
self._lat = lat
self._lon = lon
def __str__(self):
return 'Location(%s,%s)' % (self._lat, self._lon)
def __unicode__(self):
return u'Location(%s,%s)' % (self._lat, self._lon)
@property
def lat(self):
return self._lat
@lat.setter
def lat(self, value):
self._lat = value
@property
def lon(self):
return self._lon
@lon.setter
def lon(self, value):
self._lon = value
class Antipodal(Location):
"""docstring for Antipodal"""
def __init__(self, lat, lon):
Location.__init__(self, 0, 0)
self.calcLat(lat)
self.calcLon(lon)
def calc_lat(self, lat):
self._lat = -lat
def calc_lon(self, lon):
self._lon = 180 - lon |
A_COMMA = ","
A_QUOTE = "'"
DOUBLE_QUOTES = '"'
A_TAB = " "
AN_ESCAPED_TAB = "\t"
NEWLINE = """
"""
AN_ESCAPED_NEWLINE = "\n"
| a_comma = ','
a_quote = "'"
double_quotes = '"'
a_tab = '\t'
an_escaped_tab = '\t'
newline = '\n'
an_escaped_newline = '\n' |
"""
[4/14/2014] Challenge #158 [Easy] The Torn Number
https://www.reddit.com/r/dailyprogrammer/comments/230m05/4142014_challenge_158_easy_the_torn_number/
#Description:
I had the other day in my possession a label bearing the number 3 0 2 5 in large figures. This got accidentally torn in
half, so that 3 0 was on one piece and 2 5 on the other. On looking at these pieces I began to make a calculation,
when I discovered this little peculiarity. If we add the 3 0 and the 2 5 together and square the sum we get as the
result, the complete original number on the label! Thus, 30 added to 25 is 55, and 55 multiplied by 55 is 3025.
Curious, is it not?
Now, the challenge is to find another number, composed of four figures, all different, which may be divided in the
middle and produce the same result.
#Bonus
Create a program that verifies if a number is a valid torn number.
"""
def main():
pass
if __name__ == "__main__":
main()
| """
[4/14/2014] Challenge #158 [Easy] The Torn Number
https://www.reddit.com/r/dailyprogrammer/comments/230m05/4142014_challenge_158_easy_the_torn_number/
#Description:
I had the other day in my possession a label bearing the number 3 0 2 5 in large figures. This got accidentally torn in
half, so that 3 0 was on one piece and 2 5 on the other. On looking at these pieces I began to make a calculation,
when I discovered this little peculiarity. If we add the 3 0 and the 2 5 together and square the sum we get as the
result, the complete original number on the label! Thus, 30 added to 25 is 55, and 55 multiplied by 55 is 3025.
Curious, is it not?
Now, the challenge is to find another number, composed of four figures, all different, which may be divided in the
middle and produce the same result.
#Bonus
Create a program that verifies if a number is a valid torn number.
"""
def main():
pass
if __name__ == '__main__':
main() |
def zebra_2(x,y):
pattern=["/","/","/","-","-","-"]
z=0
while z<y:
for i in range(0,x):
print(pattern[i % len(pattern)], end='')
z+=1
print("\n")
x=int(input("give me a number of charcters in the row:" ))
y=int(input("give me a number of rows:" ))
zebra_2(x,y)
| def zebra_2(x, y):
pattern = ['/', '/', '/', '-', '-', '-']
z = 0
while z < y:
for i in range(0, x):
print(pattern[i % len(pattern)], end='')
z += 1
print('\n')
x = int(input('give me a number of charcters in the row:'))
y = int(input('give me a number of rows:'))
zebra_2(x, y) |
weather_appid = "12345678"
weather_appsecret = "abcdefg"
baidu_map_ak = "dfjkal;fjalskf;as"
| weather_appid = '12345678'
weather_appsecret = 'abcdefg'
baidu_map_ak = 'dfjkal;fjalskf;as' |
class FailedRunException(Exception):
"""
raised when an a run has not succeeded
"""
class BackendNotAvailableException(Exception):
"""
raise when a Backend is ill-configured
"""
| class Failedrunexception(Exception):
"""
raised when an a run has not succeeded
"""
class Backendnotavailableexception(Exception):
"""
raise when a Backend is ill-configured
""" |
first, second, year = map(int, input().split())
if first == second:
print(1)
elif first < 13 and second < 13:
print(0)
else:
print(1) | (first, second, year) = map(int, input().split())
if first == second:
print(1)
elif first < 13 and second < 13:
print(0)
else:
print(1) |
# Converts the rows of data, with the specified
# headers, into an easily human readable csv string.
def readable_csv(rows, headers, digits=None):
if digits is not None:
for i, row in enumerate(rows):
for j, col in enumerate(row):
if isinstance(col, float):
rows[i][j] = round(col, digits)
# First, stringify everything.
rows = [[str(c) for c in row] for row in rows]
# Get the width needed for each column and add two.
widths = [max([len(r[col]) for r in rows]) for col in range(len(rows[0]))]
widths = [max(w, len(headers[i])) + 2 for i, w in enumerate(widths)]
def space(row):
return [c.ljust(widths[i]) for i, c in enumerate(row)]
result = '%s\n'%(','.join(space(headers)))
for row in rows:
result += '%s\n'%(','.join(space(row)))
return result[:-1] | def readable_csv(rows, headers, digits=None):
if digits is not None:
for (i, row) in enumerate(rows):
for (j, col) in enumerate(row):
if isinstance(col, float):
rows[i][j] = round(col, digits)
rows = [[str(c) for c in row] for row in rows]
widths = [max([len(r[col]) for r in rows]) for col in range(len(rows[0]))]
widths = [max(w, len(headers[i])) + 2 for (i, w) in enumerate(widths)]
def space(row):
return [c.ljust(widths[i]) for (i, c) in enumerate(row)]
result = '%s\n' % ','.join(space(headers))
for row in rows:
result += '%s\n' % ','.join(space(row))
return result[:-1] |
# Short help
def display_summary():
print("{:<13}{}".format( 'mount', "Creates a semi-tracked/local copy of a SCM Repository" ))
# DOCOPT command line definition
USAGE = """
Creates a semi-tracked/local copy of the specified repository/branch/reference
===============================================================================
usage: evie [common-opts] mount [options] <dst> <repo> <origin> <id>
evie [common-opts] mount [options] get-success-msg
evie [common-opts] mount [options] get-error-msg
Arguments:
<dst> PARENT directory for where the copy is placed. The
directory is specified as a relative path to the root
of primary repository.
<repo> Name of the repository to mount
<origin> Path/URL to the repository
<id> Label/Tag/Hash/Version of code to be mounted
get-success-msg Returns a SCM specific message that informs the end user
of additional action(s) that may be required when
the command is successful
get-error-msg Returns a SCM specific message that informs the end user
of additional action(s) that may be required when
the command fails
Options:
-p PKGNAME Specifies the Package name if different from the <repo>
name
-b BRANCH Specifies the source branch in <repo>. The use/need
of this option in dependent on the <repo> SCM type.
--noro Do NOT mark the package as read-only in the file system
-h, --help Display help for this command
Notes:
o The command MUST be run in the root of the primary respostiory.
o The 'mount' command is different from the 'copy' in that creates
semi-tracked clone of the repository which can be updated directly from
the source <repo> at a later date (think git subtrees)
"""
| def display_summary():
print('{:<13}{}'.format('mount', 'Creates a semi-tracked/local copy of a SCM Repository'))
usage = "\nCreates a semi-tracked/local copy of the specified repository/branch/reference\n===============================================================================\nusage: evie [common-opts] mount [options] <dst> <repo> <origin> <id>\n evie [common-opts] mount [options] get-success-msg\n evie [common-opts] mount [options] get-error-msg\n\nArguments:\n <dst> PARENT directory for where the copy is placed. The\n directory is specified as a relative path to the root\n of primary repository.\n <repo> Name of the repository to mount\n <origin> Path/URL to the repository\n <id> Label/Tag/Hash/Version of code to be mounted\n\n get-success-msg Returns a SCM specific message that informs the end user\n of additional action(s) that may be required when \n the command is successful\n get-error-msg Returns a SCM specific message that informs the end user\n of additional action(s) that may be required when \n the command fails\nOptions:\n -p PKGNAME Specifies the Package name if different from the <repo> \n name\n -b BRANCH Specifies the source branch in <repo>. The use/need\n of this option in dependent on the <repo> SCM type.\n --noro Do NOT mark the package as read-only in the file system\n -h, --help Display help for this command\n\n \nNotes:\n o The command MUST be run in the root of the primary respostiory.\n o The 'mount' command is different from the 'copy' in that creates\n semi-tracked clone of the repository which can be updated directly from\n the source <repo> at a later date (think git subtrees)\n\n" |
class PLSR_SSS_Helper(object):
def __init__(self,train_data,X,mse,msemin,component,y,y_c,y_cv,attribute,importance,
prediction,dir_path,reportpath,prediction_map,modelsavepath,img_path,tran_path):
self.train_data = train_data
self.X = X
self.mse = mse
self.msemin = msemin
self.component = component
self.y = y
self.y_c = y_c
self.y_cv = y_cv
self.attribute = attribute
self.importance = importance
self.prediction = prediction
self.dir_path = dir_path
self.reportpath = reportpath
self.prediction_map = prediction_map
self.modelsavepath = modelsavepath
self.img_path = img_path
self.tran_path = tran_path
# #
#
# def __str__(self):
# return self.dir_path
| class Plsr_Sss_Helper(object):
def __init__(self, train_data, X, mse, msemin, component, y, y_c, y_cv, attribute, importance, prediction, dir_path, reportpath, prediction_map, modelsavepath, img_path, tran_path):
self.train_data = train_data
self.X = X
self.mse = mse
self.msemin = msemin
self.component = component
self.y = y
self.y_c = y_c
self.y_cv = y_cv
self.attribute = attribute
self.importance = importance
self.prediction = prediction
self.dir_path = dir_path
self.reportpath = reportpath
self.prediction_map = prediction_map
self.modelsavepath = modelsavepath
self.img_path = img_path
self.tran_path = tran_path |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 20 07:12:02 2018
@author: vishn
"""
| """
Created on Tue Nov 20 07:12:02 2018
@author: vishn
""" |
# Symmetric Difference
# Problem Link: https://www.hackerrank.com/challenges/symmetric-difference/problem
m = int(input())
marr = set(map(int, input().split()))
n = int(input())
narr = set(map(int, input().split()))
for x in sorted(marr ^ narr):
print(x)
| m = int(input())
marr = set(map(int, input().split()))
n = int(input())
narr = set(map(int, input().split()))
for x in sorted(marr ^ narr):
print(x) |
class Scene:
def __init__(self, camera, shapes, materials, lights):
self.camera = camera
self.shapes = shapes
self.materials = materials
self.lights = lights
| class Scene:
def __init__(self, camera, shapes, materials, lights):
self.camera = camera
self.shapes = shapes
self.materials = materials
self.lights = lights |
"""
entradas
salario-->int-->s
categoria-->int-->c
Salidas
aumento-->str-->au
salario nuevo-->str-->sn
"""
s = int(input("Digite el salario $"))
c = int(input("Digite una categoria del 1 al 5: "))
if (c == 1):
a = s*0.10
if (c == 2):
a = s*0.15
if (c == 3):
a = s*0.20
if (c == 4):
a = s*0.40
if (c == 5):
a = s*0.60
sn = s+a
print("su categoria es: "+str(a))
print("Valor del sueldo nuevo $" + str(sn))
| """
entradas
salario-->int-->s
categoria-->int-->c
Salidas
aumento-->str-->au
salario nuevo-->str-->sn
"""
s = int(input('Digite el salario $'))
c = int(input('Digite una categoria del 1 al 5: '))
if c == 1:
a = s * 0.1
if c == 2:
a = s * 0.15
if c == 3:
a = s * 0.2
if c == 4:
a = s * 0.4
if c == 5:
a = s * 0.6
sn = s + a
print('su categoria es: ' + str(a))
print('Valor del sueldo nuevo $' + str(sn)) |
"""
Set of processes for being in mult-processor mode within spatial package
# Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry)
# Date: 11.01.17
"""
__author__ = 'martinez'
####### HELPING FUNCTIONS
####### PROCESSES
# Radial Averaged Fourier Transform alone process
# points: array with points coordinates
# ids: indexes to points array
# dense: dense float typed tomogram (even dimensions)
# mask: binary mask (even dimensions)
# mpa: shared multiprocessing object with the results
def pr_uni_RAFT(points, ids, dense, mask, mpa):
# TODO
pass
| """
Set of processes for being in mult-processor mode within spatial package
# Author: Antonio Martinez-Sanchez (Max Planck Institute for Biochemistry)
# Date: 11.01.17
"""
__author__ = 'martinez'
def pr_uni_raft(points, ids, dense, mask, mpa):
pass |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Utils to process outputs to output_base in rbe_autoconf."""
load(
"//rules/rbe_repo:util.bzl",
"CC_CONFIG_DIR",
"JAVA_CONFIG_DIR",
"PLATFORM_DIR",
"print_exec_results",
)
def expand_outputs(ctx, bazel_version, project_root):
"""
Copies all outputs of the autoconfig rule to a directory in the project.
Also deletes the artifacts from the repo directory as they are only
meant to be used from the output_base.
Args:
ctx: The Bazel context.
bazel_version: The Bazel version string.
project_root: The output directory where configs will be copied to.
"""
if ctx.attr.output_base:
ctx.report_progress("copying outputs to project directory")
dest = project_root + "/" + ctx.attr.output_base + "/bazel_" + bazel_version + "/"
if ctx.attr.config_dir:
dest += ctx.attr.config_dir + "/"
platform_dest = dest + PLATFORM_DIR + "/"
java_dest = dest + JAVA_CONFIG_DIR + "/"
cc_dest = dest + CC_CONFIG_DIR + "/"
# Create the directories
result = ctx.execute(["mkdir", "-p", platform_dest])
print_exec_results("create platform output dir", result)
# Copy the local_config_cc files to dest/{CC_CONFIG_DIR}/
if ctx.attr.create_cc_configs:
result = ctx.execute(["mkdir", "-p", cc_dest])
print_exec_results("create cc output dir", result)
# Get the files that were created in the CC_CONFIG_DIR
ctx.file("local_config_files.sh", ("echo $(find ./%s -type f | sort -n)" % CC_CONFIG_DIR), True)
result = ctx.execute(["./local_config_files.sh"])
print_exec_results("resolve autoconf files", result)
autoconf_files = result.stdout.splitlines()[0].split(" ")
args = ["cp"] + autoconf_files + [cc_dest]
result = ctx.execute(args)
print_exec_results("copy local_config_cc outputs", result, True, args)
args = ["rm"] + autoconf_files
result = ctx.execute(args)
print_exec_results("remove local_config_cc outputs from repo dir", result, True, args)
# Copy the dest/{JAVA_CONFIG_DIR}/BUILD file
if ctx.attr.create_java_configs:
result = ctx.execute(["mkdir", "-p", java_dest])
print_exec_results("create java output dir", result)
args = ["cp", str(ctx.path(JAVA_CONFIG_DIR + "/BUILD")), java_dest]
result = ctx.execute(args)
print_exec_results("copy java_runtime BUILD", result, True, args)
args = ["rm", str(ctx.path(JAVA_CONFIG_DIR + "/BUILD"))]
result = ctx.execute(args)
print_exec_results("remove java_runtime BUILD from repo dir", result, True, args)
# Copy the dest/{PLATFORM_DIR}/BUILD file
args = ["cp", str(ctx.path(PLATFORM_DIR + "/BUILD")), platform_dest]
result = ctx.execute(args)
print_exec_results("copy platform BUILD", result, True, args)
args = ["rm", str(ctx.path(PLATFORM_DIR + "/BUILD"))]
result = ctx.execute(args)
print_exec_results("Remove platform BUILD from repo dir", result, True, args)
# Copy any additional external repos that were requested
if ctx.attr.config_repos:
for repo in ctx.attr.config_repos:
args = ["bash", "-c", "cp -r %s %s" % (repo, dest)]
result = ctx.execute(args)
print_exec_results("copy %s repo files" % repo, result, True, args)
args = ["rm", "-dr", "./%s" % repo]
result = ctx.execute(args)
print_exec_results("Remove %s repo files from repo dir" % repo, result, True, args)
dest_target = ctx.attr.output_base + "/bazel_" + bazel_version
if ctx.attr.config_dir:
dest_target += ctx.attr.config_dir + "/"
template = ctx.path(Label("@bazel_toolchains//rules/rbe_repo:.latest.bazelrc.tpl"))
ctx.template(
".latest.bazelrc",
template,
{
"%{dest_target}": dest_target,
},
False,
)
args = ["mv", str(ctx.path("./.latest.bazelrc")), project_root + "/" + ctx.attr.output_base + "/"]
result = ctx.execute(args)
print_exec_results("Move .latest.bazelrc file to outputs", result, True, args)
# TODO(ngiraldo): Generate new BUILD files that point to checked in configs
# Create an empty BUILD file so the repo can be built
ctx.file("BUILD", "", False)
| """Utils to process outputs to output_base in rbe_autoconf."""
load('//rules/rbe_repo:util.bzl', 'CC_CONFIG_DIR', 'JAVA_CONFIG_DIR', 'PLATFORM_DIR', 'print_exec_results')
def expand_outputs(ctx, bazel_version, project_root):
"""
Copies all outputs of the autoconfig rule to a directory in the project.
Also deletes the artifacts from the repo directory as they are only
meant to be used from the output_base.
Args:
ctx: The Bazel context.
bazel_version: The Bazel version string.
project_root: The output directory where configs will be copied to.
"""
if ctx.attr.output_base:
ctx.report_progress('copying outputs to project directory')
dest = project_root + '/' + ctx.attr.output_base + '/bazel_' + bazel_version + '/'
if ctx.attr.config_dir:
dest += ctx.attr.config_dir + '/'
platform_dest = dest + PLATFORM_DIR + '/'
java_dest = dest + JAVA_CONFIG_DIR + '/'
cc_dest = dest + CC_CONFIG_DIR + '/'
result = ctx.execute(['mkdir', '-p', platform_dest])
print_exec_results('create platform output dir', result)
if ctx.attr.create_cc_configs:
result = ctx.execute(['mkdir', '-p', cc_dest])
print_exec_results('create cc output dir', result)
ctx.file('local_config_files.sh', 'echo $(find ./%s -type f | sort -n)' % CC_CONFIG_DIR, True)
result = ctx.execute(['./local_config_files.sh'])
print_exec_results('resolve autoconf files', result)
autoconf_files = result.stdout.splitlines()[0].split(' ')
args = ['cp'] + autoconf_files + [cc_dest]
result = ctx.execute(args)
print_exec_results('copy local_config_cc outputs', result, True, args)
args = ['rm'] + autoconf_files
result = ctx.execute(args)
print_exec_results('remove local_config_cc outputs from repo dir', result, True, args)
if ctx.attr.create_java_configs:
result = ctx.execute(['mkdir', '-p', java_dest])
print_exec_results('create java output dir', result)
args = ['cp', str(ctx.path(JAVA_CONFIG_DIR + '/BUILD')), java_dest]
result = ctx.execute(args)
print_exec_results('copy java_runtime BUILD', result, True, args)
args = ['rm', str(ctx.path(JAVA_CONFIG_DIR + '/BUILD'))]
result = ctx.execute(args)
print_exec_results('remove java_runtime BUILD from repo dir', result, True, args)
args = ['cp', str(ctx.path(PLATFORM_DIR + '/BUILD')), platform_dest]
result = ctx.execute(args)
print_exec_results('copy platform BUILD', result, True, args)
args = ['rm', str(ctx.path(PLATFORM_DIR + '/BUILD'))]
result = ctx.execute(args)
print_exec_results('Remove platform BUILD from repo dir', result, True, args)
if ctx.attr.config_repos:
for repo in ctx.attr.config_repos:
args = ['bash', '-c', 'cp -r %s %s' % (repo, dest)]
result = ctx.execute(args)
print_exec_results('copy %s repo files' % repo, result, True, args)
args = ['rm', '-dr', './%s' % repo]
result = ctx.execute(args)
print_exec_results('Remove %s repo files from repo dir' % repo, result, True, args)
dest_target = ctx.attr.output_base + '/bazel_' + bazel_version
if ctx.attr.config_dir:
dest_target += ctx.attr.config_dir + '/'
template = ctx.path(label('@bazel_toolchains//rules/rbe_repo:.latest.bazelrc.tpl'))
ctx.template('.latest.bazelrc', template, {'%{dest_target}': dest_target}, False)
args = ['mv', str(ctx.path('./.latest.bazelrc')), project_root + '/' + ctx.attr.output_base + '/']
result = ctx.execute(args)
print_exec_results('Move .latest.bazelrc file to outputs', result, True, args)
ctx.file('BUILD', '', False) |
# https://leetcode.com/problems/climbing-stairs/
class Solution:
# def climbStairs(self, n: int) -> int:
# array = [1, 2]
# for i in range(2, n+1):
# array.append(array[i-1] + array[i-2])
# return array[n-1]
def climbStairs(self, n: int) -> int:
if n <= 2:
return n
f1, f2, f3 = 1, 2, 3
for i in range(3, n+1):
f3 = f1 + f2
f1 = f2
f2 = f3
return f3
print(Solution().climbStairs(1))
print(Solution().climbStairs(2))
print(Solution().climbStairs(3))
print(Solution().climbStairs(4))
print(Solution().climbStairs(5))
| class Solution:
def climb_stairs(self, n: int) -> int:
if n <= 2:
return n
(f1, f2, f3) = (1, 2, 3)
for i in range(3, n + 1):
f3 = f1 + f2
f1 = f2
f2 = f3
return f3
print(solution().climbStairs(1))
print(solution().climbStairs(2))
print(solution().climbStairs(3))
print(solution().climbStairs(4))
print(solution().climbStairs(5)) |
"""
The ska_tmc_cdm.messages.mccssubarray contains code that models the structured
command arguments, command responses, and attribute values for the
MCCSSubarray Tango device.
"""
| """
The ska_tmc_cdm.messages.mccssubarray contains code that models the structured
command arguments, command responses, and attribute values for the
MCCSSubarray Tango device.
""" |
def filter_data(data):
"""
Front function to filter data to perform a train
Args:
data (pd.DataFrame): a pandas dataframe with the non-filtered data
Returns:
filtered_data (pd.DataFrame): a pandas dataframe with the filtered data
"""
filtered_data = data.copy()
return data | def filter_data(data):
"""
Front function to filter data to perform a train
Args:
data (pd.DataFrame): a pandas dataframe with the non-filtered data
Returns:
filtered_data (pd.DataFrame): a pandas dataframe with the filtered data
"""
filtered_data = data.copy()
return data |
# HAUL Resources
def get(i):
return None
def use(filename):
# Do nothing, it is overridden when testing; in order to load resources at runtime
return -1 | def get(i):
return None
def use(filename):
return -1 |
def failure_message(message=None, user=None, user_group=None):
resp = '''Message failed to send, please try again later or contact administrator
from: Broadcast Admin
- Only you can see this message
'''
return resp
| def failure_message(message=None, user=None, user_group=None):
resp = 'Message failed to send, please try again later or contact administrator\n from: Broadcast Admin\n - Only you can see this message\n '
return resp |
n_str = input()
n = int(n_str)
if (n == 1):
print(1.000000000000)
else:
sum = 0.000000000000
for i in range(1, n+1):
sum += round((1.000000000000)/i, 12)
print(sum)
| n_str = input()
n = int(n_str)
if n == 1:
print(1.0)
else:
sum = 0.0
for i in range(1, n + 1):
sum += round(1.0 / i, 12)
print(sum) |
def is_rotation(s, t):
"""
Returns True iff s is a rotated version of t.
"""
return len(s) == len(t) and s in t + t
if __name__ == "__main__":
testStringPairs = [
("", ""),
("stackoverflow", "flowstackover"),
("12345", "5xy1234"),
("stackoverflaw", "overflowstack")
]
for (index, pair) in enumerate(testStringPairs):
s, t = pair
print("Test String #{}:".format(index + 1))
print("{} {} a rotated version of {}.".format(
repr(s), "is" if is_rotation(s, t) else "is not", repr(t)
)) | def is_rotation(s, t):
"""
Returns True iff s is a rotated version of t.
"""
return len(s) == len(t) and s in t + t
if __name__ == '__main__':
test_string_pairs = [('', ''), ('stackoverflow', 'flowstackover'), ('12345', '5xy1234'), ('stackoverflaw', 'overflowstack')]
for (index, pair) in enumerate(testStringPairs):
(s, t) = pair
print('Test String #{}:'.format(index + 1))
print('{} {} a rotated version of {}.'.format(repr(s), 'is' if is_rotation(s, t) else 'is not', repr(t))) |
class Redirect:
def __init__(self, url: str = ""):
self.redirect_url = url
def to_dict(self):
tmp_dict = {
"redirect_url": self.redirect_url,
}
return tmp_dict | class Redirect:
def __init__(self, url: str=''):
self.redirect_url = url
def to_dict(self):
tmp_dict = {'redirect_url': self.redirect_url}
return tmp_dict |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Rules for auto-generating the Paths_* module needed in third-party.
Some third-party Haskell packages use a Paths_{package_name}.hs file
which is auto-generated by Cabal. That file lets them
- Get the package's current version number
- Find useful data file
This file exports the "cabal_paths" rule for auto-generating that Paths module.
For usage information, see the below documentation for that rule.
"""
def _impl_path_module_gen(ctx):
base_dir = ctx.label.package + (
("/" + ctx.attr.data_dir) if ctx.attr.data_dir else ""
)
ctx.actions.expand_template(
template = ctx.file._template,
output = ctx.outputs.out,
substitutions = {
"%{module}": "Paths_" + ctx.attr.package,
"%{base_dir}": base_dir,
"%{version}": str(ctx.attr.version),
},
)
return [DefaultInfo(files = depset([ctx.outputs.out]))]
cabal_paths = rule(
implementation = _impl_path_module_gen,
attrs = {
"out": attr.output(mandatory = True),
"data_dir": attr.string(),
"package": attr.string(),
"version": attr.int_list(mandatory = True, allow_empty = False),
"_template": attr.label(
allow_single_file = True,
default = Label(
"//bzl/cabal_package:paths.template",
),
),
},
)
"""Generate a Cabal Paths_* module.
Generates a Paths_ module for use by Cabal packages.
Example usage:
haskell_binary(
name = "hlint",
srcs = [":paths"],
)
cabal_paths(
name = "paths",
package = "hlint",
version = [1, 18, 5],
# Corresponds to the Cabal "data-dir" field.
data_dir = "datafiles",
)
Args:
name: The name of the resulting library target.
package: The name (string) of the Cabal package that's being built.
data_dir: The subdirectory (relative to this package) that contains the
data files (if any). If empty, assumes the data files are at the top
level of the package.
data: The data files that this package depends on to run.
version: The version number of this package (list of ints)
**kwargs: Additonal parameters to the haskell_library.
"""
| """Rules for auto-generating the Paths_* module needed in third-party.
Some third-party Haskell packages use a Paths_{package_name}.hs file
which is auto-generated by Cabal. That file lets them
- Get the package's current version number
- Find useful data file
This file exports the "cabal_paths" rule for auto-generating that Paths module.
For usage information, see the below documentation for that rule.
"""
def _impl_path_module_gen(ctx):
base_dir = ctx.label.package + ('/' + ctx.attr.data_dir if ctx.attr.data_dir else '')
ctx.actions.expand_template(template=ctx.file._template, output=ctx.outputs.out, substitutions={'%{module}': 'Paths_' + ctx.attr.package, '%{base_dir}': base_dir, '%{version}': str(ctx.attr.version)})
return [default_info(files=depset([ctx.outputs.out]))]
cabal_paths = rule(implementation=_impl_path_module_gen, attrs={'out': attr.output(mandatory=True), 'data_dir': attr.string(), 'package': attr.string(), 'version': attr.int_list(mandatory=True, allow_empty=False), '_template': attr.label(allow_single_file=True, default=label('//bzl/cabal_package:paths.template'))})
'Generate a Cabal Paths_* module.\n\nGenerates a Paths_ module for use by Cabal packages.\n\nExample usage:\n\n haskell_binary(\n name = "hlint",\n srcs = [":paths"],\n )\n\n cabal_paths(\n name = "paths",\n package = "hlint",\n version = [1, 18, 5],\n # Corresponds to the Cabal "data-dir" field.\n data_dir = "datafiles",\n )\n\n\nArgs:\n name: The name of the resulting library target.\n package: The name (string) of the Cabal package that\'s being built.\n data_dir: The subdirectory (relative to this package) that contains the\n data files (if any). If empty, assumes the data files are at the top\n level of the package.\n data: The data files that this package depends on to run.\n version: The version number of this package (list of ints)\n **kwargs: Additonal parameters to the haskell_library.\n' |
#!/usr/bin/python
array = [0] * 43
Top = 1
Bottom = 2
Far = 4
Near = 8
Left = 16
Right = 32
scopeName = 'FDataConstants::'
#Edge map
array[Top + Far] = 'TopFar'
array[Top + Near] = 'TopNear'
array[Top + Left] = 'FTopLeft'
array[Top + Right] = 'TopRight'
array[Bottom + Far] = 'BottomFar'
array[Bottom + Near] = 'BottomNear'
array[Bottom + Left] = 'BottomLeft'
array[Bottom + Right] = 'BottomRight'
array[Far + Left] = 'FarLeft'
array[Far + Right] = 'FarRight'
array[Near + Left] = 'NearLeft'
array[Near+ Right] = 'NearRight'
#Vertex map
array[Top + Far + Left] = 'TopFarLeft'
array[Top + Far + Right] = 'TopFarRight'
array[Top + Near + Left] = 'TopNearLeft'
array[Top + Near + Right] = 'TopNearRight'
array[Bottom + Far + Left] = 'BottomFarLeft'
array[Bottom + Far + Right] = 'BottomFarRight'
array[Bottom + Near + Left] = 'BottomNearLeft'
array[Bottom + Near + Right] = 'BottomNearRight'
for e in array:
if e == 0:
print(str(e), end=', '),
else:
print('\n' + scopeName + str(e), end=', '),
| array = [0] * 43
top = 1
bottom = 2
far = 4
near = 8
left = 16
right = 32
scope_name = 'FDataConstants::'
array[Top + Far] = 'TopFar'
array[Top + Near] = 'TopNear'
array[Top + Left] = 'FTopLeft'
array[Top + Right] = 'TopRight'
array[Bottom + Far] = 'BottomFar'
array[Bottom + Near] = 'BottomNear'
array[Bottom + Left] = 'BottomLeft'
array[Bottom + Right] = 'BottomRight'
array[Far + Left] = 'FarLeft'
array[Far + Right] = 'FarRight'
array[Near + Left] = 'NearLeft'
array[Near + Right] = 'NearRight'
array[Top + Far + Left] = 'TopFarLeft'
array[Top + Far + Right] = 'TopFarRight'
array[Top + Near + Left] = 'TopNearLeft'
array[Top + Near + Right] = 'TopNearRight'
array[Bottom + Far + Left] = 'BottomFarLeft'
array[Bottom + Far + Right] = 'BottomFarRight'
array[Bottom + Near + Left] = 'BottomNearLeft'
array[Bottom + Near + Right] = 'BottomNearRight'
for e in array:
if e == 0:
(print(str(e), end=', '),)
else:
(print('\n' + scopeName + str(e), end=', '),) |
class Website(object):
def __init__(self, site):
self.URL = site
class Internet(object):
def __init__(self):
self.url_list = dict()
def add_url(self, website):
if website.URL in self.url_list:
self.url_list[website.URL] += 1
else:
self.url_list[website.URL] = 1
def solution(self):
return sorted(self.url_list.items(), key=lambda i: (-i[1], i[0]))
def solve(S, N):
net = Internet()
for s in S:
net.add_url(s)
return net.solution()
# write your code here
N = int(input())
S = []
for _ in range(N):
S.append(Website(input()))
out_ = solve(S, N)
print(len(out_))
for i_out_ in out_:
print(i_out_[0]) | class Website(object):
def __init__(self, site):
self.URL = site
class Internet(object):
def __init__(self):
self.url_list = dict()
def add_url(self, website):
if website.URL in self.url_list:
self.url_list[website.URL] += 1
else:
self.url_list[website.URL] = 1
def solution(self):
return sorted(self.url_list.items(), key=lambda i: (-i[1], i[0]))
def solve(S, N):
net = internet()
for s in S:
net.add_url(s)
return net.solution()
n = int(input())
s = []
for _ in range(N):
S.append(website(input()))
out_ = solve(S, N)
print(len(out_))
for i_out_ in out_:
print(i_out_[0]) |
max= 0
a = 2
b = 3
if a < b: max= b
if b < a: max= a
assert (max == a or max == b) and max >= a and max >= b
| max = 0
a = 2
b = 3
if a < b:
max = b
if b < a:
max = a
assert (max == a or max == b) and max >= a and (max >= b) |
def rotateLeft(array_list , num_rotate ):
alist = list(array_list)
rotated_list = alist[num_rotate :]+alist[:num_rotate ]
return rotated_list
array_list = []
n = int(input("Enter number of elements in array list : "))
for i in range(0, n):
elem = int(input())
array_list.append(elem)
num_rotate=int(input('Enter Number of rotations to be made: '))
print("The List after rotations is: ")
print(rotateLeft(array_list, num_rotate)) | def rotate_left(array_list, num_rotate):
alist = list(array_list)
rotated_list = alist[num_rotate:] + alist[:num_rotate]
return rotated_list
array_list = []
n = int(input('Enter number of elements in array list : '))
for i in range(0, n):
elem = int(input())
array_list.append(elem)
num_rotate = int(input('Enter Number of rotations to be made: '))
print('The List after rotations is: ')
print(rotate_left(array_list, num_rotate)) |
"""Module describes keys and types of nodes
for an internal structure which is used
to render the difference using formatters"""
# left part of the dictionary
KEY = 'KEY'
VALUE = 'VALUE'
STATE = 'STATE'
# if the type is CHANGED then the left part consists
# of these two keys instead of VALUE
VALUE_LEFT = 'VALUE_LEFT'
VALUE_RIGHT = 'VALUE_RIGHT'
# right part of the dictionary
# Node types
ADDED = 'ADDED'
DELETED = 'DELETED'
UNCHANGED = 'UNCHANGED'
CHILDREN = 'CHILDREN'
CHANGED = 'CHANGED'
ROOT = 'ROOT'
| """Module describes keys and types of nodes
for an internal structure which is used
to render the difference using formatters"""
key = 'KEY'
value = 'VALUE'
state = 'STATE'
value_left = 'VALUE_LEFT'
value_right = 'VALUE_RIGHT'
added = 'ADDED'
deleted = 'DELETED'
unchanged = 'UNCHANGED'
children = 'CHILDREN'
changed = 'CHANGED'
root = 'ROOT' |
class RefBuilderBackend:
def __init__(self, ref_name):
self.ref_name = ref_name
def resolve_attr(self, attr):
return getattr(RefBuilder(self.ref_name), attr)
def resolve_item(self, item):
return RefBuilder(self.ref_name)[item]
class DataBackend:
def __init__(self, data):
self.data = data
def resolve_attr(self, attr):
try:
return self.data[attr]
except KeyError:
raise AttributeError
def resolve_item(self, item):
return self.data[item]
class LazyResource:
def __init__(self, ref_name):
self.__backend = RefBuilderBackend(ref_name)
def __getattr__(self, attr: str):
return self.__backend.resolve_attr(attr)
def __getitem__(self, item):
return self.__backend.resolve_item(item)
def load_data(self, data):
self.__backend = DataBackend(data)
class RefBuilder(str):
_inner: str
def __new__(cls, content):
instance = str.__new__(cls, '@{%s}' % content)
instance._inner = content
return instance
def __getattr__(self, attr):
return RefBuilder('.'.join((self._inner, attr)))
def __getitem__(self, key):
return RefBuilder('{}[{}]'.format(self._inner, key))
class Client:
api_base = '/services/data/v38.0'
class CompositeClient:
def __init__(self, client=Client):
self.client = client
self.request_queue = {}
def get(self, resource_name, id):
ref = '{}{}'.format(resource_name, len(self.request_queue))
resource = LazyResource(ref)
self.request_queue[ref] = dict(
resource=resource,
payload=dict(
method='GET',
url=self.client.api_base + f'/sobjects/{resource_name}/{id}',
referenceId=ref,
)
)
return resource
def create(self, resource_name, payload):
ref = '{}{}'.format(resource_name, len(self.request_queue))
resource = LazyResource(ref)
self.request_queue[ref] = dict(
resource=resource,
payload=dict(
method='POST',
url=self.client.api_base + f'/sobjects/{resource_name}/',
referenceId=ref,
body=payload,
)
)
return resource
def build_payload(self):
return {
'compositeRequest': [req['payload'] for req in self.request_queue.values()]
}
def load_data(self, data):
for response in data['compositeResponse']:
resource = self.request_queue.pop(response['referenceId'])['resource']
resource.load_data(response['body'])
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
return
composite = CompositeClient
"""
with CompositeClient() as client:
account = client.get('Account', '00123983903')
opportunity = client.get('Opportunity', account.OpportunityId)
proposal = client.create('Proposal', dict(
OpportunityId=opportunity.Id,
Name=f"{account.Name} - {opportunity.Commission}",
))
import pprint
pprint.pprint(client.build_payload())
fixture = {
'compositeResponse': [{
'referenceId': 'Account0',
'body': {
'Id': '00123983903',
'OpportunityId': '34534556234',
'Name': 'Salesforce Dave!',
}
}, {
'referenceId': 'Opportunity1',
'body': {
'Id': '34534556234',
'Commission': 5000000,
}
}, {
'referenceId': 'Proposal2',
'body': {
'Id': '02059305356',
}
}]
}
print(account.Id)
client.load_data(fixture)
assert account.Id == '00123983903'
assert account['Name'] == 'Salesforce Dave!'
assert account.Name == 'Salesforce Dave!'
"""
| class Refbuilderbackend:
def __init__(self, ref_name):
self.ref_name = ref_name
def resolve_attr(self, attr):
return getattr(ref_builder(self.ref_name), attr)
def resolve_item(self, item):
return ref_builder(self.ref_name)[item]
class Databackend:
def __init__(self, data):
self.data = data
def resolve_attr(self, attr):
try:
return self.data[attr]
except KeyError:
raise AttributeError
def resolve_item(self, item):
return self.data[item]
class Lazyresource:
def __init__(self, ref_name):
self.__backend = ref_builder_backend(ref_name)
def __getattr__(self, attr: str):
return self.__backend.resolve_attr(attr)
def __getitem__(self, item):
return self.__backend.resolve_item(item)
def load_data(self, data):
self.__backend = data_backend(data)
class Refbuilder(str):
_inner: str
def __new__(cls, content):
instance = str.__new__(cls, '@{%s}' % content)
instance._inner = content
return instance
def __getattr__(self, attr):
return ref_builder('.'.join((self._inner, attr)))
def __getitem__(self, key):
return ref_builder('{}[{}]'.format(self._inner, key))
class Client:
api_base = '/services/data/v38.0'
class Compositeclient:
def __init__(self, client=Client):
self.client = client
self.request_queue = {}
def get(self, resource_name, id):
ref = '{}{}'.format(resource_name, len(self.request_queue))
resource = lazy_resource(ref)
self.request_queue[ref] = dict(resource=resource, payload=dict(method='GET', url=self.client.api_base + f'/sobjects/{resource_name}/{id}', referenceId=ref))
return resource
def create(self, resource_name, payload):
ref = '{}{}'.format(resource_name, len(self.request_queue))
resource = lazy_resource(ref)
self.request_queue[ref] = dict(resource=resource, payload=dict(method='POST', url=self.client.api_base + f'/sobjects/{resource_name}/', referenceId=ref, body=payload))
return resource
def build_payload(self):
return {'compositeRequest': [req['payload'] for req in self.request_queue.values()]}
def load_data(self, data):
for response in data['compositeResponse']:
resource = self.request_queue.pop(response['referenceId'])['resource']
resource.load_data(response['body'])
def __enter__(self):
return self
def __exit__(self, *args, **kwargs):
return
composite = CompositeClient
'\nwith CompositeClient() as client:\n account = client.get(\'Account\', \'00123983903\')\n opportunity = client.get(\'Opportunity\', account.OpportunityId)\n proposal = client.create(\'Proposal\', dict(\n OpportunityId=opportunity.Id,\n Name=f"{account.Name} - {opportunity.Commission}",\n ))\n\n\nimport pprint\npprint.pprint(client.build_payload())\n\nfixture = {\n \'compositeResponse\': [{\n \'referenceId\': \'Account0\',\n \'body\': {\n \'Id\': \'00123983903\',\n \'OpportunityId\': \'34534556234\',\n \'Name\': \'Salesforce Dave!\',\n }\n }, {\n \'referenceId\': \'Opportunity1\',\n \'body\': {\n \'Id\': \'34534556234\',\n \'Commission\': 5000000,\n }\n }, {\n \'referenceId\': \'Proposal2\',\n \'body\': {\n \'Id\': \'02059305356\',\n }\n }]\n}\n\nprint(account.Id)\n\nclient.load_data(fixture)\n\n\nassert account.Id == \'00123983903\'\nassert account[\'Name\'] == \'Salesforce Dave!\'\nassert account.Name == \'Salesforce Dave!\'\n' |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class MyClass(object):
pass
def unpredictable(obj):
"""Returns a new list containing obj.
>>> unpredictable(MyClass())
<doctest_unpredictable.MyClass object at 0x10055a2d0>
"""
return obj
| class Myclass(object):
pass
def unpredictable(obj):
"""Returns a new list containing obj.
>>> unpredictable(MyClass())
<doctest_unpredictable.MyClass object at 0x10055a2d0>
"""
return obj |
#createMinMaxFunction.py
def minimum_value(lst):
#check if any ints or floats are in the list
type_list = check_list_types(lst)
#if not, return error
if float not in type_list and int not in type_list:
return "error"
# if not create check every value in list against the value assigned to minimum
# default value for minimum is inf
minimum = float('inf')
for val in lst:
try:
if val < minimum:
minimum = val
except:
return_operator_error(val)
return minimum
def maximum_value(lst):
#check if any ints or floats are in the list
type_list = check_list_types(lst)
#if not, return error
if float not in type_list and int not in type_list:
return "error"
# if not create check every value in list against the value assigned to minimum
# default value for minimum is inf
maximum = float('-inf')
for val in lst:
try:
if val > maximum:
maximum = val
except:
return_operator_error(val)
return maximum
def return_operator_error(val):
print("object is type:", type(val), "Cannot apply operator")
def check_list_types(lst):
# create a list called type_list that records type every element in lst
type_list = [type(val) for val in lst]
#reduce this list with set() to record each type only once
#convert set() to list()
types = list(set(type_list))
return types
list1 = [12,24,33,485]
string_list = ["These", "are", "strings", "not", "values"]
mixed_list = [1,2,35,"fdsajfsa",3128473217980]
min_list1 = minimum_value(list1)
max_list1 = maximum_value(list1)
min_string = minimum_value(string_list)
max_string = maximum_value(string_list)
min_mixed = minimum_value(mixed_list)
max_mixed = maximum_value(mixed_list)
print("Minimum value from list1:", min_list1)
print("Maximum value from list1:", max_list1)
print("Minimum value from string_list:", min_string)
print("Maximum value from string_list:", max_string)
print("Minimum value from mixed_list:", min_mixed)
print("Maximum value from mixed_list:", max_mixed) | def minimum_value(lst):
type_list = check_list_types(lst)
if float not in type_list and int not in type_list:
return 'error'
minimum = float('inf')
for val in lst:
try:
if val < minimum:
minimum = val
except:
return_operator_error(val)
return minimum
def maximum_value(lst):
type_list = check_list_types(lst)
if float not in type_list and int not in type_list:
return 'error'
maximum = float('-inf')
for val in lst:
try:
if val > maximum:
maximum = val
except:
return_operator_error(val)
return maximum
def return_operator_error(val):
print('object is type:', type(val), 'Cannot apply operator')
def check_list_types(lst):
type_list = [type(val) for val in lst]
types = list(set(type_list))
return types
list1 = [12, 24, 33, 485]
string_list = ['These', 'are', 'strings', 'not', 'values']
mixed_list = [1, 2, 35, 'fdsajfsa', 3128473217980]
min_list1 = minimum_value(list1)
max_list1 = maximum_value(list1)
min_string = minimum_value(string_list)
max_string = maximum_value(string_list)
min_mixed = minimum_value(mixed_list)
max_mixed = maximum_value(mixed_list)
print('Minimum value from list1:', min_list1)
print('Maximum value from list1:', max_list1)
print('Minimum value from string_list:', min_string)
print('Maximum value from string_list:', max_string)
print('Minimum value from mixed_list:', min_mixed)
print('Maximum value from mixed_list:', max_mixed) |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
primes = [2, 3, 5, 7]
def is_prime(n):
"""
A function that checks if a given number n is a prime looping
through it and, possibly, expanding the array/list of known
primes only if/when necessary (ie: as soon as you check for a
potential prime which is greater than a given threshold for each n, stop).
:param n:
:return:
"""
if n < 2:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if is_prime(i) and i not in primes:
primes.append(i)
if n % i == 0:
return False
return True
| primes = [2, 3, 5, 7]
def is_prime(n):
"""
A function that checks if a given number n is a prime looping
through it and, possibly, expanding the array/list of known
primes only if/when necessary (ie: as soon as you check for a
potential prime which is greater than a given threshold for each n, stop).
:param n:
:return:
"""
if n < 2:
return False
for i in range(3, int(n ** 0.5) + 1, 2):
if is_prime(i) and i not in primes:
primes.append(i)
if n % i == 0:
return False
return True |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 01:37:45 2018
@author: 51667
"""
qzMoneyCnsmpt = [0 for i in range(41)]
qzMoneyCnsmpt[1] = 43
for i in range(1,40):
qzMoneyCnsmpt[i + 1] = qzMoneyCnsmpt[i] + i + 5.5
qzCumMoneyCnsmpt = [0 for i in range(41)]
for i in range(40):
qzCumMoneyCnsmpt[i + 1] = qzCumMoneyCnsmpt[i] + qzMoneyCnsmpt[i + 1]
qzCumExpCnspmt = [4*n for n in qzCumMoneyCnsmpt] | """
Created on Mon Jul 9 01:37:45 2018
@author: 51667
"""
qz_money_cnsmpt = [0 for i in range(41)]
qzMoneyCnsmpt[1] = 43
for i in range(1, 40):
qzMoneyCnsmpt[i + 1] = qzMoneyCnsmpt[i] + i + 5.5
qz_cum_money_cnsmpt = [0 for i in range(41)]
for i in range(40):
qzCumMoneyCnsmpt[i + 1] = qzCumMoneyCnsmpt[i] + qzMoneyCnsmpt[i + 1]
qz_cum_exp_cnspmt = [4 * n for n in qzCumMoneyCnsmpt] |
def main():
n = int(input())
p = []
for _ in range(n):
p.append(input())
k = p.copy()
k.sort()
# print(k, p)
if k == p:
print("INCREASING")
return
# print(reversed(k), p, reversed(k) == p)
if list(reversed(k)) == p:
print("DECREASING")
else:
print("NEITHER")
return
if __name__ == "__main__":
main()
| def main():
n = int(input())
p = []
for _ in range(n):
p.append(input())
k = p.copy()
k.sort()
if k == p:
print('INCREASING')
return
if list(reversed(k)) == p:
print('DECREASING')
else:
print('NEITHER')
return
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.