content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class Hover():
"""
Generate hover information
"""
def hover(self, ws, doc, position):
# return {'contents': '.hover.'}
return None
| class Hover:
"""
Generate hover information
"""
def hover(self, ws, doc, position):
return None |
# -*- coding: utf-8 -*-
dict1 = {'Name':'Zara','Age': 18, 'Gender': ['Female','Les']}
print(len(dict1))
print(dict1['Name'])
del dict1['Name']
dict1['Name'] = "none" #change the factor
print(dict1['Name'])
print(dict1)
print(str(dict1)) #same
list1 = list(range(20)) # a list 0-19
print(list1)
print(dict.keys(dict1)) #print the keys of dict1
dict2 = {} #list updating
dict2.update(dict1)
print(dict2) | dict1 = {'Name': 'Zara', 'Age': 18, 'Gender': ['Female', 'Les']}
print(len(dict1))
print(dict1['Name'])
del dict1['Name']
dict1['Name'] = 'none'
print(dict1['Name'])
print(dict1)
print(str(dict1))
list1 = list(range(20))
print(list1)
print(dict.keys(dict1))
dict2 = {}
dict2.update(dict1)
print(dict2) |
def largest(test):
largest = []
for i in range(test):
size = int(input())
elements = input().split(" ", size)
lst = []
for j in elements:
lst.append(int(j))
largest.append(max(lst))
for i in largest:
print(i)
Test_cases = int(input())
largest(Test_cases)
| def largest(test):
largest = []
for i in range(test):
size = int(input())
elements = input().split(' ', size)
lst = []
for j in elements:
lst.append(int(j))
largest.append(max(lst))
for i in largest:
print(i)
test_cases = int(input())
largest(Test_cases) |
class Node(object):
def __init__(self, key, value, left=None, right=None, parent=None):
self.key = key
self.value = value
self.parent = parent
self.right_child = right
self.left_child = left
self.balance_factor = 0
def has_right_child(self):
return self.right_child is not None
def has_left_child(self):
return self.left_child is not None
def is_right_child(self):
return self.parent is not None and self.parent.right_child == self
def is_left_child(self):
return self.parent is not None and self.parent.left_child == self
def is_root(self):
return self.parent is None
def is_leaf(self):
return not self.is_root()
def has_any_children(self):
return self.left_child is not None or self.right_child is not None
def has_both_children(self):
return self.has_right_child() and self.has_left_child()
def get_only_child(self):
# quick note:
# assertions are supposed to be used in this context.
# their purpose is to make my assumptions about the use of this api known to outsiders
assert self.has_any_children() and not self.has_both_children()
if self.right_child is not None:
return self.right_child
else:
return self.left_child
def __repr__(self):
return "<Node key: {}>".format(self.key)
| class Node(object):
def __init__(self, key, value, left=None, right=None, parent=None):
self.key = key
self.value = value
self.parent = parent
self.right_child = right
self.left_child = left
self.balance_factor = 0
def has_right_child(self):
return self.right_child is not None
def has_left_child(self):
return self.left_child is not None
def is_right_child(self):
return self.parent is not None and self.parent.right_child == self
def is_left_child(self):
return self.parent is not None and self.parent.left_child == self
def is_root(self):
return self.parent is None
def is_leaf(self):
return not self.is_root()
def has_any_children(self):
return self.left_child is not None or self.right_child is not None
def has_both_children(self):
return self.has_right_child() and self.has_left_child()
def get_only_child(self):
assert self.has_any_children() and (not self.has_both_children())
if self.right_child is not None:
return self.right_child
else:
return self.left_child
def __repr__(self):
return '<Node key: {}>'.format(self.key) |
if __name__ == '__main__':
N = int(input())
arr = []
for _ in range(N):
s = input()
l = s.split(" ")
if l[0] == "print":
print(arr)
elif l[0] == "sort":
arr.sort()
elif l[0] == "append":
arr.append(int(l[1]))
elif l[0] == "reverse":
arr.reverse()
elif l[0] == "insert":
arr.insert(int(l[1]), int(l[2]))
elif l[0] == "pop":
arr.pop()
elif l[0] == "remove":
arr.remove(int(l[1]))
| if __name__ == '__main__':
n = int(input())
arr = []
for _ in range(N):
s = input()
l = s.split(' ')
if l[0] == 'print':
print(arr)
elif l[0] == 'sort':
arr.sort()
elif l[0] == 'append':
arr.append(int(l[1]))
elif l[0] == 'reverse':
arr.reverse()
elif l[0] == 'insert':
arr.insert(int(l[1]), int(l[2]))
elif l[0] == 'pop':
arr.pop()
elif l[0] == 'remove':
arr.remove(int(l[1])) |
gdbsettings=[
"set follow-fork-mode child",
"catch fork"
]
pipe_write_retries=5 | gdbsettings = ['set follow-fork-mode child', 'catch fork']
pipe_write_retries = 5 |
"""
This module contains the main class to be used in custom bridges.
Methods from :class:`Bridge` class should be used in other bridges
"""
__all__ = ['Bridge', ]
class Bridge:
"""Main bridge class containing basic functions."""
@staticmethod
def noop(_model, _gui):
"""Do nothing."""
@staticmethod
def exit_app(_model, gui):
"""Exit GUI application."""
gui.exit_app()
@staticmethod
def speed(dspeed):
"""Change simulation speed."""
def func(model, _gui):
"""Apply speed."""
model.apply_speed(dspeed)
return func
@staticmethod
def toggle_pause(model, _gui):
"""Pause/unpause simulation."""
model.toggle_pause()
@staticmethod
def toggle_sysinfo(_model, gui):
"""Turn system info panel on/off."""
gui.sysinfo.toggle()
| """
This module contains the main class to be used in custom bridges.
Methods from :class:`Bridge` class should be used in other bridges
"""
__all__ = ['Bridge']
class Bridge:
"""Main bridge class containing basic functions."""
@staticmethod
def noop(_model, _gui):
"""Do nothing."""
@staticmethod
def exit_app(_model, gui):
"""Exit GUI application."""
gui.exit_app()
@staticmethod
def speed(dspeed):
"""Change simulation speed."""
def func(model, _gui):
"""Apply speed."""
model.apply_speed(dspeed)
return func
@staticmethod
def toggle_pause(model, _gui):
"""Pause/unpause simulation."""
model.toggle_pause()
@staticmethod
def toggle_sysinfo(_model, gui):
"""Turn system info panel on/off."""
gui.sysinfo.toggle() |
#from const import cw
#from const import ccw
cw,ccw = 1,-1
class Point:
x = 0
y = 0
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
def __add__(self, p):
return Point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return Point(self.x - p.x, self.y - p.y)
def translate(self, x, y):
self.x += x
self.y += y
return self
def dup(self):
return Point(self.x, self.y)
# def _rotcw(self):
# x,y = self.x,self.y
# self.x, self.y = y, -x
# return self
#
# def _rotccw(self):
# x,y = self.x,self.y
# self.x,self.y = -y, x
# return self
def rotate(self, pivot, cdir = cw):
x = self.x
y = self.y
if cdir == cw:
self.x = y - pivot.y + pivot.x
self.y = pivot.x - x + pivot.y
return self
# return (self - pivot)._rotcw() + pivot
else:
self.x = pivot.y - y + pivot.x
self.y = x - pivot.x + pivot.y
# return (self - pivot)._rotccw() + pivot
| (cw, ccw) = (1, -1)
class Point:
x = 0
y = 0
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, p):
return point(self.x + p.x, self.y + p.y)
def __sub__(self, p):
return point(self.x - p.x, self.y - p.y)
def translate(self, x, y):
self.x += x
self.y += y
return self
def dup(self):
return point(self.x, self.y)
def rotate(self, pivot, cdir=cw):
x = self.x
y = self.y
if cdir == cw:
self.x = y - pivot.y + pivot.x
self.y = pivot.x - x + pivot.y
return self
else:
self.x = pivot.y - y + pivot.x
self.y = x - pivot.x + pivot.y |
# -*- coding: utf-8 -*-
"""
Created on Tue May 4 06:26:45 2021
@author: Oluchukwu Okoh
"""
class Solution(object):
def runningSum(nums):
return [sum(nums[:i+1]) for i in range(len(nums))]
| """
Created on Tue May 4 06:26:45 2021
@author: Oluchukwu Okoh
"""
class Solution(object):
def running_sum(nums):
return [sum(nums[:i + 1]) for i in range(len(nums))] |
_SDP_SOURCE_PORT = 7
_SDP_SOURCE_CPU = 31
_SDP_TAG = 0xFF
def update_sdp_header_for_udp_send(sdp_header, source_x, source_y):
""" Apply defaults to the sdp header for sending over UDP
:param sdp_header: The SDP header values
:type sdp_header:\
:py:class:`spinnman.messages.sdp.sdp_header.SDPHeader`
:return: Nothing is returned
"""
sdp_header.tag = _SDP_TAG
sdp_header.source_port = _SDP_SOURCE_PORT
sdp_header.source_cpu = _SDP_SOURCE_CPU
sdp_header.source_chip_x = source_x
sdp_header.source_chip_y = source_y
| _sdp_source_port = 7
_sdp_source_cpu = 31
_sdp_tag = 255
def update_sdp_header_for_udp_send(sdp_header, source_x, source_y):
""" Apply defaults to the sdp header for sending over UDP
:param sdp_header: The SDP header values
:type sdp_header: :py:class:`spinnman.messages.sdp.sdp_header.SDPHeader`
:return: Nothing is returned
"""
sdp_header.tag = _SDP_TAG
sdp_header.source_port = _SDP_SOURCE_PORT
sdp_header.source_cpu = _SDP_SOURCE_CPU
sdp_header.source_chip_x = source_x
sdp_header.source_chip_y = source_y |
# coding: utf-8
class Context:
"""
Context which used by all request builders
:ivar http_client: Default HTTP client
:ivar apikey: API key for access to the Twelvedata API
:ivar base_url: Base URL for Twelvedata API
:ivar defaults: Default parameters that will be used by request builders.
"""
http_client = None
apikey = None
base_url = None
defaults = None
@classmethod
def from_context(cls, ctx):
"""
Creates copy of specified Context
"""
instance = cls()
instance.http_client = ctx.http_client
instance.apikey = ctx.apikey
instance.base_url = ctx.base_url
instance.defaults = dict(ctx.defaults or {})
return instance
| class Context:
"""
Context which used by all request builders
:ivar http_client: Default HTTP client
:ivar apikey: API key for access to the Twelvedata API
:ivar base_url: Base URL for Twelvedata API
:ivar defaults: Default parameters that will be used by request builders.
"""
http_client = None
apikey = None
base_url = None
defaults = None
@classmethod
def from_context(cls, ctx):
"""
Creates copy of specified Context
"""
instance = cls()
instance.http_client = ctx.http_client
instance.apikey = ctx.apikey
instance.base_url = ctx.base_url
instance.defaults = dict(ctx.defaults or {})
return instance |
x = input("Type a number: ")
y = input("Type another number: ")
sum = int(x) + int(y)
print("The sum is: ", sum)
| x = input('Type a number: ')
y = input('Type another number: ')
sum = int(x) + int(y)
print('The sum is: ', sum) |
brd = {
'name': ('StickIt! V1', 'StickIt! V2', 'StickIt! V3'),
'port': {
'pmod' : {
'pm1' : {
'd0': 'ch15',
'd1': 'ch11',
'd2': 'chclk',
'd3': 'ch28',
'd4': 'ch16',
'd5': 'ch13',
'd6': 'ch0',
'd7': 'ch14',
},
'pm2' : {
'd0': 'ch17',
'd1': 'ch15',
'd2': 'ch1',
'd3': 'chclk',
'd4': 'ch18',
'd5': 'ch16',
'd6': 'ch3',
'd7': 'ch0',
},
'pm3' : {
'd0': 'ch20',
'd1': 'ch17',
'd2': 'ch4',
'd3': 'ch1',
'd4': 'ch21',
'd5': 'ch18',
'd6': 'ch5',
'd7': 'ch3',
},
'pm4' : {
'd0': 'ch22',
'd1': 'ch20',
'd2': 'ch6',
'd3': 'ch4',
'd4': 'ch23',
'd5': 'ch21',
'd6': 'ch7',
'd7': 'ch5',
},
'pm5' : {
'd0': 'ch8',
'd1': 'ch22',
'd2': 'ch25',
'd3': 'ch6',
'd4': 'ch26',
'd5': 'ch23',
'd6': 'ch10',
'd7': 'ch7',
},
'pm6' : {
'd0': 'ch11',
'd1': 'ch8',
'd2': 'ch28',
'd3': 'ch25',
'd4': 'ch13',
'd5': 'ch26',
'd6': 'ch14',
'd7': 'ch10',
}
},
'dualpmod' : {
'pm1+pm2' : {
'd0': 'ch15',
'd1': 'ch11',
'd2': 'chclk',
'd3': 'ch28',
'd4': 'ch16',
'd5': 'ch13',
'd6': 'ch0',
'd7': 'ch14',
'd8': 'ch17',
'd9': 'ch15',
'd10': 'ch1',
'd11': 'chclk',
'd12': 'ch18',
'd13': 'ch16',
'd14': 'ch3',
'd15': 'ch0',
},
'pm2+pm3' : {
'd0': 'ch17',
'd1': 'ch15',
'd2': 'ch1',
'd3': 'chclk',
'd4': 'ch18',
'd5': 'ch16',
'd6': 'ch3',
'd7': 'ch0',
'd8': 'ch20',
'd9': 'ch17',
'd10': 'ch4',
'd11': 'ch1',
'd12': 'ch21',
'd13': 'ch18',
'd14': 'ch5',
'd15': 'ch3',
},
'pm4+pm5' : {
'd0': 'ch22',
'd1': 'ch20',
'd2': 'ch6',
'd3': 'ch4',
'd4': 'ch23',
'd5': 'ch21',
'd6': 'ch7',
'd7': 'ch5',
'd8': 'ch8',
'd9': 'ch22',
'd10': 'ch25',
'd11': 'ch6',
'd12': 'ch26',
'd13': 'ch23',
'd14': 'ch10',
'd15': 'ch7',
},
'pm5+pm6' : {
'd0': 'ch8',
'd1': 'ch22',
'd2': 'ch25',
'd3': 'ch6',
'd4': 'ch26',
'd5': 'ch23',
'd6': 'ch10',
'd7': 'ch7',
'd8': 'ch11',
'd9': 'ch8',
'd10': 'ch28',
'd11': 'ch25',
'd12': 'ch13',
'd13': 'ch26',
'd14': 'ch14',
'd15': 'ch10',
}
},
'wing' : {
'wing1' : {
'd0': 'ch3',
'd1': 'ch18',
'd2': 'ch1',
'd3': 'ch17',
'd4': 'ch0',
'd5': 'ch16',
'd6': 'chclk',
'd7': 'ch15',
},
'wing2' : {
'd0': 'ch7',
'd1': 'ch23',
'd2': 'ch6',
'd3': 'ch22',
'd4': 'ch5',
'd5': 'ch21',
'd6': 'ch4',
'd7': 'ch20',
},
'wing3' : {
'd0': 'ch14',
'd1': 'ch13',
'd2': 'ch28',
'd3': 'ch11',
'd4': 'ch10',
'd5': 'ch26',
'd6': 'ch25',
'd7': 'ch8',
}
},
'dualwing' : {
'wing1+wing2' : {
'd0': 'ch7',
'd1': 'ch23',
'd2': 'ch6',
'd3': 'ch22',
'd4': 'ch5',
'd5': 'ch21',
'd6': 'ch4',
'd7': 'ch20',
'd8': 'ch3',
'd9': 'ch18',
'd10': 'ch1',
'd11': 'ch17',
'd12': 'ch0',
'd13': 'ch16',
'd14': 'chclk',
'd15': 'ch15',
},
'wing2+wing3' : {
'd0': 'ch14',
'd1': 'ch13',
'd2': 'ch28',
'd3': 'ch11',
'd4': 'ch10',
'd5': 'ch26',
'd6': 'ch25',
'd7': 'ch8',
'd8': 'ch7',
'd9': 'ch23',
'd10': 'ch6',
'd11': 'ch22',
'd12': 'ch5',
'd13': 'ch21',
'd14': 'ch4',
'd15': 'ch20',
}
},
'xula' : {
'default' : {
'chclk' : 'chclk',
'ch0' : 'ch0',
'ch1' : 'ch1',
'ch2' : 'ch2',
'ch3' : 'ch3',
'ch4' : 'ch4',
'ch5' : 'ch5',
'ch6' : 'ch6',
'ch7' : 'ch7',
'ch8' : 'ch8',
'ch9' : 'ch9',
'ch10' : 'ch10',
'ch11' : 'ch11',
'ch12' : 'ch12',
'ch13' : 'ch13',
'ch14' : 'ch14',
'ch15' : 'ch15',
'ch16' : 'ch16',
'ch17' : 'ch17',
'ch18' : 'ch18',
'ch19' : 'ch19',
'ch20' : 'ch20',
'ch21' : 'ch21',
'ch22' : 'ch22',
'ch23' : 'ch23',
'ch24' : 'ch24',
'ch25' : 'ch25',
'ch26' : 'ch26',
'ch27' : 'ch27',
'ch28' : 'ch28',
'ch29' : 'ch29',
'ch30' : 'ch30',
'ch31' : 'ch31',
'ch32' : 'ch32',
'ch33' : 'ch33'
}
}
}
}
| brd = {'name': ('StickIt! V1', 'StickIt! V2', 'StickIt! V3'), 'port': {'pmod': {'pm1': {'d0': 'ch15', 'd1': 'ch11', 'd2': 'chclk', 'd3': 'ch28', 'd4': 'ch16', 'd5': 'ch13', 'd6': 'ch0', 'd7': 'ch14'}, 'pm2': {'d0': 'ch17', 'd1': 'ch15', 'd2': 'ch1', 'd3': 'chclk', 'd4': 'ch18', 'd5': 'ch16', 'd6': 'ch3', 'd7': 'ch0'}, 'pm3': {'d0': 'ch20', 'd1': 'ch17', 'd2': 'ch4', 'd3': 'ch1', 'd4': 'ch21', 'd5': 'ch18', 'd6': 'ch5', 'd7': 'ch3'}, 'pm4': {'d0': 'ch22', 'd1': 'ch20', 'd2': 'ch6', 'd3': 'ch4', 'd4': 'ch23', 'd5': 'ch21', 'd6': 'ch7', 'd7': 'ch5'}, 'pm5': {'d0': 'ch8', 'd1': 'ch22', 'd2': 'ch25', 'd3': 'ch6', 'd4': 'ch26', 'd5': 'ch23', 'd6': 'ch10', 'd7': 'ch7'}, 'pm6': {'d0': 'ch11', 'd1': 'ch8', 'd2': 'ch28', 'd3': 'ch25', 'd4': 'ch13', 'd5': 'ch26', 'd6': 'ch14', 'd7': 'ch10'}}, 'dualpmod': {'pm1+pm2': {'d0': 'ch15', 'd1': 'ch11', 'd2': 'chclk', 'd3': 'ch28', 'd4': 'ch16', 'd5': 'ch13', 'd6': 'ch0', 'd7': 'ch14', 'd8': 'ch17', 'd9': 'ch15', 'd10': 'ch1', 'd11': 'chclk', 'd12': 'ch18', 'd13': 'ch16', 'd14': 'ch3', 'd15': 'ch0'}, 'pm2+pm3': {'d0': 'ch17', 'd1': 'ch15', 'd2': 'ch1', 'd3': 'chclk', 'd4': 'ch18', 'd5': 'ch16', 'd6': 'ch3', 'd7': 'ch0', 'd8': 'ch20', 'd9': 'ch17', 'd10': 'ch4', 'd11': 'ch1', 'd12': 'ch21', 'd13': 'ch18', 'd14': 'ch5', 'd15': 'ch3'}, 'pm4+pm5': {'d0': 'ch22', 'd1': 'ch20', 'd2': 'ch6', 'd3': 'ch4', 'd4': 'ch23', 'd5': 'ch21', 'd6': 'ch7', 'd7': 'ch5', 'd8': 'ch8', 'd9': 'ch22', 'd10': 'ch25', 'd11': 'ch6', 'd12': 'ch26', 'd13': 'ch23', 'd14': 'ch10', 'd15': 'ch7'}, 'pm5+pm6': {'d0': 'ch8', 'd1': 'ch22', 'd2': 'ch25', 'd3': 'ch6', 'd4': 'ch26', 'd5': 'ch23', 'd6': 'ch10', 'd7': 'ch7', 'd8': 'ch11', 'd9': 'ch8', 'd10': 'ch28', 'd11': 'ch25', 'd12': 'ch13', 'd13': 'ch26', 'd14': 'ch14', 'd15': 'ch10'}}, 'wing': {'wing1': {'d0': 'ch3', 'd1': 'ch18', 'd2': 'ch1', 'd3': 'ch17', 'd4': 'ch0', 'd5': 'ch16', 'd6': 'chclk', 'd7': 'ch15'}, 'wing2': {'d0': 'ch7', 'd1': 'ch23', 'd2': 'ch6', 'd3': 'ch22', 'd4': 'ch5', 'd5': 'ch21', 'd6': 'ch4', 'd7': 'ch20'}, 'wing3': {'d0': 'ch14', 'd1': 'ch13', 'd2': 'ch28', 'd3': 'ch11', 'd4': 'ch10', 'd5': 'ch26', 'd6': 'ch25', 'd7': 'ch8'}}, 'dualwing': {'wing1+wing2': {'d0': 'ch7', 'd1': 'ch23', 'd2': 'ch6', 'd3': 'ch22', 'd4': 'ch5', 'd5': 'ch21', 'd6': 'ch4', 'd7': 'ch20', 'd8': 'ch3', 'd9': 'ch18', 'd10': 'ch1', 'd11': 'ch17', 'd12': 'ch0', 'd13': 'ch16', 'd14': 'chclk', 'd15': 'ch15'}, 'wing2+wing3': {'d0': 'ch14', 'd1': 'ch13', 'd2': 'ch28', 'd3': 'ch11', 'd4': 'ch10', 'd5': 'ch26', 'd6': 'ch25', 'd7': 'ch8', 'd8': 'ch7', 'd9': 'ch23', 'd10': 'ch6', 'd11': 'ch22', 'd12': 'ch5', 'd13': 'ch21', 'd14': 'ch4', 'd15': 'ch20'}}, 'xula': {'default': {'chclk': 'chclk', 'ch0': 'ch0', 'ch1': 'ch1', 'ch2': 'ch2', 'ch3': 'ch3', 'ch4': 'ch4', 'ch5': 'ch5', 'ch6': 'ch6', 'ch7': 'ch7', 'ch8': 'ch8', 'ch9': 'ch9', 'ch10': 'ch10', 'ch11': 'ch11', 'ch12': 'ch12', 'ch13': 'ch13', 'ch14': 'ch14', 'ch15': 'ch15', 'ch16': 'ch16', 'ch17': 'ch17', 'ch18': 'ch18', 'ch19': 'ch19', 'ch20': 'ch20', 'ch21': 'ch21', 'ch22': 'ch22', 'ch23': 'ch23', 'ch24': 'ch24', 'ch25': 'ch25', 'ch26': 'ch26', 'ch27': 'ch27', 'ch28': 'ch28', 'ch29': 'ch29', 'ch30': 'ch30', 'ch31': 'ch31', 'ch32': 'ch32', 'ch33': 'ch33'}}}} |
def move(x=0, dx=10, y=0, dy=10):
x = x + dx
y = y + dy
return x, y
x = 50
y = 50
new_x, new_y = move(x, 50, y, -25)
print("The new coords are: ", new_x, ",", new_y)
print("Call with missing x and y...")
missing_x, missing_y = move(dx=50, dy=50)
print("The new coords are: ", missing_x, ",", missing_y)
| def move(x=0, dx=10, y=0, dy=10):
x = x + dx
y = y + dy
return (x, y)
x = 50
y = 50
(new_x, new_y) = move(x, 50, y, -25)
print('The new coords are: ', new_x, ',', new_y)
print('Call with missing x and y...')
(missing_x, missing_y) = move(dx=50, dy=50)
print('The new coords are: ', missing_x, ',', missing_y) |
def to_bytes(bytes_or_str):
"""
Converts supplied data into bytes if the data is of type str.
:param bytes_or_str: Data to be converted.
:return: UTF-8 encoded bytes if the data was of type str. Otherwise it returns the supplied data as is.
"""
if isinstance(bytes_or_str, str):
return bytes_or_str.encode()
return bytes_or_str
def to_str(bytes_or_str):
"""
Converts supplied data into a UTF-8 encoded string if the data is of type bytes.
:param bytes_or_str: Data to be converted.
:return: UTF-8 encoded string if the data was of type bytes. Otherwise it returns the supplied data as is.
"""
if isinstance(bytes_or_str, bytes):
return bytes_or_str.decode()
return bytes_or_str
| def to_bytes(bytes_or_str):
"""
Converts supplied data into bytes if the data is of type str.
:param bytes_or_str: Data to be converted.
:return: UTF-8 encoded bytes if the data was of type str. Otherwise it returns the supplied data as is.
"""
if isinstance(bytes_or_str, str):
return bytes_or_str.encode()
return bytes_or_str
def to_str(bytes_or_str):
"""
Converts supplied data into a UTF-8 encoded string if the data is of type bytes.
:param bytes_or_str: Data to be converted.
:return: UTF-8 encoded string if the data was of type bytes. Otherwise it returns the supplied data as is.
"""
if isinstance(bytes_or_str, bytes):
return bytes_or_str.decode()
return bytes_or_str |
class Name_list:
def __init__(self):
self.PREMIER_URL = 'https://www.footballwebpages.co.uk/premier-league'
self.PREMIER_URL_H = 'https://www.footballwebpages.co.uk/premier-league/league-table/home'
self.PREMIER_URL_A = 'https://www.footballwebpages.co.uk/premier-league/league-table/away'
self.LEAGUE_LISTS = ["Premier League"]
self.PREMIER_RESULTS = 'https://www.goal.com/en/results/'# + YYYY-MM-DD
| class Name_List:
def __init__(self):
self.PREMIER_URL = 'https://www.footballwebpages.co.uk/premier-league'
self.PREMIER_URL_H = 'https://www.footballwebpages.co.uk/premier-league/league-table/home'
self.PREMIER_URL_A = 'https://www.footballwebpages.co.uk/premier-league/league-table/away'
self.LEAGUE_LISTS = ['Premier League']
self.PREMIER_RESULTS = 'https://www.goal.com/en/results/' |
expected_output = {
"services-accounting-information": {
"flow-aggregate-template-detail": {
"flow-aggregate-template-detail-ipv4": {
"detail-entry": {
"source-address": "27.93.202.64",
"destination-address": "106.187.14.158",
"source-port": "8",
"destination-port": "0",
"protocol": {"#text": "1"},
"tos": "0",
"tcp-flags": "0",
"source-mask": "32",
"destination-mask": "30",
"input-snmp-interface-index": "618",
"output-snmp-interface-index": "620",
"start-time": "79167425",
"end-time": "79167425",
"packet-count": "1",
"byte-count": "84",
}
}
}
}
}
| expected_output = {'services-accounting-information': {'flow-aggregate-template-detail': {'flow-aggregate-template-detail-ipv4': {'detail-entry': {'source-address': '27.93.202.64', 'destination-address': '106.187.14.158', 'source-port': '8', 'destination-port': '0', 'protocol': {'#text': '1'}, 'tos': '0', 'tcp-flags': '0', 'source-mask': '32', 'destination-mask': '30', 'input-snmp-interface-index': '618', 'output-snmp-interface-index': '620', 'start-time': '79167425', 'end-time': '79167425', 'packet-count': '1', 'byte-count': '84'}}}}} |
_HAS_COLORS = False
COLOR_LOGO = 1
COLOR_LOGO_ALT = 2
COLOR_FOCUSED = 3
COLOR_SCROLLBAR_TRACK = 4
COLOR_SCROLLBAR_THUMB = 5
COLOR_PROGRESSBAR = 6
COLOR_HIGHLIGHT = 7
def has_colors() -> bool:
return _HAS_COLORS
def set_colors(has_colors: bool) -> None:
global _HAS_COLORS
_HAS_COLORS = has_colors
| _has_colors = False
color_logo = 1
color_logo_alt = 2
color_focused = 3
color_scrollbar_track = 4
color_scrollbar_thumb = 5
color_progressbar = 6
color_highlight = 7
def has_colors() -> bool:
return _HAS_COLORS
def set_colors(has_colors: bool) -> None:
global _HAS_COLORS
_has_colors = has_colors |
"""
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
"""
#Difficulty: Medium
#13 / 13 test cases passed.
#Runtime: 588 ms
#Memory Usage: 30.5 MB
#Runtime: 588 ms, faster than 12.54% of Python3 online submissions for Add and Search Word - Data structure design.
#Memory Usage: 30.5 MB, less than 9.69% of Python3 online submissions for Add and Search Word - Data structure design.
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = [None] * 26
self.is_word = False
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
current = self
for char in word:
index = ord(char) - ord('a')
if not current.children[index]:
current.children[index] = WordDictionary()
current = current.children[index]
current.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the
dot character '.' to represent any one letter.
"""
current = self
for i in range(len(word)):
index = ord(word[i]) - ord('a')
if word[i] == '.':
for char in current.children:
if char and char.search(word[i+1:]):
return True
return False
if not current.children[index]:
return False
current = current.children[index]
return current and current.is_word
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
| """
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
search(word) can search a literal word or a regular expression string
containing only letters a-z or .. A . means it can represent any one letter.
Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
Note:
You may assume that all words are consist of lowercase letters a-z.
"""
class Worddictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.children = [None] * 26
self.is_word = False
def add_word(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
current = self
for char in word:
index = ord(char) - ord('a')
if not current.children[index]:
current.children[index] = word_dictionary()
current = current.children[index]
current.is_word = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the
dot character '.' to represent any one letter.
"""
current = self
for i in range(len(word)):
index = ord(word[i]) - ord('a')
if word[i] == '.':
for char in current.children:
if char and char.search(word[i + 1:]):
return True
return False
if not current.children[index]:
return False
current = current.children[index]
return current and current.is_word |
"""Core workflow configuration/constants"""
REQUEST_IDENTIFIER = 'Initial'
REQUEST_STATUS = (
('Initiated', 'Initiated'),
('Withdrawn', 'Withdrawn'),
('Completed', 'Completed')
)
TASK_STATUS = (
('Not Started', 'Not Started'),
('In Progress', 'In Progress'),
('Rolled Back', 'Rolled Back'),
('Completed', 'Completed')
)
# register workflow apps here
# enable 'tests' app only for manual testing purpose
WORKFLOW_APPS = [
'tests'
]
| """Core workflow configuration/constants"""
request_identifier = 'Initial'
request_status = (('Initiated', 'Initiated'), ('Withdrawn', 'Withdrawn'), ('Completed', 'Completed'))
task_status = (('Not Started', 'Not Started'), ('In Progress', 'In Progress'), ('Rolled Back', 'Rolled Back'), ('Completed', 'Completed'))
workflow_apps = ['tests'] |
'''10. Write a Python program to print without newline or space.'''
print("This is a sentence", end='')
print("This is a new line that will not show")
| """10. Write a Python program to print without newline or space."""
print('This is a sentence', end='')
print('This is a new line that will not show') |
def pair(relation, human_readable = None):
'''
Creates a dictionary pair of a relation uri in string form and a human readable equivalent.
Args:
relation (str): This should be preformated so generate_uri works on it
human_readable (str): a plain-text description of the uri
Return:
d (dictionary)
'''
d = {
'relation': relation,
'human_readable': human_readable
}
return d
# In this mapping, outer dictionary key represents the column header in the csv.
# We use the same header as the human-readable description so users are
# familiar with what they're selecting on group comparisons.
# Note: we don't handle "serotype" here as it has to be split into O and H type.
mapping = {
'primary_dbxref': pair('ge:0001800', 'primary_dbxref'),
'secondary_sample_accession': pair(':secondary_sample_accession', 'secondary_sample_accession'),
'study_accession': pair('obi:0001628', 'study_accession'),
'secondary_study_accession': pair(':secondary_study_accession', 'secondary_study_accession'),
'strain': pair(':0001429', 'strain'),
'serotype': '',
'O-Type': pair('ge:0001076', 'O-Type'),
'H-Type': pair('ge:0001077', 'H-Type'),
'stx1_subtype': pair('subt:stx1', 'stx1_subtype'),
'stx2_subtype': pair('subt:stx2', 'stx2_subtype'),
'syndrome': pair('ge:0001613', 'syndrome'),
'isolation_host': pair('ge:0001567', 'isolation_host'),
'isolation_source': pair('ge:0000025', 'isolation_source'),
'isolation_date': pair('ge:0000020', 'isolation_date'),
'isolation_location': pair('ge:0000117', 'isolation_location'),
'contact': pair('ge:0001642', 'contact')
}
| def pair(relation, human_readable=None):
"""
Creates a dictionary pair of a relation uri in string form and a human readable equivalent.
Args:
relation (str): This should be preformated so generate_uri works on it
human_readable (str): a plain-text description of the uri
Return:
d (dictionary)
"""
d = {'relation': relation, 'human_readable': human_readable}
return d
mapping = {'primary_dbxref': pair('ge:0001800', 'primary_dbxref'), 'secondary_sample_accession': pair(':secondary_sample_accession', 'secondary_sample_accession'), 'study_accession': pair('obi:0001628', 'study_accession'), 'secondary_study_accession': pair(':secondary_study_accession', 'secondary_study_accession'), 'strain': pair(':0001429', 'strain'), 'serotype': '', 'O-Type': pair('ge:0001076', 'O-Type'), 'H-Type': pair('ge:0001077', 'H-Type'), 'stx1_subtype': pair('subt:stx1', 'stx1_subtype'), 'stx2_subtype': pair('subt:stx2', 'stx2_subtype'), 'syndrome': pair('ge:0001613', 'syndrome'), 'isolation_host': pair('ge:0001567', 'isolation_host'), 'isolation_source': pair('ge:0000025', 'isolation_source'), 'isolation_date': pair('ge:0000020', 'isolation_date'), 'isolation_location': pair('ge:0000117', 'isolation_location'), 'contact': pair('ge:0001642', 'contact')} |
# coding: utf-8
# Copyright 2020. ThingsBoard
# #
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# #
# http://www.apache.org/licenses/LICENSE-2.0
# #
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class File:
def __init__(self, path: str, filename: str, version: str):
self._path = path
self._filename = filename
self._version = version
self._class_name = None
@property
def full_file_path(self):
return self._path + self._filename
@property
def filename(self):
return self._filename
@property
def version(self):
return self._version
@property
def class_name(self):
return self._class_name
@class_name.setter
def class_name(self, value):
self._class_name = value
def __str__(self):
return f'{self._path}{self._filename}'
| class File:
def __init__(self, path: str, filename: str, version: str):
self._path = path
self._filename = filename
self._version = version
self._class_name = None
@property
def full_file_path(self):
return self._path + self._filename
@property
def filename(self):
return self._filename
@property
def version(self):
return self._version
@property
def class_name(self):
return self._class_name
@class_name.setter
def class_name(self, value):
self._class_name = value
def __str__(self):
return f'{self._path}{self._filename}' |
class InvalidTimeRangeError(Exception):
"""Error for invalid time ranges."""
def __init__(self, start, stop):
msg = 'Start time {} exceeds stop time {}'.format(
start.isoformat(),
stop.isoformat()
)
super(InvalidTimeRangeError, self).__init__(msg)
class UnknownCounterTypeError(Exception):
"""Error for unknown counter types."""
def __init__(self, counter_type):
msg = 'Encountered unknown counter type {}'.format(counter_type)
super(UnknownCounterTypeError, self).__init__(msg)
class UnknownConversionError(Exception):
"""Error for unknown conversion."""
def __init__(self, conversion_name):
msg = 'Unknown conversion {}.'.format(conversion_name)
super(UnknownConversionError, self).__init__(msg)
class UnknownFieldFunctionError(Exception):
"""Error for unknown field functions."""
def __init__(self, function_name):
msg = 'Unknown field function {}.'.format(function_name)
super(UnknownFieldFunctionError, self).__init__(msg)
class UnknownLicenserError(Exception):
"""Error for unknown licenser."""
def __init__(self, licenser_name):
msg = 'Unknown licenser {}.'.format(licenser_name)
super(UnknownLicenserError, self).__init__(msg)
class NoSamplesError(Exception):
"""Error for no samples."""
def __init__(self):
msg = "Resource does not have any samples during the time period."
super(NoSamplesError, self).__init__(msg)
| class Invalidtimerangeerror(Exception):
"""Error for invalid time ranges."""
def __init__(self, start, stop):
msg = 'Start time {} exceeds stop time {}'.format(start.isoformat(), stop.isoformat())
super(InvalidTimeRangeError, self).__init__(msg)
class Unknowncountertypeerror(Exception):
"""Error for unknown counter types."""
def __init__(self, counter_type):
msg = 'Encountered unknown counter type {}'.format(counter_type)
super(UnknownCounterTypeError, self).__init__(msg)
class Unknownconversionerror(Exception):
"""Error for unknown conversion."""
def __init__(self, conversion_name):
msg = 'Unknown conversion {}.'.format(conversion_name)
super(UnknownConversionError, self).__init__(msg)
class Unknownfieldfunctionerror(Exception):
"""Error for unknown field functions."""
def __init__(self, function_name):
msg = 'Unknown field function {}.'.format(function_name)
super(UnknownFieldFunctionError, self).__init__(msg)
class Unknownlicensererror(Exception):
"""Error for unknown licenser."""
def __init__(self, licenser_name):
msg = 'Unknown licenser {}.'.format(licenser_name)
super(UnknownLicenserError, self).__init__(msg)
class Nosampleserror(Exception):
"""Error for no samples."""
def __init__(self):
msg = 'Resource does not have any samples during the time period.'
super(NoSamplesError, self).__init__(msg) |
# Number letter counts
# Problem 17
# If the numbers 1 to 5 are written out in words: one, two, three,
# four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in
# total.
#
# If all the numbers from 1 to 1000 (one thousand) inclusive were
# written out in words, how many letters would be used?
#
#
# NOTE: Do not count spaces or hyphens. For example, 342
# (three hundred and forty-two) contains 23 letters and 115 (one hundred and
# fifteen) contains 20 letters. The use of "and" when writing out
# numbers is in compliance with British usage.
#
dictionary = {
1: len('one'),
2: len('two'),
3: len('three'),
4: len('four'),
5: len('five'),
6: len('six'),
7: len('seven'),
8: len('eight'),
9: len('nine'),
10: len('ten'),
11: len('eleven'),
12: len('twelve'),
13: len('thirteen'),
14: len('fourteen'),
15: len('fifteen'),
16: len('sixteen'),
17: len('seventeen'),
18: len('eighteen'),
19: len('nineteen'),
20: len('twenty'),
30: len('thirty'),
40: len('forty'),
50: len('fifty'),
60: len('sixty'),
70: len('seventy'),
80: len('eighty'),
90: len('ninety'),
100: len('hundred'),
1000: len('thousand')
}
def count_number_letters_0_99():
count_0_9 = sum(dictionary.get(n) for n in range(1, 10))
count = sum(dictionary.get(n) for n in range(1, 20)) # 1 - 19
count += sum(dictionary.get(tens * 10) * 10 for tens in range(2, 10)) # 20, 30, 40, 50, 60, 70, 80, 90
return count + count_0_9 * 8
# @WARNING: UNREADABLE
def solve():
count_0_99 = count_number_letters_0_99()
count_hundreds = len('and') * 99 + dictionary.get(100) * 100 + count_0_99
total = sum(dictionary.get(h) for h in range(1, 10)) * 100 + count_hundreds * 9
return dictionary.get(1) + dictionary.get(1000) + count_0_99 + total
if __name__ == '__main__':
print(__file__ + ": %d" % solve())
| dictionary = {1: len('one'), 2: len('two'), 3: len('three'), 4: len('four'), 5: len('five'), 6: len('six'), 7: len('seven'), 8: len('eight'), 9: len('nine'), 10: len('ten'), 11: len('eleven'), 12: len('twelve'), 13: len('thirteen'), 14: len('fourteen'), 15: len('fifteen'), 16: len('sixteen'), 17: len('seventeen'), 18: len('eighteen'), 19: len('nineteen'), 20: len('twenty'), 30: len('thirty'), 40: len('forty'), 50: len('fifty'), 60: len('sixty'), 70: len('seventy'), 80: len('eighty'), 90: len('ninety'), 100: len('hundred'), 1000: len('thousand')}
def count_number_letters_0_99():
count_0_9 = sum((dictionary.get(n) for n in range(1, 10)))
count = sum((dictionary.get(n) for n in range(1, 20)))
count += sum((dictionary.get(tens * 10) * 10 for tens in range(2, 10)))
return count + count_0_9 * 8
def solve():
count_0_99 = count_number_letters_0_99()
count_hundreds = len('and') * 99 + dictionary.get(100) * 100 + count_0_99
total = sum((dictionary.get(h) for h in range(1, 10))) * 100 + count_hundreds * 9
return dictionary.get(1) + dictionary.get(1000) + count_0_99 + total
if __name__ == '__main__':
print(__file__ + ': %d' % solve()) |
num = 10
num = 22
a= 2
def main():
pass
if __name__ == '__main__':
main()
b = 3
aa = 33
ss = 334
| num = 10
num = 22
a = 2
def main():
pass
if __name__ == '__main__':
main()
b = 3
aa = 33
ss = 334 |
def has_attachment(ctx):
return bool(len(ctx.message.attachments))
def has_embed(ctx):
return bool(len(ctx.message.embeds))
def file_type(ctx, filetype, attnum = 0):
if not has_attachment(ctx): return False
return ctx.message.attachments[attnum].endswith(filetype) | def has_attachment(ctx):
return bool(len(ctx.message.attachments))
def has_embed(ctx):
return bool(len(ctx.message.embeds))
def file_type(ctx, filetype, attnum=0):
if not has_attachment(ctx):
return False
return ctx.message.attachments[attnum].endswith(filetype) |
class ARANGODB:
"""
Arango DB configuration
"""
URL = 'http://arangodb:8529'
USER = 'root'
PASSWORD = ''
DB_NAME = 'thesis' | class Arangodb:
"""
Arango DB configuration
"""
url = 'http://arangodb:8529'
user = 'root'
password = ''
db_name = 'thesis' |
#!/usr/bin/python3.6
# created by cicek on 26.07.2018 22:25
def myFunc():
print("hello")
myFunc()
# You must define functions before they are called, in the same way that you must assign variables before using them
def function(variable):
variable += 1
print(variable)
function(7)
# print(variable) # NameError: name 'variable' is not defined
# Arguments can be changed every time you call the function. (7) is the ARGUMENT
# Parameters are used when defining the function. (variable)
# Once you return a value from a function, it immediately stops being executed.
def add_numbers(x, y):
total = x + y
return total
print("This won't be printed")
print(add_numbers(834, 567))
def fun():
"""
print("hello")
:return:
"""
'''
print("hi")
'''
fun()
# Docstrings (documentation strings)
def shout(word):
"""
Print a word with an
exclamation mark following it.
"""
print(word + "!")
shout("spam")
def multiply(x, y):
return x * y
a = 4
b = 7
operation = multiply
print(operation(a, b))
print("")
something = print
something("hello man")
print("-----------------")
# def add():
# return 5+3
# def twice():
# return add()+add()
# print( twice() ) # 16
# def add(x,y):
# return x+y
# def twice():
# xa=5
# ya=3
# return add(xa,ya)+add(xa,ya)
# print( twice() ) # 16
#
# def add(x,y):
# return x+y
# def twice(add,x,y):
# return add(x,y)+add(x,y)
# print ( twice(add,5,3) ) # 16
#
def add(x,y):
return x+y
def twice(add,x,y):
return add(add(x,y),add(x,y))
print ( twice(add,5,3) )
def car(d, f):
return d+f
def carpet(car, d, f):
return car(car(d, f), car(d, f))
print( carpet(car, 16, 4) )
| def my_func():
print('hello')
my_func()
def function(variable):
variable += 1
print(variable)
function(7)
def add_numbers(x, y):
total = x + y
return total
print("This won't be printed")
print(add_numbers(834, 567))
def fun():
"""
print("hello")
:return:
"""
'\n print("hi")\n '
fun()
def shout(word):
"""
Print a word with an
exclamation mark following it.
"""
print(word + '!')
shout('spam')
def multiply(x, y):
return x * y
a = 4
b = 7
operation = multiply
print(operation(a, b))
print('')
something = print
something('hello man')
print('-----------------')
def add(x, y):
return x + y
def twice(add, x, y):
return add(add(x, y), add(x, y))
print(twice(add, 5, 3))
def car(d, f):
return d + f
def carpet(car, d, f):
return car(car(d, f), car(d, f))
print(carpet(car, 16, 4)) |
# Every two consecutive numbers add up to 1
n = int(input())
if n % 2 == 0:
print(n // 2)
else:
print(n // 2 + -n)
| n = int(input())
if n % 2 == 0:
print(n // 2)
else:
print(n // 2 + -n) |
def xor_2_bytes(input1,input2):
xor_bytes = b''
for b1, b2 in zip(input1, input2):
xor_bytes += (bytes([b1 ^ b2]))
print(xor_bytes)
return xor_bytes.hex()
if __name__ == "__main__":
byte_string1 = bytes.fromhex('1c0111001f010100061a024b53535009181c')
byte_string2 = bytes.fromhex('686974207468652062756c6c277320657965')
print(byte_string1)
print(byte_string2)
print(xor_2_bytes(byte_string1,byte_string2)) | def xor_2_bytes(input1, input2):
xor_bytes = b''
for (b1, b2) in zip(input1, input2):
xor_bytes += bytes([b1 ^ b2])
print(xor_bytes)
return xor_bytes.hex()
if __name__ == '__main__':
byte_string1 = bytes.fromhex('1c0111001f010100061a024b53535009181c')
byte_string2 = bytes.fromhex('686974207468652062756c6c277320657965')
print(byte_string1)
print(byte_string2)
print(xor_2_bytes(byte_string1, byte_string2)) |
# converting vehicle age to inter
def process_vehicule_age(df):
ds = df.copy()
ds["Vehicle_Age"] = ds["Vehicle_Age"].map(
lambda x: 0 if x == "< 1 Year" else 1 if x == "1-2 Year" else 2
)
ds["Vehicle_Age"] = ds["Vehicle_Age"].astype("int")
return ds
# changing the column type for different columns
def change_type(df):
cols_types = {
"str": [
"Gender",
"Driving_License",
"Region_Code",
"Previously_Insured",
"Vehicle_Damage",
"Policy_Sales_Channel",
],
"float": ["Age", "Annual_Premium", "Vehicle_Age", "Vintage"],
"int": ["id", "Response"],
}
for k, v in cols_types.items():
for c in v:
df[c] = df[c].astype(k)
return df
# prepocessing steps for one hot encoding
| def process_vehicule_age(df):
ds = df.copy()
ds['Vehicle_Age'] = ds['Vehicle_Age'].map(lambda x: 0 if x == '< 1 Year' else 1 if x == '1-2 Year' else 2)
ds['Vehicle_Age'] = ds['Vehicle_Age'].astype('int')
return ds
def change_type(df):
cols_types = {'str': ['Gender', 'Driving_License', 'Region_Code', 'Previously_Insured', 'Vehicle_Damage', 'Policy_Sales_Channel'], 'float': ['Age', 'Annual_Premium', 'Vehicle_Age', 'Vintage'], 'int': ['id', 'Response']}
for (k, v) in cols_types.items():
for c in v:
df[c] = df[c].astype(k)
return df |
"""
Python client for Mantis connect SOAP API
"""
__version__ = '0.4.0'
__author__ = 'Ji Haijun'
__module_name__ = 'mantisconnect2'
__license__ = 'MIT'
| """
Python client for Mantis connect SOAP API
"""
__version__ = '0.4.0'
__author__ = 'Ji Haijun'
__module_name__ = 'mantisconnect2'
__license__ = 'MIT' |
class Solution:
def lengthOfLastWord(self, s: str) -> int:
p, length = len(s) - 1, 0
while p >= 0:
if s[p] != ' ':
length += 1
else:
if length > 0:
return length
p -= 1
return length | class Solution:
def length_of_last_word(self, s: str) -> int:
(p, length) = (len(s) - 1, 0)
while p >= 0:
if s[p] != ' ':
length += 1
elif length > 0:
return length
p -= 1
return length |
"""
Created on 18 Feb 2019
@author: Frank Ypma
"""
class FlowFile(object):
""""
Mock object for a nifi message, containing flowfile content and a dict of attributes
For now, only string content is accepted, but that could be expanded
"""
def __init__(self, content="", attributes=None):
assert isinstance(content, str)
assert isinstance(attributes, dict)
self.content = content
if attributes is None:
self.attributes = {}
else:
self.attributes = attributes
def __str__(self):
return f"{{'content': '{self.content}', 'attributes': {self.attributes!r}}}"
__repr__ = __str__
| """
Created on 18 Feb 2019
@author: Frank Ypma
"""
class Flowfile(object):
""""
Mock object for a nifi message, containing flowfile content and a dict of attributes
For now, only string content is accepted, but that could be expanded
"""
def __init__(self, content='', attributes=None):
assert isinstance(content, str)
assert isinstance(attributes, dict)
self.content = content
if attributes is None:
self.attributes = {}
else:
self.attributes = attributes
def __str__(self):
return f"{{'content': '{self.content}', 'attributes': {self.attributes!r}}}"
__repr__ = __str__ |
#!/usr/bin/python3
# author: Karel Fiala
# email: fiala.karel@gmail.com
# config
SERVER_IP = "0.0.0.0"
SERVER_PORT = 5556
CLIENT_LISTEN_IP = "dev.haut.local"
CLIENT_LISTEN_PORT = 5555
BUFFER_SIZE = 1024
WEBSERVER_IP_BIND = "0.0.0.0"
WEBSERVER_PORT_BIND = 5557 | server_ip = '0.0.0.0'
server_port = 5556
client_listen_ip = 'dev.haut.local'
client_listen_port = 5555
buffer_size = 1024
webserver_ip_bind = '0.0.0.0'
webserver_port_bind = 5557 |
while True:
try:
entrada = int(input())
print('Y' if entrada % 6 == 0 else 'N')
except:
break | while True:
try:
entrada = int(input())
print('Y' if entrada % 6 == 0 else 'N')
except:
break |
class Params(object):
"""
Unified Parameter Object for passing arguments among APIs
from the algorithm frame (e.g., client_trainer.py and server aggregator.py).
Usage::
>> my_params = Params()
>> # add parameter
>> my_params.add(name="w", param=model_weights)
>> # get parameter
>> my_params.w
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def add(self, name: str, param):
self.__dict__.update({name: param})
def get(self, name: str):
if not hasattr(self, name):
raise ValueError(f"Attribute not found: {name}")
return getattr(self, name)
| class Params(object):
"""
Unified Parameter Object for passing arguments among APIs
from the algorithm frame (e.g., client_trainer.py and server aggregator.py).
Usage::
>> my_params = Params()
>> # add parameter
>> my_params.add(name="w", param=model_weights)
>> # get parameter
>> my_params.w
"""
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def add(self, name: str, param):
self.__dict__.update({name: param})
def get(self, name: str):
if not hasattr(self, name):
raise value_error(f'Attribute not found: {name}')
return getattr(self, name) |
# Created by Hansi at 2/14/2020
def calculate_recall(tp, n):
"""
:param tp: int
Number of True Positives
:param n: int
Number of total instances
:return: float
Recall
"""
if n == 0:
return 0
return tp / n
def calculate_precision(tp, fp):
"""
:param tp: int
Number of True Positives
:param fp: int
Number of False Positives
:return: float
Precision
"""
if tp + fp == 0:
return 0
return tp / (tp + fp)
def calculate_f1(recall, precision):
"""
:param recall: float
:param precision: float
:return: float
F1
"""
if recall + precision == 0:
f1 = 0
else:
f1 = 2 * ((recall * precision) / (
recall + precision))
return f1
| def calculate_recall(tp, n):
"""
:param tp: int
Number of True Positives
:param n: int
Number of total instances
:return: float
Recall
"""
if n == 0:
return 0
return tp / n
def calculate_precision(tp, fp):
"""
:param tp: int
Number of True Positives
:param fp: int
Number of False Positives
:return: float
Precision
"""
if tp + fp == 0:
return 0
return tp / (tp + fp)
def calculate_f1(recall, precision):
"""
:param recall: float
:param precision: float
:return: float
F1
"""
if recall + precision == 0:
f1 = 0
else:
f1 = 2 * (recall * precision / (recall + precision))
return f1 |
def once(function):
function_has_been_called = False
def wrapper(*args, **kwargs):
if not function_has_been_called:
function_has_been_called = True
return wrapper(*args, **kwargs)
return wrapper
| def once(function):
function_has_been_called = False
def wrapper(*args, **kwargs):
if not function_has_been_called:
function_has_been_called = True
return wrapper(*args, **kwargs)
return wrapper |
"""This is my module docstring"""
'This is another string that has no runtime effect'
b'Bytes literal'
0
1000
def test():
'Function docstring'
| """This is my module docstring"""
'This is another string that has no runtime effect'
b'Bytes literal'
0
1000
def test():
"""Function docstring""" |
'''2. Write a Python program to create a sequence where the first four members
of the sequence are equal to one, and each successive term of the sequence is equal to the
sum of the four previous ones. Find the Nth member of the sequence.'''
num = int(input("Enter the number of terms: "))
| """2. Write a Python program to create a sequence where the first four members
of the sequence are equal to one, and each successive term of the sequence is equal to the
sum of the four previous ones. Find the Nth member of the sequence."""
num = int(input('Enter the number of terms: ')) |
## AUTHOR: Vamsi Krishna Reddy Satti
##################################################################################
# Optimizers
##################################################################################
class SGD:
def __init__(self, model, lr):
self.model = model
self.lr = lr
def step(self):
for layer in self.model.layers:
for name in layer.params:
layer.params[name] -= self.lr * layer.grad[name]
| class Sgd:
def __init__(self, model, lr):
self.model = model
self.lr = lr
def step(self):
for layer in self.model.layers:
for name in layer.params:
layer.params[name] -= self.lr * layer.grad[name] |
if sm.hasQuest(2566):
if sm.hasItem(4032985):
sm.chatScript("You already have the Ignition Device.")
else:
sm.giveItem(4032985)
sm.chatScript("Ignition Device. Bring ") | if sm.hasQuest(2566):
if sm.hasItem(4032985):
sm.chatScript('You already have the Ignition Device.')
else:
sm.giveItem(4032985)
sm.chatScript('Ignition Device. Bring ') |
'''
Created on June 13, 2018
@author: David Stocker
'''
#classes
class EmptyFileError(ValueError):
'''File contains no data '''
pass
class UndefinedPersistenceError(ValueError):
''' No persistence has been defined '''
pass
class PersistenceQueryError(ValueError):
''' Invalid Relational Query to persistence '''
pass
class EnhancementError(ValueError):
pass
class XMLSchemavalidationError(ValueError):
pass
class UndefinedValueListError(ValueError):
pass
class DuplicateValueListError(ValueError):
pass
class UndefinedOperatorError(ValueError):
pass
class DisallowedCloneError(ValueError):
pass
class UndefinedUUIDError(ValueError):
pass
class TemplatePathError(ValueError):
pass
class DuplicateConditionError(ValueError):
pass
class MalformedConditionError(ValueError):
''' A condition is somehow malformed and can not be processed'''
pass
class MalformedArgumentPathError(ValueError):
'''Parsing a conditional argument path via regular expressions yields a zero length array.
This means that the argument path does not follow the xPath style '''
pass
class MismatchedArgumentPathError(ValueError):
'''Walking down an agent's attributes using th3e argumen path yields an error.
This indicated that the agent does not have the desired arguent path available '''
pass
class MissingArgumentError(ValueError):
'''A conditional that requires argument X has been called without that argument '''
pass
class MissingAgentPathError(ValueError):
'''A conditional that requires an agent with an attribute at path X has been called without that agent/attribute combo'''
pass
class MissingAgentError(ValueError):
'''A conditional that requires a reference agent has been called without one'''
pass
class MissingTokenError(ValueError):
''' A conditional is somehow malformed and can not be processed'''
pass
class UnknownConditionalError(ValueError):
''' Unknown conditional %s requested from catalog '''
pass
class ChannelError(ValueError):
''' A stimulus is uses an undefined channeland can not be processed - or the channel is malformed'''
pass
class DuplicateChannelError(ValueError):
''' The channel already exists'''
pass
class DuplicateSubscription(ValueError):
''' already subscribed to the object '''
pass
class DisallowedDescriptorType(ValueError):
''' Used for controllers that try to subscribe to a descriptor that they can't handle, or are not allowed to have '''
pass
class DisallowedChannelChange(ValueError):
''' The method is not allowed on this particuler channel type '''
pass
class ControllerUpdateError(ValueError):
''' The controller is invalid'''
pass
class InvalidControllerError(ValueError):
''' The controller is invalid'''
pass
class DuplicateControllerError(ValueError):
''' The controller is invalid'''
pass
class PassiveControllerActivationError(ValueError):
''' Strictly passive (mayBeActive == False) controllers may not be activated'''
pass
class MismatchedStimulusDestination(ValueError):
"""A stimulus is given a set of controllers as the destination, but the stimulus has an agent oriented distribution model"""
pass
class NullDisplacement(ValueError):
"""A displacement can't be determined; usually because the two locations are not in the same zone"""
pass
class DurationModelError(ValueError):
"""A generic problem with a duration model"""
pass
class MemePropertyValidationError(ValueError):
"""A meme has an invalid property"""
pass
class MemePropertyValueError(ValueError):
"""A meme has a property with an invalid value"""
pass
class MemePropertyValueTypeError(ValueError):
"""A meme's property has been asked to assign a value of the wrong type"""
pass
class MemePropertyValueOutOfBoundsError(ValueError):
"""A meme property with constrained bounds has been asked to assign a value outside those bounds"""
pass
class MemeMembershipValidationError(ValueError):
"""A meme has an invalid member"""
pass
class NonInstantiatedSingletonError(ValueError):
"""This error should only occur if the meme is a singleton, but no entity has been instantiated. It means that there
is a technical problem with the meme loader in that it did not instantiate singleton memes"""
pass
class MemeMemberCardinalityError(ValueError):
"""A meme's membership roll violates the cardinality rules of its parent metameme"""
pass
class EntityPropertyValueTypeError(ValueError):
"""An entity's property has been asked to assign a value of the wrong type"""
pass
class EntityPropertyDuplicateError(ValueError):
"""An entity's property has been asked to assign a value of the wrong type"""
pass
class EntityPropertyValueOutOfBoundsError(ValueError):
"""An entity property with constrained bounds has been asked to assign a value outside those bounds"""
pass
class EntityMemberDuplicateError(ValueError):
"""An entity may not have a unique member more than 1x"""
pass
class EntityMemberMissingError(ValueError):
"""An entity may not have a unique member more than 1x"""
pass
class ScriptError(ValueError):
"""A script error"""
pass
class GeneratorError(ValueError):
"""General error for random numbers """
pass
class StateEventScriptInitError(ValueError):
"""An error initializing a state event script"""
pass
class SourceMemeManipulationError(ValueError):
"""An error in manipulating a source meme"""
pass
class TagError(ValueError):
pass
class EntityMaxXOffsetExceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMax"""
pass
class EntityMaxYOffsetExceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMax"""
pass
class EntityMaxZOffsetExceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMax"""
pass
class EntityMinXOffsetExceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMin"""
pass
class EntityMinYOffsetExceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMin"""
pass
class EntityMinZOffsetExceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMin"""
pass
class EntityMaxXAngleExceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMax"""
pass
class EntityMaxYAngleExceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMax"""
pass
class EntityMaxZAngleExceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMax"""
pass
class EntityMinXAngleExceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMin"""
pass
class EntityMinYAngleExceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMin"""
pass
class EntityMinZAngleExceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMin"""
pass
class InvalidStimulusProcessingType(ValueError):
''' The Stimulus Engine may only take the types TiogaSchema.ConditionalStimulus and
Stimulus.StimulusChoice. Everything else throws an exception'''
pass
| """
Created on June 13, 2018
@author: David Stocker
"""
class Emptyfileerror(ValueError):
"""File contains no data """
pass
class Undefinedpersistenceerror(ValueError):
""" No persistence has been defined """
pass
class Persistencequeryerror(ValueError):
""" Invalid Relational Query to persistence """
pass
class Enhancementerror(ValueError):
pass
class Xmlschemavalidationerror(ValueError):
pass
class Undefinedvaluelisterror(ValueError):
pass
class Duplicatevaluelisterror(ValueError):
pass
class Undefinedoperatorerror(ValueError):
pass
class Disallowedcloneerror(ValueError):
pass
class Undefineduuiderror(ValueError):
pass
class Templatepatherror(ValueError):
pass
class Duplicateconditionerror(ValueError):
pass
class Malformedconditionerror(ValueError):
""" A condition is somehow malformed and can not be processed"""
pass
class Malformedargumentpatherror(ValueError):
"""Parsing a conditional argument path via regular expressions yields a zero length array.
This means that the argument path does not follow the xPath style """
pass
class Mismatchedargumentpatherror(ValueError):
"""Walking down an agent's attributes using th3e argumen path yields an error.
This indicated that the agent does not have the desired arguent path available """
pass
class Missingargumenterror(ValueError):
"""A conditional that requires argument X has been called without that argument """
pass
class Missingagentpatherror(ValueError):
"""A conditional that requires an agent with an attribute at path X has been called without that agent/attribute combo"""
pass
class Missingagenterror(ValueError):
"""A conditional that requires a reference agent has been called without one"""
pass
class Missingtokenerror(ValueError):
""" A conditional is somehow malformed and can not be processed"""
pass
class Unknownconditionalerror(ValueError):
""" Unknown conditional %s requested from catalog """
pass
class Channelerror(ValueError):
""" A stimulus is uses an undefined channeland can not be processed - or the channel is malformed"""
pass
class Duplicatechannelerror(ValueError):
""" The channel already exists"""
pass
class Duplicatesubscription(ValueError):
""" already subscribed to the object """
pass
class Disalloweddescriptortype(ValueError):
""" Used for controllers that try to subscribe to a descriptor that they can't handle, or are not allowed to have """
pass
class Disallowedchannelchange(ValueError):
""" The method is not allowed on this particuler channel type """
pass
class Controllerupdateerror(ValueError):
""" The controller is invalid"""
pass
class Invalidcontrollererror(ValueError):
""" The controller is invalid"""
pass
class Duplicatecontrollererror(ValueError):
""" The controller is invalid"""
pass
class Passivecontrolleractivationerror(ValueError):
""" Strictly passive (mayBeActive == False) controllers may not be activated"""
pass
class Mismatchedstimulusdestination(ValueError):
"""A stimulus is given a set of controllers as the destination, but the stimulus has an agent oriented distribution model"""
pass
class Nulldisplacement(ValueError):
"""A displacement can't be determined; usually because the two locations are not in the same zone"""
pass
class Durationmodelerror(ValueError):
"""A generic problem with a duration model"""
pass
class Memepropertyvalidationerror(ValueError):
"""A meme has an invalid property"""
pass
class Memepropertyvalueerror(ValueError):
"""A meme has a property with an invalid value"""
pass
class Memepropertyvaluetypeerror(ValueError):
"""A meme's property has been asked to assign a value of the wrong type"""
pass
class Memepropertyvalueoutofboundserror(ValueError):
"""A meme property with constrained bounds has been asked to assign a value outside those bounds"""
pass
class Mememembershipvalidationerror(ValueError):
"""A meme has an invalid member"""
pass
class Noninstantiatedsingletonerror(ValueError):
"""This error should only occur if the meme is a singleton, but no entity has been instantiated. It means that there
is a technical problem with the meme loader in that it did not instantiate singleton memes"""
pass
class Mememembercardinalityerror(ValueError):
"""A meme's membership roll violates the cardinality rules of its parent metameme"""
pass
class Entitypropertyvaluetypeerror(ValueError):
"""An entity's property has been asked to assign a value of the wrong type"""
pass
class Entitypropertyduplicateerror(ValueError):
"""An entity's property has been asked to assign a value of the wrong type"""
pass
class Entitypropertyvalueoutofboundserror(ValueError):
"""An entity property with constrained bounds has been asked to assign a value outside those bounds"""
pass
class Entitymemberduplicateerror(ValueError):
"""An entity may not have a unique member more than 1x"""
pass
class Entitymembermissingerror(ValueError):
"""An entity may not have a unique member more than 1x"""
pass
class Scripterror(ValueError):
"""A script error"""
pass
class Generatorerror(ValueError):
"""General error for random numbers """
pass
class Stateeventscriptiniterror(ValueError):
"""An error initializing a state event script"""
pass
class Sourcemememanipulationerror(ValueError):
"""An error in manipulating a source meme"""
pass
class Tagerror(ValueError):
pass
class Entitymaxxoffsetexceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMax"""
pass
class Entitymaxyoffsetexceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMax"""
pass
class Entitymaxzoffsetexceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMax"""
pass
class Entityminxoffsetexceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMin"""
pass
class Entityminyoffsetexceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMin"""
pass
class Entityminzoffsetexceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMin"""
pass
class Entitymaxxangleexceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMax"""
pass
class Entitymaxyangleexceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMax"""
pass
class Entitymaxzangleexceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMax"""
pass
class Entityminxangleexceeded(ValueError):
""" An offset element's 'x' is greater than the 'x' value of the agent's OffsetMin"""
pass
class Entityminyangleexceeded(ValueError):
""" An offset element's 'y' is greater than the 'y' value of the agent's OffsetMin"""
pass
class Entityminzangleexceeded(ValueError):
""" An offset element's 'z' is greater than the 'z' value of the agent's OffsetMin"""
pass
class Invalidstimulusprocessingtype(ValueError):
""" The Stimulus Engine may only take the types TiogaSchema.ConditionalStimulus and
Stimulus.StimulusChoice. Everything else throws an exception"""
pass |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 17:11:21 2020
@author: ahmad
"""
for i in range(0, 10):
storage = ""
for x in range(0, i + 1):
storage += "*"
print(storage)
# storage += "*" => storage = storage + "*"
print("/////////////////////////")
for i in range(0, 10):
storage = ""
for x in range(0, 10):
if x < 9 - i:
storage += " "
else:
storage += "*"
print(storage)
| """
Created on Sat May 23 17:11:21 2020
@author: ahmad
"""
for i in range(0, 10):
storage = ''
for x in range(0, i + 1):
storage += '*'
print(storage)
print('/////////////////////////')
for i in range(0, 10):
storage = ''
for x in range(0, 10):
if x < 9 - i:
storage += ' '
else:
storage += '*'
print(storage) |
# http://www.codewars.com/kata/554b4ac871d6813a03000035/
def high_and_low(numbers):
lst = [int(num) for num in numbers.split()]
return "{0} {1}".format(max(lst), min(lst))
| def high_and_low(numbers):
lst = [int(num) for num in numbers.split()]
return '{0} {1}'.format(max(lst), min(lst)) |
"""
For details of problem statement visit:
https://www.hackerrank.com/rest/contests/master/challenges/the-minion-game/download_pdf?language=English
"""
def minion_game(s):
# your code goes here
i = len(s)
t = 0
k = 0
for x in range(i):
if s[x] == "A" or s[x] == "E" or s[x] == "I" or s[x] == "O" or s[x] == "U":
k = k + (i - x)
else:
t = t + (i - x)
if t == k:
print("Draw")
elif t > k:
print("Stuart", t)
else:
print("Kevin", k)
| """
For details of problem statement visit:
https://www.hackerrank.com/rest/contests/master/challenges/the-minion-game/download_pdf?language=English
"""
def minion_game(s):
i = len(s)
t = 0
k = 0
for x in range(i):
if s[x] == 'A' or s[x] == 'E' or s[x] == 'I' or (s[x] == 'O') or (s[x] == 'U'):
k = k + (i - x)
else:
t = t + (i - x)
if t == k:
print('Draw')
elif t > k:
print('Stuart', t)
else:
print('Kevin', k) |
# Coding Challenge 2
### Chelsea Lizardo
### NRS 528
#
#
string = 'hi dee hi how are you mr dee'
#Count the occurrence of each word, and print the word plus the count.
def word_count(str):
counts = dict()
words = str.split()
for w in words:
if w in counts:
counts[w] += 1
else:
counts[w] = 1
return counts
print( word_count('hi dee hi how are you mr dee')) | string = 'hi dee hi how are you mr dee'
def word_count(str):
counts = dict()
words = str.split()
for w in words:
if w in counts:
counts[w] += 1
else:
counts[w] = 1
return counts
print(word_count('hi dee hi how are you mr dee')) |
def xo(s):
xcount = 0
ocount = 0
for i in s.lower():
if (i == 'x'):
xcount += 1
elif (i == 'o'):
ocount += 1
return xcount == ocount
print(xo('ooxx'))
# Using count()
def xo2(s):
s = s.lower()
return s.count('x') == s.count('o') | def xo(s):
xcount = 0
ocount = 0
for i in s.lower():
if i == 'x':
xcount += 1
elif i == 'o':
ocount += 1
return xcount == ocount
print(xo('ooxx'))
def xo2(s):
s = s.lower()
return s.count('x') == s.count('o') |
def print_formatted(number):
width = len(str(bin(number)))-2
for num in range(1, number+1):
decimal = int(num)
octal = oct(num)
hexadecimal = hex(num)
binary = bin(num)
print(str(decimal).rjust(width), octal[2:].rjust(
width), hexadecimal[2:].title().rjust(width), binary[2:].rjust(width))
print_formatted(20)
"""
1 1 1 1
2 2 2 10
3 3 3 11
4 4 4 100
5 5 5 101
6 6 6 110
7 7 7 111
8 10 8 1000
9 11 9 1001
10 12 A 1010
11 13 B 1011
12 14 C 1100
13 15 D 1101
14 16 E 1110
15 17 F 1111
16 20 10 10000
17 21 11 10001
18 22 12 10010
19 23 13 10011
20 24 14 10100
""" | def print_formatted(number):
width = len(str(bin(number))) - 2
for num in range(1, number + 1):
decimal = int(num)
octal = oct(num)
hexadecimal = hex(num)
binary = bin(num)
print(str(decimal).rjust(width), octal[2:].rjust(width), hexadecimal[2:].title().rjust(width), binary[2:].rjust(width))
print_formatted(20)
'\n 1 1 1 1\n 2 2 2 10\n 3 3 3 11\n 4 4 4 100\n 5 5 5 101\n 6 6 6 110\n 7 7 7 111\n 8 10 8 1000\n 9 11 9 1001\n 10 12 A 1010\n 11 13 B 1011\n 12 14 C 1100\n 13 15 D 1101\n 14 16 E 1110\n 15 17 F 1111\n 16 20 10 10000\n 17 21 11 10001\n 18 22 12 10010\n 19 23 13 10011\n 20 24 14 10100\n' |
#
# PySNMP MIB module Nortel-Magellan-Passport-CallRedirectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-CallRedirectionMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:26:41 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
RowStatus, Integer32, StorageType, Unsigned32, DisplayString, Counter32 = mibBuilder.importSymbols("Nortel-Magellan-Passport-StandardTextualConventionsMIB", "RowStatus", "Integer32", "StorageType", "Unsigned32", "DisplayString", "Counter32")
AsciiString, Link, AsciiStringIndex, NonReplicated = mibBuilder.importSymbols("Nortel-Magellan-Passport-TextualConventionsMIB", "AsciiString", "Link", "AsciiStringIndex", "NonReplicated")
components, passportMIBs = mibBuilder.importSymbols("Nortel-Magellan-Passport-UsefulDefinitionsMIB", "components", "passportMIBs")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
IpAddress, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Integer32, NotificationType, Gauge32, Unsigned32, Bits, ModuleIdentity, Counter32, Counter64, ObjectIdentity, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Integer32", "NotificationType", "Gauge32", "Unsigned32", "Bits", "ModuleIdentity", "Counter32", "Counter64", "ObjectIdentity", "TimeTicks")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
callRedirectionMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132))
crs = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132))
crsRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1), )
if mibBuilder.loadTexts: crsRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsRowStatusTable.setDescription('This entry controls the addition and deletion of crs components.')
crsRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"))
if mibBuilder.loadTexts: crsRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsRowStatusEntry.setDescription('A single entry in the table represents a single crs component.')
crsRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 1), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: crsRowStatus.setDescription('This variable is used as the basis for SNMP naming of crs components. These components can be added and deleted.')
crsComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: crsComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crsStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: crsStorageType.setDescription('This variable represents the storage type value for the crs tables.')
crsIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 10), NonReplicated())
if mibBuilder.loadTexts: crsIndex.setStatus('mandatory')
if mibBuilder.loadTexts: crsIndex.setDescription('This variable represents the index for the crs tables.')
crsProvTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 10), )
if mibBuilder.loadTexts: crsProvTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsProvTable.setDescription('The Provisioned group contains provisionable attributes of the CallRedirectionServer component.')
crsProvEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 10, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"))
if mibBuilder.loadTexts: crsProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsProvEntry.setDescription('An entry in the crsProvTable.')
crsLogicalProcessor = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 10, 1, 2), Link()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsLogicalProcessor.setStatus('mandatory')
if mibBuilder.loadTexts: crsLogicalProcessor.setDescription('This attribute specifies the logical processor on which the call redirection server process is to run.')
crsStateTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11), )
if mibBuilder.loadTexts: crsStateTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsStateTable.setDescription('This group contains the three OSI State attributes. The descriptions generically indicate what each state attribute implies about the component. Note that not all the values and state combinations described here are supported by every component which uses this group. For component-specific information and the valid state combinations, refer to NTP 241-7001-150, Passport Operations and Maintenance Guide.')
crsStateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"))
if mibBuilder.loadTexts: crsStateEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsStateEntry.setDescription('An entry in the crsStateTable.')
crsAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("locked", 0), ("unlocked", 1), ("shuttingDown", 2))).clone('unlocked')).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsAdminState.setStatus('mandatory')
if mibBuilder.loadTexts: crsAdminState.setDescription('This attribute indicates the OSI Administrative State of the component. The value locked indicates that the component is administratively prohibited from providing services for its users. A Lock or Lock - force command has been previously issued for this component. When the value is locked, the value of usageState must be idle. The value shuttingDown indicates that the component is administratively permitted to provide service to its existing users only. A Lock command was issued against the component and it is in the process of shutting down. The value unlocked indicates that the component is administratively permitted to provide services for its users. To enter this state, issue an Unlock command to this component.')
crsOperationalState = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1))).clone('disabled')).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsOperationalState.setStatus('mandatory')
if mibBuilder.loadTexts: crsOperationalState.setDescription('This attribute indicates the OSI Operational State of the component. The value enabled indicates that the component is available for operation. Note that if adminState is locked, it would still not be providing service. The value disabled indicates that the component is not available for operation. For example, something is wrong with the component itself, or with another component on which this one depends. If the value is disabled, the usageState must be idle.')
crsUsageState = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("idle", 0), ("active", 1), ("busy", 2))).clone('idle')).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsUsageState.setStatus('mandatory')
if mibBuilder.loadTexts: crsUsageState.setDescription('This attribute indicates the OSI Usage State of the component. The value idle indicates that the component is not currently in use. The value active indicates that the component is in use and has spare capacity to provide for additional users. The value busy indicates that the component is in use and has no spare operating capacity for additional users at this time.')
crsStatTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12), )
if mibBuilder.loadTexts: crsStatTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsStatTable.setDescription('The Statistics operational group defines the statistics associated with the CallRedirectionServer component.')
crsStatEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"))
if mibBuilder.loadTexts: crsStatEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsStatEntry.setDescription('An entry in the crsStatTable.')
crsTotalAddresses = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsTotalAddresses.setStatus('mandatory')
if mibBuilder.loadTexts: crsTotalAddresses.setDescription('The totalAddresses attribute indicates the number of PrimaryAddress components associated with the CallRedirectionServer component.')
crsRequestsReceived = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsRequestsReceived.setStatus('mandatory')
if mibBuilder.loadTexts: crsRequestsReceived.setDescription('The requestsReceived attribute counts the number of redirection requests received by the CallRedirectionServer component. This counter wraps to 0 when it exceeds its maximum value.')
crsPrimaryMatches = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsPrimaryMatches.setStatus('mandatory')
if mibBuilder.loadTexts: crsPrimaryMatches.setDescription('The primaryMatches attribute counts the Call Redirection Server attempts to find a matching PrimaryAddress where the lookup attempt was successful. This counter wraps to 0 when it exceeds its maximum value.')
crsSecAddressListExhausted = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsSecAddressListExhausted.setStatus('mandatory')
if mibBuilder.loadTexts: crsSecAddressListExhausted.setDescription('The secAddressListExhausted attribute counts the Call Redirection Server attempts to find a SecondaryAddress component given a PrimaryAddress component where the lookup attempt resulted in the exhaustion of the secondary redirection list. This counter wraps to 0 when it exceeds its maximum value.')
crsMaxAddrLenExceeded = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsMaxAddrLenExceeded.setStatus('mandatory')
if mibBuilder.loadTexts: crsMaxAddrLenExceeded.setDescription('The maxAddrLenExceeded attribute counts how often the concatenation of the secondary address and the suffix digits from the original called address have exceeded the maximum of 15 digits. The suffix digits can be determined by removing the primary address digits from the front of the original called address. If appending the suffix digits to a secondary address causes the resulting address to exceed 15 digits, this secondary member is skipped and the next secondary member is tried.')
crsSecRidMidUnsuccessful = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsSecRidMidUnsuccessful.setStatus('mandatory')
if mibBuilder.loadTexts: crsSecRidMidUnsuccessful.setDescription('The secRidMidUnsuccessful attribute counts the number of RID/ MID redirections resulting in the destination address not being reached. This situation could occur when the destination address does not exist on the specified module or the specified module could not be reached.')
crsSecAddrUnsuccessful = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsSecAddrUnsuccessful.setStatus('mandatory')
if mibBuilder.loadTexts: crsSecAddrUnsuccessful.setDescription('The secAddrUnsuccessful attribute counts the number of Address redirections resulting in the destination user not being reached. This situation could occur when the destination user line is disabled, the destination address does not exist on the specified module, or the specified module could not be reached.')
crsRidRedirected = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsRidRedirected.setStatus('mandatory')
if mibBuilder.loadTexts: crsRidRedirected.setDescription('The ridRedirected attribute counts requests received by the Call Redirection Server resulting in the request being redirected to another RID specified by the AlternateRid component. This counter wraps to 0 when it exceeds its maximum value.')
crsRidMidRedirected = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsRidMidRedirected.setStatus('mandatory')
if mibBuilder.loadTexts: crsRidMidRedirected.setDescription('The ridMidRedirected attribute counts requests received by the Call Redirection Server resulting in the request being redirected to another RID/MID specified by the SecondaryRidMid component. This counter wraps to 0 when it exceeds its maximum value.')
crsAddressRedirected = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsAddressRedirected.setStatus('mandatory')
if mibBuilder.loadTexts: crsAddressRedirected.setDescription('The addressRedirected attribute counts requests received by the Call Redirection Server resulting in the request being redirected to another Address specified by the SecondaryAddress component. This counter wraps to 0 when it exceeds its maximum value.')
crsAltRidUnsuccessful = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsAltRidUnsuccessful.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidUnsuccessful.setDescription('The altRidUnsuccessful attribute counts the number of RID redirections resulting in the destination address not being reached. This situation could occur when the alternate RID cannot be reached, the module hosting the destination address is isolated, or the port associated with the secondary address is unavailable at the alternate RID.')
crsPAddr = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2))
crsPAddrRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1), )
if mibBuilder.loadTexts: crsPAddrRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrRowStatusTable.setDescription('This entry controls the addition and deletion of crsPAddr components.')
crsPAddrRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrIndex"))
if mibBuilder.loadTexts: crsPAddrRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrRowStatusEntry.setDescription('A single entry in the table represents a single crsPAddr component.')
crsPAddrRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 1), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsPAddrRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsPAddr components. These components can be added and deleted.')
crsPAddrComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsPAddrComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crsPAddrStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsPAddrStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrStorageType.setDescription('This variable represents the storage type value for the crsPAddr tables.')
crsPAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 10), AsciiStringIndex().subtype(subtypeSpec=ValueSizeConstraint(1, 17)))
if mibBuilder.loadTexts: crsPAddrIndex.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrIndex.setDescription('This variable represents the index for the crsPAddr tables.')
crsPAddrSRidMid = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2))
crsPAddrSRidMidRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1), )
if mibBuilder.loadTexts: crsPAddrSRidMidRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidRowStatusTable.setDescription('This entry controls the addition and deletion of crsPAddrSRidMid components.')
crsPAddrSRidMidRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrSRidMidIndex"))
if mibBuilder.loadTexts: crsPAddrSRidMidRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidRowStatusEntry.setDescription('A single entry in the table represents a single crsPAddrSRidMid component.')
crsPAddrSRidMidRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 1), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsPAddrSRidMidRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsPAddrSRidMid components. These components can be added and deleted.')
crsPAddrSRidMidComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsPAddrSRidMidComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crsPAddrSRidMidStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsPAddrSRidMidStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidStorageType.setDescription('This variable represents the storage type value for the crsPAddrSRidMid tables.')
crsPAddrSRidMidIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 10), NonReplicated())
if mibBuilder.loadTexts: crsPAddrSRidMidIndex.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidIndex.setDescription('This variable represents the index for the crsPAddrSRidMid tables.')
crsPAddrSRidMidRidMidProvTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10), )
if mibBuilder.loadTexts: crsPAddrSRidMidRidMidProvTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidRidMidProvTable.setDescription('The SecRidMidProv group defines the secondary RID/MID pair associated with a specific primary address.')
crsPAddrSRidMidRidMidProvEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrSRidMidIndex"))
if mibBuilder.loadTexts: crsPAddrSRidMidRidMidProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidRidMidProvEntry.setDescription('An entry in the crsPAddrSRidMidRidMidProvTable.')
crsPAddrSRidMidRoutingId = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 126))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsPAddrSRidMidRoutingId.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidRoutingId.setDescription('This attribute specifies a group of one or more interconnected nodes (called a subnet) to which the primary address is redirected.')
crsPAddrSRidMidModuleId = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 1909))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsPAddrSRidMidModuleId.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSRidMidModuleId.setDescription('This attribute specifies a Passport node to which the primary address is redirected.')
crsPAddrSAddr = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3))
crsPAddrSAddrRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1), )
if mibBuilder.loadTexts: crsPAddrSAddrRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrRowStatusTable.setDescription('This entry controls the addition and deletion of crsPAddrSAddr components.')
crsPAddrSAddrRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrSAddrIndex"))
if mibBuilder.loadTexts: crsPAddrSAddrRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrRowStatusEntry.setDescription('A single entry in the table represents a single crsPAddrSAddr component.')
crsPAddrSAddrRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 1), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsPAddrSAddrRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsPAddrSAddr components. These components can be added and deleted.')
crsPAddrSAddrComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsPAddrSAddrComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crsPAddrSAddrStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsPAddrSAddrStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrStorageType.setDescription('This variable represents the storage type value for the crsPAddrSAddr tables.')
crsPAddrSAddrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 7)))
if mibBuilder.loadTexts: crsPAddrSAddrIndex.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrIndex.setDescription('This variable represents the index for the crsPAddrSAddr tables.')
crsPAddrSAddrSecAddrProvTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 10), )
if mibBuilder.loadTexts: crsPAddrSAddrSecAddrProvTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrSecAddrProvTable.setDescription('The SecAddrProv group defines one of the secondary addresses associated with a specific primary address.')
crsPAddrSAddrSecAddrProvEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 10, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsPAddrSAddrIndex"))
if mibBuilder.loadTexts: crsPAddrSAddrSecAddrProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrSecAddrProvEntry.setDescription('An entry in the crsPAddrSAddrSecAddrProvTable.')
crsPAddrSAddrAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 10, 1, 3), AsciiString().subtype(subtypeSpec=ValueSizeConstraint(1, 17))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsPAddrSAddrAddress.setStatus('mandatory')
if mibBuilder.loadTexts: crsPAddrSAddrAddress.setDescription('This attribute specifies a secondary address to which the primary address is redirected. The address attribute includes the Numbering Plan Indicator (NPI) and the digits which form a unique identifier of the customer interface. The address may belong to the X.121 or E.164 addressing plan. Address digits are selected and assigned by network operators. The address attribute takes the form: x.<X.121 address> or e.<E.164 address>')
crsAltRid = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3))
crsAltRidRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1), )
if mibBuilder.loadTexts: crsAltRidRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidRowStatusTable.setDescription('This entry controls the addition and deletion of crsAltRid components.')
crsAltRidRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsAltRidIndex"))
if mibBuilder.loadTexts: crsAltRidRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidRowStatusEntry.setDescription('A single entry in the table represents a single crsAltRid component.')
crsAltRidRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 1), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsAltRidRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsAltRid components. These components can be added and deleted.')
crsAltRidComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsAltRidComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crsAltRidStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: crsAltRidStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidStorageType.setDescription('This variable represents the storage type value for the crsAltRid tables.')
crsAltRidIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 10), NonReplicated())
if mibBuilder.loadTexts: crsAltRidIndex.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidIndex.setDescription('This variable represents the index for the crsAltRid tables.')
crsAltRidAltRidProvTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 10), )
if mibBuilder.loadTexts: crsAltRidAltRidProvTable.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidAltRidProvTable.setDescription('The AltRidProv group defines the alternate RID associated with the Crs component.')
crsAltRidAltRidProvEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 10, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsIndex"), (0, "Nortel-Magellan-Passport-CallRedirectionMIB", "crsAltRidIndex"))
if mibBuilder.loadTexts: crsAltRidAltRidProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidAltRidProvEntry.setDescription('An entry in the crsAltRidAltRidProvTable.')
crsAltRidRoutingId = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 10, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 126))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: crsAltRidRoutingId.setStatus('mandatory')
if mibBuilder.loadTexts: crsAltRidRoutingId.setDescription('This attribute specifies a group of one or more interconnected nodes (called a subnet) to which the request is redirected.')
callRedirectionGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1))
callRedirectionGroupBE = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1, 5))
callRedirectionGroupBE01 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1, 5, 2))
callRedirectionGroupBE01A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1, 5, 2, 2))
callRedirectionCapabilities = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3))
callRedirectionCapabilitiesBE = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3, 5))
callRedirectionCapabilitiesBE01 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3, 5, 2))
callRedirectionCapabilitiesBE01A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3, 5, 2, 2))
mibBuilder.exportSymbols("Nortel-Magellan-Passport-CallRedirectionMIB", crsIndex=crsIndex, crsSecAddressListExhausted=crsSecAddressListExhausted, crsAltRid=crsAltRid, crsPAddrSRidMidRowStatusTable=crsPAddrSRidMidRowStatusTable, crsStorageType=crsStorageType, crsAddressRedirected=crsAddressRedirected, crsTotalAddresses=crsTotalAddresses, crsAltRidUnsuccessful=crsAltRidUnsuccessful, crsPAddrComponentName=crsPAddrComponentName, crsPrimaryMatches=crsPrimaryMatches, crsPAddrSRidMidRowStatus=crsPAddrSRidMidRowStatus, crsAltRidComponentName=crsAltRidComponentName, crsAltRidIndex=crsAltRidIndex, callRedirectionCapabilitiesBE01=callRedirectionCapabilitiesBE01, crsPAddrSRidMid=crsPAddrSRidMid, crsStateEntry=crsStateEntry, crsSecAddrUnsuccessful=crsSecAddrUnsuccessful, crsAltRidAltRidProvTable=crsAltRidAltRidProvTable, callRedirectionGroupBE01A=callRedirectionGroupBE01A, crsPAddrSRidMidStorageType=crsPAddrSRidMidStorageType, crsRowStatusEntry=crsRowStatusEntry, crsPAddrSRidMidIndex=crsPAddrSRidMidIndex, crsSecRidMidUnsuccessful=crsSecRidMidUnsuccessful, crsProvTable=crsProvTable, crsPAddrSRidMidModuleId=crsPAddrSRidMidModuleId, crsAltRidRoutingId=crsAltRidRoutingId, callRedirectionCapabilitiesBE=callRedirectionCapabilitiesBE, crsRowStatus=crsRowStatus, crsRowStatusTable=crsRowStatusTable, crsPAddrRowStatusEntry=crsPAddrRowStatusEntry, crsPAddrSAddrIndex=crsPAddrSAddrIndex, crsPAddrSRidMidRowStatusEntry=crsPAddrSRidMidRowStatusEntry, crsComponentName=crsComponentName, crsAltRidRowStatus=crsAltRidRowStatus, crsPAddrSRidMidRoutingId=crsPAddrSRidMidRoutingId, crsPAddrSAddrRowStatus=crsPAddrSAddrRowStatus, callRedirectionGroup=callRedirectionGroup, crsRidRedirected=crsRidRedirected, crs=crs, callRedirectionGroupBE=callRedirectionGroupBE, crsMaxAddrLenExceeded=crsMaxAddrLenExceeded, crsStateTable=crsStateTable, crsPAddr=crsPAddr, crsPAddrRowStatus=crsPAddrRowStatus, crsPAddrSAddrRowStatusEntry=crsPAddrSAddrRowStatusEntry, crsPAddrSAddr=crsPAddrSAddr, crsPAddrSAddrSecAddrProvTable=crsPAddrSAddrSecAddrProvTable, crsAltRidAltRidProvEntry=crsAltRidAltRidProvEntry, crsRidMidRedirected=crsRidMidRedirected, crsPAddrStorageType=crsPAddrStorageType, crsAltRidRowStatusTable=crsAltRidRowStatusTable, crsPAddrSRidMidRidMidProvTable=crsPAddrSRidMidRidMidProvTable, crsStatTable=crsStatTable, callRedirectionCapabilitiesBE01A=callRedirectionCapabilitiesBE01A, crsAltRidStorageType=crsAltRidStorageType, crsOperationalState=crsOperationalState, crsPAddrSAddrAddress=crsPAddrSAddrAddress, crsProvEntry=crsProvEntry, crsAdminState=crsAdminState, crsPAddrSAddrRowStatusTable=crsPAddrSAddrRowStatusTable, callRedirectionMIB=callRedirectionMIB, crsLogicalProcessor=crsLogicalProcessor, crsPAddrSRidMidRidMidProvEntry=crsPAddrSRidMidRidMidProvEntry, callRedirectionCapabilities=callRedirectionCapabilities, crsPAddrSRidMidComponentName=crsPAddrSRidMidComponentName, crsPAddrSAddrStorageType=crsPAddrSAddrStorageType, crsPAddrSAddrSecAddrProvEntry=crsPAddrSAddrSecAddrProvEntry, callRedirectionGroupBE01=callRedirectionGroupBE01, crsPAddrRowStatusTable=crsPAddrRowStatusTable, crsRequestsReceived=crsRequestsReceived, crsPAddrSAddrComponentName=crsPAddrSAddrComponentName, crsAltRidRowStatusEntry=crsAltRidRowStatusEntry, crsStatEntry=crsStatEntry, crsPAddrIndex=crsPAddrIndex, crsUsageState=crsUsageState)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_size_constraint, value_range_constraint, constraints_union, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint')
(row_status, integer32, storage_type, unsigned32, display_string, counter32) = mibBuilder.importSymbols('Nortel-Magellan-Passport-StandardTextualConventionsMIB', 'RowStatus', 'Integer32', 'StorageType', 'Unsigned32', 'DisplayString', 'Counter32')
(ascii_string, link, ascii_string_index, non_replicated) = mibBuilder.importSymbols('Nortel-Magellan-Passport-TextualConventionsMIB', 'AsciiString', 'Link', 'AsciiStringIndex', 'NonReplicated')
(components, passport_mi_bs) = mibBuilder.importSymbols('Nortel-Magellan-Passport-UsefulDefinitionsMIB', 'components', 'passportMIBs')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(ip_address, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, integer32, notification_type, gauge32, unsigned32, bits, module_identity, counter32, counter64, object_identity, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'Integer32', 'NotificationType', 'Gauge32', 'Unsigned32', 'Bits', 'ModuleIdentity', 'Counter32', 'Counter64', 'ObjectIdentity', 'TimeTicks')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
call_redirection_mib = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132))
crs = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132))
crs_row_status_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1))
if mibBuilder.loadTexts:
crsRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsRowStatusTable.setDescription('This entry controls the addition and deletion of crs components.')
crs_row_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'))
if mibBuilder.loadTexts:
crsRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsRowStatusEntry.setDescription('A single entry in the table represents a single crs component.')
crs_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 1), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
crsRowStatus.setDescription('This variable is used as the basis for SNMP naming of crs components. These components can be added and deleted.')
crs_component_name = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsComponentName.setStatus('mandatory')
if mibBuilder.loadTexts:
crsComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crs_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 4), storage_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsStorageType.setStatus('mandatory')
if mibBuilder.loadTexts:
crsStorageType.setDescription('This variable represents the storage type value for the crs tables.')
crs_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 1, 1, 10), non_replicated())
if mibBuilder.loadTexts:
crsIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
crsIndex.setDescription('This variable represents the index for the crs tables.')
crs_prov_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 10))
if mibBuilder.loadTexts:
crsProvTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsProvTable.setDescription('The Provisioned group contains provisionable attributes of the CallRedirectionServer component.')
crs_prov_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 10, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'))
if mibBuilder.loadTexts:
crsProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsProvEntry.setDescription('An entry in the crsProvTable.')
crs_logical_processor = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 10, 1, 2), link()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsLogicalProcessor.setStatus('mandatory')
if mibBuilder.loadTexts:
crsLogicalProcessor.setDescription('This attribute specifies the logical processor on which the call redirection server process is to run.')
crs_state_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11))
if mibBuilder.loadTexts:
crsStateTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsStateTable.setDescription('This group contains the three OSI State attributes. The descriptions generically indicate what each state attribute implies about the component. Note that not all the values and state combinations described here are supported by every component which uses this group. For component-specific information and the valid state combinations, refer to NTP 241-7001-150, Passport Operations and Maintenance Guide.')
crs_state_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'))
if mibBuilder.loadTexts:
crsStateEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsStateEntry.setDescription('An entry in the crsStateTable.')
crs_admin_state = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('locked', 0), ('unlocked', 1), ('shuttingDown', 2))).clone('unlocked')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsAdminState.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAdminState.setDescription('This attribute indicates the OSI Administrative State of the component. The value locked indicates that the component is administratively prohibited from providing services for its users. A Lock or Lock - force command has been previously issued for this component. When the value is locked, the value of usageState must be idle. The value shuttingDown indicates that the component is administratively permitted to provide service to its existing users only. A Lock command was issued against the component and it is in the process of shutting down. The value unlocked indicates that the component is administratively permitted to provide services for its users. To enter this state, issue an Unlock command to this component.')
crs_operational_state = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disabled', 0), ('enabled', 1))).clone('disabled')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsOperationalState.setStatus('mandatory')
if mibBuilder.loadTexts:
crsOperationalState.setDescription('This attribute indicates the OSI Operational State of the component. The value enabled indicates that the component is available for operation. Note that if adminState is locked, it would still not be providing service. The value disabled indicates that the component is not available for operation. For example, something is wrong with the component itself, or with another component on which this one depends. If the value is disabled, the usageState must be idle.')
crs_usage_state = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 11, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('idle', 0), ('active', 1), ('busy', 2))).clone('idle')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsUsageState.setStatus('mandatory')
if mibBuilder.loadTexts:
crsUsageState.setDescription('This attribute indicates the OSI Usage State of the component. The value idle indicates that the component is not currently in use. The value active indicates that the component is in use and has spare capacity to provide for additional users. The value busy indicates that the component is in use and has no spare operating capacity for additional users at this time.')
crs_stat_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12))
if mibBuilder.loadTexts:
crsStatTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsStatTable.setDescription('The Statistics operational group defines the statistics associated with the CallRedirectionServer component.')
crs_stat_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'))
if mibBuilder.loadTexts:
crsStatEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsStatEntry.setDescription('An entry in the crsStatTable.')
crs_total_addresses = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 2), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 4294967295))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsTotalAddresses.setStatus('mandatory')
if mibBuilder.loadTexts:
crsTotalAddresses.setDescription('The totalAddresses attribute indicates the number of PrimaryAddress components associated with the CallRedirectionServer component.')
crs_requests_received = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsRequestsReceived.setStatus('mandatory')
if mibBuilder.loadTexts:
crsRequestsReceived.setDescription('The requestsReceived attribute counts the number of redirection requests received by the CallRedirectionServer component. This counter wraps to 0 when it exceeds its maximum value.')
crs_primary_matches = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsPrimaryMatches.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPrimaryMatches.setDescription('The primaryMatches attribute counts the Call Redirection Server attempts to find a matching PrimaryAddress where the lookup attempt was successful. This counter wraps to 0 when it exceeds its maximum value.')
crs_sec_address_list_exhausted = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsSecAddressListExhausted.setStatus('mandatory')
if mibBuilder.loadTexts:
crsSecAddressListExhausted.setDescription('The secAddressListExhausted attribute counts the Call Redirection Server attempts to find a SecondaryAddress component given a PrimaryAddress component where the lookup attempt resulted in the exhaustion of the secondary redirection list. This counter wraps to 0 when it exceeds its maximum value.')
crs_max_addr_len_exceeded = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsMaxAddrLenExceeded.setStatus('mandatory')
if mibBuilder.loadTexts:
crsMaxAddrLenExceeded.setDescription('The maxAddrLenExceeded attribute counts how often the concatenation of the secondary address and the suffix digits from the original called address have exceeded the maximum of 15 digits. The suffix digits can be determined by removing the primary address digits from the front of the original called address. If appending the suffix digits to a secondary address causes the resulting address to exceed 15 digits, this secondary member is skipped and the next secondary member is tried.')
crs_sec_rid_mid_unsuccessful = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsSecRidMidUnsuccessful.setStatus('mandatory')
if mibBuilder.loadTexts:
crsSecRidMidUnsuccessful.setDescription('The secRidMidUnsuccessful attribute counts the number of RID/ MID redirections resulting in the destination address not being reached. This situation could occur when the destination address does not exist on the specified module or the specified module could not be reached.')
crs_sec_addr_unsuccessful = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsSecAddrUnsuccessful.setStatus('mandatory')
if mibBuilder.loadTexts:
crsSecAddrUnsuccessful.setDescription('The secAddrUnsuccessful attribute counts the number of Address redirections resulting in the destination user not being reached. This situation could occur when the destination user line is disabled, the destination address does not exist on the specified module, or the specified module could not be reached.')
crs_rid_redirected = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsRidRedirected.setStatus('mandatory')
if mibBuilder.loadTexts:
crsRidRedirected.setDescription('The ridRedirected attribute counts requests received by the Call Redirection Server resulting in the request being redirected to another RID specified by the AlternateRid component. This counter wraps to 0 when it exceeds its maximum value.')
crs_rid_mid_redirected = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsRidMidRedirected.setStatus('mandatory')
if mibBuilder.loadTexts:
crsRidMidRedirected.setDescription('The ridMidRedirected attribute counts requests received by the Call Redirection Server resulting in the request being redirected to another RID/MID specified by the SecondaryRidMid component. This counter wraps to 0 when it exceeds its maximum value.')
crs_address_redirected = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsAddressRedirected.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAddressRedirected.setDescription('The addressRedirected attribute counts requests received by the Call Redirection Server resulting in the request being redirected to another Address specified by the SecondaryAddress component. This counter wraps to 0 when it exceeds its maximum value.')
crs_alt_rid_unsuccessful = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 12, 1, 12), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsAltRidUnsuccessful.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidUnsuccessful.setDescription('The altRidUnsuccessful attribute counts the number of RID redirections resulting in the destination address not being reached. This situation could occur when the alternate RID cannot be reached, the module hosting the destination address is isolated, or the port associated with the secondary address is unavailable at the alternate RID.')
crs_p_addr = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2))
crs_p_addr_row_status_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1))
if mibBuilder.loadTexts:
crsPAddrRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrRowStatusTable.setDescription('This entry controls the addition and deletion of crsPAddr components.')
crs_p_addr_row_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrIndex'))
if mibBuilder.loadTexts:
crsPAddrRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrRowStatusEntry.setDescription('A single entry in the table represents a single crsPAddr component.')
crs_p_addr_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 1), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsPAddrRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsPAddr components. These components can be added and deleted.')
crs_p_addr_component_name = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsPAddrComponentName.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crs_p_addr_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 4), storage_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsPAddrStorageType.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrStorageType.setDescription('This variable represents the storage type value for the crsPAddr tables.')
crs_p_addr_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 1, 1, 10), ascii_string_index().subtype(subtypeSpec=value_size_constraint(1, 17)))
if mibBuilder.loadTexts:
crsPAddrIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrIndex.setDescription('This variable represents the index for the crsPAddr tables.')
crs_p_addr_s_rid_mid = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2))
crs_p_addr_s_rid_mid_row_status_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1))
if mibBuilder.loadTexts:
crsPAddrSRidMidRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidRowStatusTable.setDescription('This entry controls the addition and deletion of crsPAddrSRidMid components.')
crs_p_addr_s_rid_mid_row_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrSRidMidIndex'))
if mibBuilder.loadTexts:
crsPAddrSRidMidRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidRowStatusEntry.setDescription('A single entry in the table represents a single crsPAddrSRidMid component.')
crs_p_addr_s_rid_mid_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 1), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsPAddrSRidMidRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsPAddrSRidMid components. These components can be added and deleted.')
crs_p_addr_s_rid_mid_component_name = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsPAddrSRidMidComponentName.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crs_p_addr_s_rid_mid_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 4), storage_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsPAddrSRidMidStorageType.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidStorageType.setDescription('This variable represents the storage type value for the crsPAddrSRidMid tables.')
crs_p_addr_s_rid_mid_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 1, 1, 10), non_replicated())
if mibBuilder.loadTexts:
crsPAddrSRidMidIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidIndex.setDescription('This variable represents the index for the crsPAddrSRidMid tables.')
crs_p_addr_s_rid_mid_rid_mid_prov_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10))
if mibBuilder.loadTexts:
crsPAddrSRidMidRidMidProvTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidRidMidProvTable.setDescription('The SecRidMidProv group defines the secondary RID/MID pair associated with a specific primary address.')
crs_p_addr_s_rid_mid_rid_mid_prov_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrSRidMidIndex'))
if mibBuilder.loadTexts:
crsPAddrSRidMidRidMidProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidRidMidProvEntry.setDescription('An entry in the crsPAddrSRidMidRidMidProvTable.')
crs_p_addr_s_rid_mid_routing_id = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10, 1, 2), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 126))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsPAddrSRidMidRoutingId.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidRoutingId.setDescription('This attribute specifies a group of one or more interconnected nodes (called a subnet) to which the primary address is redirected.')
crs_p_addr_s_rid_mid_module_id = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 2, 10, 1, 3), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 1909))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsPAddrSRidMidModuleId.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSRidMidModuleId.setDescription('This attribute specifies a Passport node to which the primary address is redirected.')
crs_p_addr_s_addr = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3))
crs_p_addr_s_addr_row_status_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1))
if mibBuilder.loadTexts:
crsPAddrSAddrRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrRowStatusTable.setDescription('This entry controls the addition and deletion of crsPAddrSAddr components.')
crs_p_addr_s_addr_row_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrSAddrIndex'))
if mibBuilder.loadTexts:
crsPAddrSAddrRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrRowStatusEntry.setDescription('A single entry in the table represents a single crsPAddrSAddr component.')
crs_p_addr_s_addr_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 1), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsPAddrSAddrRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsPAddrSAddr components. These components can be added and deleted.')
crs_p_addr_s_addr_component_name = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsPAddrSAddrComponentName.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crs_p_addr_s_addr_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 4), storage_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsPAddrSAddrStorageType.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrStorageType.setDescription('This variable represents the storage type value for the crsPAddrSAddr tables.')
crs_p_addr_s_addr_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 1, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(1, 7)))
if mibBuilder.loadTexts:
crsPAddrSAddrIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrIndex.setDescription('This variable represents the index for the crsPAddrSAddr tables.')
crs_p_addr_s_addr_sec_addr_prov_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 10))
if mibBuilder.loadTexts:
crsPAddrSAddrSecAddrProvTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrSecAddrProvTable.setDescription('The SecAddrProv group defines one of the secondary addresses associated with a specific primary address.')
crs_p_addr_s_addr_sec_addr_prov_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 10, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsPAddrSAddrIndex'))
if mibBuilder.loadTexts:
crsPAddrSAddrSecAddrProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrSecAddrProvEntry.setDescription('An entry in the crsPAddrSAddrSecAddrProvTable.')
crs_p_addr_s_addr_address = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 2, 3, 10, 1, 3), ascii_string().subtype(subtypeSpec=value_size_constraint(1, 17))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsPAddrSAddrAddress.setStatus('mandatory')
if mibBuilder.loadTexts:
crsPAddrSAddrAddress.setDescription('This attribute specifies a secondary address to which the primary address is redirected. The address attribute includes the Numbering Plan Indicator (NPI) and the digits which form a unique identifier of the customer interface. The address may belong to the X.121 or E.164 addressing plan. Address digits are selected and assigned by network operators. The address attribute takes the form: x.<X.121 address> or e.<E.164 address>')
crs_alt_rid = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3))
crs_alt_rid_row_status_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1))
if mibBuilder.loadTexts:
crsAltRidRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidRowStatusTable.setDescription('This entry controls the addition and deletion of crsAltRid components.')
crs_alt_rid_row_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsAltRidIndex'))
if mibBuilder.loadTexts:
crsAltRidRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidRowStatusEntry.setDescription('A single entry in the table represents a single crsAltRid component.')
crs_alt_rid_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 1), row_status()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsAltRidRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidRowStatus.setDescription('This variable is used as the basis for SNMP naming of crsAltRid components. These components can be added and deleted.')
crs_alt_rid_component_name = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsAltRidComponentName.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
crs_alt_rid_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 4), storage_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
crsAltRidStorageType.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidStorageType.setDescription('This variable represents the storage type value for the crsAltRid tables.')
crs_alt_rid_index = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 1, 1, 10), non_replicated())
if mibBuilder.loadTexts:
crsAltRidIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidIndex.setDescription('This variable represents the index for the crsAltRid tables.')
crs_alt_rid_alt_rid_prov_table = mib_table((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 10))
if mibBuilder.loadTexts:
crsAltRidAltRidProvTable.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidAltRidProvTable.setDescription('The AltRidProv group defines the alternate RID associated with the Crs component.')
crs_alt_rid_alt_rid_prov_entry = mib_table_row((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 10, 1)).setIndexNames((0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsIndex'), (0, 'Nortel-Magellan-Passport-CallRedirectionMIB', 'crsAltRidIndex'))
if mibBuilder.loadTexts:
crsAltRidAltRidProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidAltRidProvEntry.setDescription('An entry in the crsAltRidAltRidProvTable.')
crs_alt_rid_routing_id = mib_table_column((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 132, 3, 10, 1, 2), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 126))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
crsAltRidRoutingId.setStatus('mandatory')
if mibBuilder.loadTexts:
crsAltRidRoutingId.setDescription('This attribute specifies a group of one or more interconnected nodes (called a subnet) to which the request is redirected.')
call_redirection_group = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1))
call_redirection_group_be = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1, 5))
call_redirection_group_be01 = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1, 5, 2))
call_redirection_group_be01_a = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 1, 5, 2, 2))
call_redirection_capabilities = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3))
call_redirection_capabilities_be = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3, 5))
call_redirection_capabilities_be01 = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3, 5, 2))
call_redirection_capabilities_be01_a = mib_identifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 132, 3, 5, 2, 2))
mibBuilder.exportSymbols('Nortel-Magellan-Passport-CallRedirectionMIB', crsIndex=crsIndex, crsSecAddressListExhausted=crsSecAddressListExhausted, crsAltRid=crsAltRid, crsPAddrSRidMidRowStatusTable=crsPAddrSRidMidRowStatusTable, crsStorageType=crsStorageType, crsAddressRedirected=crsAddressRedirected, crsTotalAddresses=crsTotalAddresses, crsAltRidUnsuccessful=crsAltRidUnsuccessful, crsPAddrComponentName=crsPAddrComponentName, crsPrimaryMatches=crsPrimaryMatches, crsPAddrSRidMidRowStatus=crsPAddrSRidMidRowStatus, crsAltRidComponentName=crsAltRidComponentName, crsAltRidIndex=crsAltRidIndex, callRedirectionCapabilitiesBE01=callRedirectionCapabilitiesBE01, crsPAddrSRidMid=crsPAddrSRidMid, crsStateEntry=crsStateEntry, crsSecAddrUnsuccessful=crsSecAddrUnsuccessful, crsAltRidAltRidProvTable=crsAltRidAltRidProvTable, callRedirectionGroupBE01A=callRedirectionGroupBE01A, crsPAddrSRidMidStorageType=crsPAddrSRidMidStorageType, crsRowStatusEntry=crsRowStatusEntry, crsPAddrSRidMidIndex=crsPAddrSRidMidIndex, crsSecRidMidUnsuccessful=crsSecRidMidUnsuccessful, crsProvTable=crsProvTable, crsPAddrSRidMidModuleId=crsPAddrSRidMidModuleId, crsAltRidRoutingId=crsAltRidRoutingId, callRedirectionCapabilitiesBE=callRedirectionCapabilitiesBE, crsRowStatus=crsRowStatus, crsRowStatusTable=crsRowStatusTable, crsPAddrRowStatusEntry=crsPAddrRowStatusEntry, crsPAddrSAddrIndex=crsPAddrSAddrIndex, crsPAddrSRidMidRowStatusEntry=crsPAddrSRidMidRowStatusEntry, crsComponentName=crsComponentName, crsAltRidRowStatus=crsAltRidRowStatus, crsPAddrSRidMidRoutingId=crsPAddrSRidMidRoutingId, crsPAddrSAddrRowStatus=crsPAddrSAddrRowStatus, callRedirectionGroup=callRedirectionGroup, crsRidRedirected=crsRidRedirected, crs=crs, callRedirectionGroupBE=callRedirectionGroupBE, crsMaxAddrLenExceeded=crsMaxAddrLenExceeded, crsStateTable=crsStateTable, crsPAddr=crsPAddr, crsPAddrRowStatus=crsPAddrRowStatus, crsPAddrSAddrRowStatusEntry=crsPAddrSAddrRowStatusEntry, crsPAddrSAddr=crsPAddrSAddr, crsPAddrSAddrSecAddrProvTable=crsPAddrSAddrSecAddrProvTable, crsAltRidAltRidProvEntry=crsAltRidAltRidProvEntry, crsRidMidRedirected=crsRidMidRedirected, crsPAddrStorageType=crsPAddrStorageType, crsAltRidRowStatusTable=crsAltRidRowStatusTable, crsPAddrSRidMidRidMidProvTable=crsPAddrSRidMidRidMidProvTable, crsStatTable=crsStatTable, callRedirectionCapabilitiesBE01A=callRedirectionCapabilitiesBE01A, crsAltRidStorageType=crsAltRidStorageType, crsOperationalState=crsOperationalState, crsPAddrSAddrAddress=crsPAddrSAddrAddress, crsProvEntry=crsProvEntry, crsAdminState=crsAdminState, crsPAddrSAddrRowStatusTable=crsPAddrSAddrRowStatusTable, callRedirectionMIB=callRedirectionMIB, crsLogicalProcessor=crsLogicalProcessor, crsPAddrSRidMidRidMidProvEntry=crsPAddrSRidMidRidMidProvEntry, callRedirectionCapabilities=callRedirectionCapabilities, crsPAddrSRidMidComponentName=crsPAddrSRidMidComponentName, crsPAddrSAddrStorageType=crsPAddrSAddrStorageType, crsPAddrSAddrSecAddrProvEntry=crsPAddrSAddrSecAddrProvEntry, callRedirectionGroupBE01=callRedirectionGroupBE01, crsPAddrRowStatusTable=crsPAddrRowStatusTable, crsRequestsReceived=crsRequestsReceived, crsPAddrSAddrComponentName=crsPAddrSAddrComponentName, crsAltRidRowStatusEntry=crsAltRidRowStatusEntry, crsStatEntry=crsStatEntry, crsPAddrIndex=crsPAddrIndex, crsUsageState=crsUsageState) |
def make_adder(x):
def adder(y):
return x + y
return adder
inc = make_adder(1)
plus10 = make_adder(10)
___assertEqual(inc(1), 2)
___assertEqual(plus10(-2), 8)
| def make_adder(x):
def adder(y):
return x + y
return adder
inc = make_adder(1)
plus10 = make_adder(10)
___assert_equal(inc(1), 2)
___assert_equal(plus10(-2), 8) |
class Solution:
def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:
if x == 1:
i_max = 0
else:
i_max = int(math.log(bound,x))
if y == 1:
j_max = 0
else:
j_max = int(math.log(bound,y))
res = []
for i in range(i_max+1):
for j in range(j_max+1):
tmp = x**i + y**j
if tmp <= bound and tmp not in res:
res.append(tmp)
return res
| class Solution:
def powerful_integers(self, x: int, y: int, bound: int) -> List[int]:
if x == 1:
i_max = 0
else:
i_max = int(math.log(bound, x))
if y == 1:
j_max = 0
else:
j_max = int(math.log(bound, y))
res = []
for i in range(i_max + 1):
for j in range(j_max + 1):
tmp = x ** i + y ** j
if tmp <= bound and tmp not in res:
res.append(tmp)
return res |
# Programacion orientada a objetos 1
# https://www.youtube.com/watch?v=lg9p0yWgXYk&list=PLh7JzoyIyU4JVOeKkiNYPkAWBq0Aszxc-&index=2
class Persona:
def __init__(self, nombre_persona, calle=1):
self.nombre = nombre_persona
self.calle = calle
def moverse(self, velocidad):
self.calle += velocidad
jose = Persona("Jose")
juan = Persona("Juan", 2)
print(jose.nombre)
print(juan.nombre)
print(jose.calle)
print(juan.calle)
jose.moverse(5)
print(jose.calle)
| class Persona:
def __init__(self, nombre_persona, calle=1):
self.nombre = nombre_persona
self.calle = calle
def moverse(self, velocidad):
self.calle += velocidad
jose = persona('Jose')
juan = persona('Juan', 2)
print(jose.nombre)
print(juan.nombre)
print(jose.calle)
print(juan.calle)
jose.moverse(5)
print(jose.calle) |
""" Given an integer array, find three numbers whose product is maximum and
output the maximum product.
Example 1: Input: [1,2,3] Output: 6
IDEA:
track
3 maximum numbers in desc order (max1 is the biggest)
and
2 smallest
"""
class Solution628:
pass
| """ Given an integer array, find three numbers whose product is maximum and
output the maximum product.
Example 1: Input: [1,2,3] Output: 6
IDEA:
track
3 maximum numbers in desc order (max1 is the biggest)
and
2 smallest
"""
class Solution628:
pass |
# simplified linked list
class Node:
def __init__ (self, value, next=None):
self.value = value
self.next = next
L = Node('a', Node('b', Node('c', Node('d'))))
# print('L', L.value)
# print(L.next.next.value)
| class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
l = node('a', node('b', node('c', node('d')))) |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def bstToGst(self, root: TreeNode) -> TreeNode:
def f(root, val = 0):
if root is None:
return 0
rightValue = f(root.right, val)
leftValue = f(root.left, root.val + rightValue + val)
t = root.val
root.val += rightValue + val
return t + leftValue + rightValue
f(root)
return root
| class Solution:
def bst_to_gst(self, root: TreeNode) -> TreeNode:
def f(root, val=0):
if root is None:
return 0
right_value = f(root.right, val)
left_value = f(root.left, root.val + rightValue + val)
t = root.val
root.val += rightValue + val
return t + leftValue + rightValue
f(root)
return root |
tokens = {
"WETH": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
"DAI": "0x6B175474E89094C44Da98b954EedeAC495271d0F",
"BAT": "0x0D8775F648430679A709E98d2b0Cb6250d2887EF",
"WBTC": "0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599",
"UNI": "0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984",
}
| tokens = {'WETH': '0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2', 'DAI': '0x6B175474E89094C44Da98b954EedeAC495271d0F', 'BAT': '0x0D8775F648430679A709E98d2b0Cb6250d2887EF', 'WBTC': '0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599', 'UNI': '0x1f9840a85d5aF5bf1D1762F925BDADdC4201F984'} |
# -*- coding: utf-8 -*-
casos = int(input())
result = []
for i in range(casos):
num1, num2, indice1, indice2 = input().split(" ")
num1 = int(num1)
num2 = int(num2)
indice1 = float(indice1)
indice2 = float(indice2)
anos = 0
while num1 <= num2:
num1 += int(num1*indice1/100)
num2 += int(num2*indice2/100)
anos +=1
if anos > 100:
result.append('Mais de 1 seculo.')
break
if anos <= 100:
result.append('{} anos.'.format(anos))
for i in result:
print(i) | casos = int(input())
result = []
for i in range(casos):
(num1, num2, indice1, indice2) = input().split(' ')
num1 = int(num1)
num2 = int(num2)
indice1 = float(indice1)
indice2 = float(indice2)
anos = 0
while num1 <= num2:
num1 += int(num1 * indice1 / 100)
num2 += int(num2 * indice2 / 100)
anos += 1
if anos > 100:
result.append('Mais de 1 seculo.')
break
if anos <= 100:
result.append('{} anos.'.format(anos))
for i in result:
print(i) |
"""
1. Clarification
2. Possible solutions
- Trie
- Queue
3. Coding
4. Tests
"""
# T=O(n), S=O(n)
class WordDictionary:
def __init__(self):
self.root = {}
self.end_of_word = '#'
def addWord(self, word: str) -> None:
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.end_of_word] = self.end_of_word
def search(self, word: str) -> bool:
cut = False
def dfs(trie, s):
nonlocal cut
if cut:
return True
t = trie
for i, c in enumerate(s):
if c == '.':
return any(dfs(t[j], s[i + 1: ]) for j in t if j != self.end_of_word)
if c not in t:
return False
t = t[c]
cut = self.end_of_word in t
return cut
return dfs(self.root, word)
# T=O(n), S=O(n)
class WordDictionary:
def __init__(self):
self.d = collections.defaultdict(list)
def addWord(self, word: str) -> None:
self.d[len(word)] += [word]
def search(self, word: str) -> bool:
n = len(word)
f = lambda s: all(map(lambda i: word[i] in {s[i], '.'}, range(n)))
return any(map(f, self.d[n]))
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
| """
1. Clarification
2. Possible solutions
- Trie
- Queue
3. Coding
4. Tests
"""
class Worddictionary:
def __init__(self):
self.root = {}
self.end_of_word = '#'
def add_word(self, word: str) -> None:
node = self.root
for char in word:
node = node.setdefault(char, {})
node[self.end_of_word] = self.end_of_word
def search(self, word: str) -> bool:
cut = False
def dfs(trie, s):
nonlocal cut
if cut:
return True
t = trie
for (i, c) in enumerate(s):
if c == '.':
return any((dfs(t[j], s[i + 1:]) for j in t if j != self.end_of_word))
if c not in t:
return False
t = t[c]
cut = self.end_of_word in t
return cut
return dfs(self.root, word)
class Worddictionary:
def __init__(self):
self.d = collections.defaultdict(list)
def add_word(self, word: str) -> None:
self.d[len(word)] += [word]
def search(self, word: str) -> bool:
n = len(word)
f = lambda s: all(map(lambda i: word[i] in {s[i], '.'}, range(n)))
return any(map(f, self.d[n])) |
"""Constants."""
CACHE_NAME = 'infographics'
CACHE_TIMEOUT = 3600
| """Constants."""
cache_name = 'infographics'
cache_timeout = 3600 |
if __name__ == '__main__':
arr = []
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([name,score])
arr.sort()
first = 100000
second = 100000
for i in range(len(arr)):
if (arr[i][1] < first):
second = first
first = arr[i][1]
elif (arr[i][1] < second and arr[i][1] != first):
second = arr[i][1]
for x in range(len(arr)):
if(arr[x][1] == second):
print(arr[x][0])
| if __name__ == '__main__':
arr = []
for _ in range(int(input())):
name = input()
score = float(input())
arr.append([name, score])
arr.sort()
first = 100000
second = 100000
for i in range(len(arr)):
if arr[i][1] < first:
second = first
first = arr[i][1]
elif arr[i][1] < second and arr[i][1] != first:
second = arr[i][1]
for x in range(len(arr)):
if arr[x][1] == second:
print(arr[x][0]) |
# Find First and Last Position of Element in Sorted Array
class Solution:
def binSearch(self, nums, target):
length = len(nums)
left, right = 0, length - 1
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
while mid >= 0 and nums[mid] == target:
mid -= 1
return mid + 1
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
def searchRange(self, nums, target):
found = self.binSearch(nums, target)
if found == -1:
return [-1, -1]
start = found
while found < len(nums) and nums[found] == target:
found += 1
return [start, found - 1]
if __name__ == "__main__":
sol = Solution()
nums = [1, 1]
target = 1
print(sol.searchRange(nums, target))
| class Solution:
def bin_search(self, nums, target):
length = len(nums)
(left, right) = (0, length - 1)
while left <= right:
mid = (left + right) // 2
if nums[mid] == target:
while mid >= 0 and nums[mid] == target:
mid -= 1
return mid + 1
elif nums[mid] > target:
right = mid - 1
else:
left = mid + 1
return -1
def search_range(self, nums, target):
found = self.binSearch(nums, target)
if found == -1:
return [-1, -1]
start = found
while found < len(nums) and nums[found] == target:
found += 1
return [start, found - 1]
if __name__ == '__main__':
sol = solution()
nums = [1, 1]
target = 1
print(sol.searchRange(nums, target)) |
# def find_all_index(text, pattern):
# pattern_index = 0
# match = []
# # if pattern is empty, then return all indices
# if pattern == '':
# for index in range(len(text)):
# match.append(index)
# return match
# for index, charc in enumerate(text):
# # check if letters are the same
# if charc == pattern[pattern_index]:
# pattern_index += 1
# # if we've reached the end of the pattern index return the start of
# # the pattern in the text
# if pattern_index == len(pattern):
# match.append(index - (pattern_index - 1))
# pattern_index = 0
# # they are not the same
# else:
# pattern_index = 0
# if not match: # list is empty
# return None
# return match
def find_all_index(text, pattern):
match = []
if pattern == '':
for index in range(len(text)):
match.append(index)
return match
for t_index, t_char in enumerate(text):
print("t_index: ", t_index)
for p_index, p_char in enumerate(pattern):
# check if more characters in the text match characters in the
# pattern
print(" p_index {}, p_char {}".format(p_index, p_char))
# check if it is a valid index of the text
if t_index + p_index > (len(text)-1):
break # not a valid index
text_char = text[t_index + p_index]
# check if letters are the same
if text_char == p_char:
# check if the letters are the same and we've reached the last
# index of the pattern
if p_index == (len(pattern) - 1):
# append the position of the charc where the pattern and text
# first matched
match.append(t_index)
# append the text index minus the pattern index
continue
# they are not the same
else:
break
if not match: # check if match is empty # Really helpful resource to find solution: https://www.python-course.eu/python3_for_loop.php
# tried all possible starting indexes in text, never found a perfect match
return None
# all characters in the pattern matched in the text
return match
if __name__ == '__main__':
print(find_all_index('aaa', 'aa'))
| def find_all_index(text, pattern):
match = []
if pattern == '':
for index in range(len(text)):
match.append(index)
return match
for (t_index, t_char) in enumerate(text):
print('t_index: ', t_index)
for (p_index, p_char) in enumerate(pattern):
print(' p_index {}, p_char {}'.format(p_index, p_char))
if t_index + p_index > len(text) - 1:
break
text_char = text[t_index + p_index]
if text_char == p_char:
if p_index == len(pattern) - 1:
match.append(t_index)
continue
else:
break
if not match:
return None
return match
if __name__ == '__main__':
print(find_all_index('aaa', 'aa')) |
def mergeSort(list):
if len(list) <= 1:
return list
# Find the middle point and devide it
middle = len(list) // 2
left_list = list[:middle]
right_list = list[middle:]
left_list = mergeSort(left_list)
right_list = mergeSort(right_list)
return merge(left_list, right_list)
# Merge the sorted halves
def merge(left_half,right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res
| def merge_sort(list):
if len(list) <= 1:
return list
middle = len(list) // 2
left_list = list[:middle]
right_list = list[middle:]
left_list = merge_sort(left_list)
right_list = merge_sort(right_list)
return merge(left_list, right_list)
def merge(left_half, right_half):
res = []
while len(left_half) != 0 and len(right_half) != 0:
if left_half[0] < right_half[0]:
res.append(left_half[0])
left_half.remove(left_half[0])
else:
res.append(right_half[0])
right_half.remove(right_half[0])
if len(left_half) == 0:
res = res + right_half
else:
res = res + left_half
return res |
class HTTPException(Exception):
def __init__(self, request, data):
msg = f"HTTP request returned {request.status} status code."
self.request = request
for k, v in data.items():
setattr(self, k, v)
msg += f"\nIn {k}: {v}"
return super().__init__(msg)
class TooManyRequests(HTTPException):
pass
class BadRequest(HTTPException):
pass
| class Httpexception(Exception):
def __init__(self, request, data):
msg = f'HTTP request returned {request.status} status code.'
self.request = request
for (k, v) in data.items():
setattr(self, k, v)
msg += f'\nIn {k}: {v}'
return super().__init__(msg)
class Toomanyrequests(HTTPException):
pass
class Badrequest(HTTPException):
pass |
"""
Supplai Version: Generated by python setup.py
"""
__version__ = "0.4.0"
| """
Supplai Version: Generated by python setup.py
"""
__version__ = '0.4.0' |
CARD_VALUES = {
'2': 1,
'3': 1,
'4': 1,
'5': 1,
'6': 1,
'7': 0,
'8': 0,
'9': 0,
'0': -1,
'1': -1,
'J': -1,
'Q': -1,
'K': -1,
'A': -1,
'*': -1
}
DECKS = 8
def main():
count = 0
cards = 0
user_input = True
decks_played = 0
while user_input:
user_input = input('CARDS >> ')
user_input = user_input.upper()
if user_input == "DONE":
break
cards += len(user_input)
for card in user_input:
count += CARD_VALUES[card]
decks_played = cards / 52.0
true_count = count / (DECKS - decks_played)
print('Count: {}'.format(count))
print('True Count: {:2.2f}'.format(true_count))
print('Decks Played: {:1.2f}'.format(decks_played))
if __name__ == '__main__':
main()
| card_values = {'2': 1, '3': 1, '4': 1, '5': 1, '6': 1, '7': 0, '8': 0, '9': 0, '0': -1, '1': -1, 'J': -1, 'Q': -1, 'K': -1, 'A': -1, '*': -1}
decks = 8
def main():
count = 0
cards = 0
user_input = True
decks_played = 0
while user_input:
user_input = input('CARDS >> ')
user_input = user_input.upper()
if user_input == 'DONE':
break
cards += len(user_input)
for card in user_input:
count += CARD_VALUES[card]
decks_played = cards / 52.0
true_count = count / (DECKS - decks_played)
print('Count: {}'.format(count))
print('True Count: {:2.2f}'.format(true_count))
print('Decks Played: {:1.2f}'.format(decks_played))
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
# Author: Arthur Imbert <arthur.imbert.pro@gmail.com>
# License: BSD 3 clause
"""
Unitary tests for bigfish.detection.spot_detection module.
"""
# TODO test bigfish.detection.detect_spots
# TODO test bigfish.detection.local_maximum_detection
# TODO test bigfish.detection.spots_thresholding
# TODO test bigfish.detection.automated_threshold_setting
| """
Unitary tests for bigfish.detection.spot_detection module.
""" |
################### EXERCISE 1 ###############################################
# Constants
METER_PER_INCH = 0.0254
INCHES_PER_FEET = 12
feet = int(input('Enter the number of feet:'))
inches = int(input('Enter the number of inches:'))
number_meters = (feet * INCHES_PER_FEET + inches) * METER_PER_INCH
print(feet,'feet',inches,'inches is equivalent to', number_meters,'meters')
metres = float(input('Enter the number of metres:'))
number_inches = int(metres/METER_PER_INCH)
feet = number_inches//INCHES_PER_FEET
inches = number_inches % INCHES_PER_FEET
print(metres,'metres is equivalent to', feet, 'feet and',inches,'inches.')
################### EXERCISE 3 ###############################################
weight = float(input('Enter the number of Kg of banana you want to order: '))
cost = 3 * weight
if cost >50:
cost += 4.99 - 1.50
else:
cost += 4.99
print('The cost of the order is:', cost)
################### EXERCISE 4 ###############################################
age = int(input('Enter your age: '))
max_rate = 208 - 0.7 * age
rate = int(input('Enter your current heart rate: '))
# Be careful, the order of the conditions in the if-elif-else does matter. If I
# swap the second and third condition, the logic will be incorrect. The program
# will return something, but it will be incorrect.
if rate >= 0.9 * max_rate:
print('Interval training')
elif rate >= 0.7 * max_rate:
print('Threshold training')
elif rate >= 0.5 * max_rate:
print('Aerobic training')
else:
print('Couch potato')
################### EXERCISE 5 ###############################################
size_a = float(input('Enter the length of the first side of the triangle: '))
size_b = float(input('Enter the length of the second side of the triangle: '))
size_c = float(input('Enter the length of the third side of the triangle: '))
semi_perimeter = (size_a + size_b + size_c)/2
area = pow(semi_perimeter
* (semi_perimeter - size_a)
* (semi_perimeter - size_b)
* (semi_perimeter - size_c),
0.5)
print('The area of the triangle is', area)
| meter_per_inch = 0.0254
inches_per_feet = 12
feet = int(input('Enter the number of feet:'))
inches = int(input('Enter the number of inches:'))
number_meters = (feet * INCHES_PER_FEET + inches) * METER_PER_INCH
print(feet, 'feet', inches, 'inches is equivalent to', number_meters, 'meters')
metres = float(input('Enter the number of metres:'))
number_inches = int(metres / METER_PER_INCH)
feet = number_inches // INCHES_PER_FEET
inches = number_inches % INCHES_PER_FEET
print(metres, 'metres is equivalent to', feet, 'feet and', inches, 'inches.')
weight = float(input('Enter the number of Kg of banana you want to order: '))
cost = 3 * weight
if cost > 50:
cost += 4.99 - 1.5
else:
cost += 4.99
print('The cost of the order is:', cost)
age = int(input('Enter your age: '))
max_rate = 208 - 0.7 * age
rate = int(input('Enter your current heart rate: '))
if rate >= 0.9 * max_rate:
print('Interval training')
elif rate >= 0.7 * max_rate:
print('Threshold training')
elif rate >= 0.5 * max_rate:
print('Aerobic training')
else:
print('Couch potato')
size_a = float(input('Enter the length of the first side of the triangle: '))
size_b = float(input('Enter the length of the second side of the triangle: '))
size_c = float(input('Enter the length of the third side of the triangle: '))
semi_perimeter = (size_a + size_b + size_c) / 2
area = pow(semi_perimeter * (semi_perimeter - size_a) * (semi_perimeter - size_b) * (semi_perimeter - size_c), 0.5)
print('The area of the triangle is', area) |
expected_output = {
'ikev2_session': {
'IPv4':{
1:{
'session_id': 3,
'status': 'UP-ACTIVE',
'ike_count': 1,
'child_count': 1,
'tunnel_id': 1,
'local_ip': '1.1.1.1',
'local_port': 500,
'remote_ip': '1.1.1.2',
'remote_port': 500,
'fvrf': 'none',
'ivrf': 'none',
'session_status': 'READY',
'encryption': 'AES-CBC',
'key_length': 256,
'prf': 'SHA256',
'hash_algo': 'SHA256',
'dh_group': 14,
'auth_sign': 'PSK',
'auth_verify': 'PSK',
'lifetime': 86400,
'activetime': 38157,
'ce_id': 1008,
'id': 3,
'local_spi': '6F86196AB2C574E3',
'remote_spi': '74AD695CF23C4805',
'local_id': '1.1.1.1',
'remote_id': '1.1.1.2',
'local_mesg_id': 2,
'remote_mesg_id': 0,
'local_next_id': 2,
'remote_next_id': 0,
'local_queued': 2,
'remote_queued': 0,
'local_window': 5,
'remote_window': 5,
'dpd_time': 0,
'dpd_retry': 0,
'fragmentation': 'no',
'dynamic_route': 'enabled',
'nat_detected': 'no',
'cts_sgt': 'disabled',
'initiator_of_sa': 'Yes',
'child_sa':{
1:{
'local_selectors': ['30.10.10.0/0 - 50.10.10.255/65535','20.10.10.0/0 - 40.10.10.255/65535'],
'remote_selectors': ['172.17.2.0/0 - 172.17.2.255/65535','172.17.2.0/0 - 172.17.3.255/65535'],
'esp_spi_in': '0x232CB82D',
'esp_spi_out': '0x30767B6E',
'ah_spi_in': '0x0',
'ah_spi_out': '0x0',
'cpi_in': '0x0',
'cpi_out': '0x0',
'child_encr': 'AES-CBC',
'keysize': 256,
'esp_hmac': 'SHA256',
'ah_hmac': 'None',
'compression': 'IPCOMP_NONE',
'mode': 'tunnel',
},
2:{
'local_selectors': ['20.10.10.0/0 - 40.10.10.255/65535'],
'remote_selectors': ['50.20.20.0/0 - 60.20.20.255/65535'],
'esp_spi_in': '0x232CB82D',
'esp_spi_out': '0x30767B6E',
'ah_spi_in': '0x0',
'ah_spi_out': '0x0',
'cpi_in': '0x0',
'cpi_out': '0x0',
'child_encr': 'AES-CBC',
'keysize': 256,
'esp_hmac': 'SHA256',
'ah_hmac': 'None',
'compression': 'IPCOMP_NONE',
'mode': 'tunnel',
},
},
},
},
'IPv6':{
1:{
'session_id': 5,
'status': 'UP-ACTIVE',
'ike_count': 1,
'child_count': 1,
'tunnel_id': 1,
'local_ip': '1.1.1::1',
'local_port': 500,
'remote_ip': '1.1.1::2',
'remote_port': 500,
'fvrf': 'none',
'ivrf': 'none',
'session_status': 'READY',
'encryption': 'AES-CBC',
'key_length': 256,
'prf': 'SHA256',
'hash_algo': 'SHA256',
'dh_group': 14,
'auth_sign': 'PSK',
'auth_verify': 'PSK',
'lifetime': 86400,
'activetime': 38157,
'ce_id': 1008,
'id': 3,
'local_spi': '6F86196AB2C574E5',
'remote_spi': '74AD695CF23C4806',
'local_id': '1.1.1::1',
'remote_id': '1.1.1::2',
'local_mesg_id': 2,
'remote_mesg_id': 0,
'local_next_id': 2,
'remote_next_id': 0,
'local_queued': 2,
'remote_queued': 0,
'local_window': 5,
'remote_window': 5,
'dpd_time': 0,
'dpd_retry': 0,
'fragmentation': 'no',
'dynamic_route': 'enabled',
'nat_detected': 'no',
'cts_sgt': 'disabled',
'initiator_of_sa': 'Yes',
'child_sa':{
1:{
'local_selectors': ['30.10.10::0/0 - 50.10.10::255/65535','20.10.10::0/0 - 40.10.10::255/65535'],
'remote_selectors': ['172.17.2::0/0 - 172.17.2::255/65535','172.17.2::0/0 - 172.17.3::255/65535'],
'esp_spi_in': '0x232CB82D',
'esp_spi_out': '0x30767B6E',
'ah_spi_in': '0x0',
'ah_spi_out': '0x0',
'cpi_in': '0x0',
'cpi_out': '0x0',
'child_encr': 'AES-CBC',
'keysize': 256,
'esp_hmac': 'SHA256',
'ah_hmac': 'None',
'compression': 'IPCOMP_NONE',
'mode': 'tunnel',
},
2:{
'local_selectors': ['20.10.10::0/0 - 40.10.10::255/65535'],
'remote_selectors': ['50.20.20::0/0 - 60.20.20::255/65535'],
'esp_spi_in': '0x232CB82D',
'esp_spi_out': '0x30767B6E',
'ah_spi_in': '0x0',
'ah_spi_out': '0x0',
'cpi_in': '0x0',
'cpi_out': '0x0',
'child_encr': 'AES-CBC',
'keysize': 256,
'esp_hmac': 'SHA256',
'ah_hmac': 'None',
'compression': 'IPCOMP_NONE',
'mode': 'tunnel',
},
},
},
},
},
} | expected_output = {'ikev2_session': {'IPv4': {1: {'session_id': 3, 'status': 'UP-ACTIVE', 'ike_count': 1, 'child_count': 1, 'tunnel_id': 1, 'local_ip': '1.1.1.1', 'local_port': 500, 'remote_ip': '1.1.1.2', 'remote_port': 500, 'fvrf': 'none', 'ivrf': 'none', 'session_status': 'READY', 'encryption': 'AES-CBC', 'key_length': 256, 'prf': 'SHA256', 'hash_algo': 'SHA256', 'dh_group': 14, 'auth_sign': 'PSK', 'auth_verify': 'PSK', 'lifetime': 86400, 'activetime': 38157, 'ce_id': 1008, 'id': 3, 'local_spi': '6F86196AB2C574E3', 'remote_spi': '74AD695CF23C4805', 'local_id': '1.1.1.1', 'remote_id': '1.1.1.2', 'local_mesg_id': 2, 'remote_mesg_id': 0, 'local_next_id': 2, 'remote_next_id': 0, 'local_queued': 2, 'remote_queued': 0, 'local_window': 5, 'remote_window': 5, 'dpd_time': 0, 'dpd_retry': 0, 'fragmentation': 'no', 'dynamic_route': 'enabled', 'nat_detected': 'no', 'cts_sgt': 'disabled', 'initiator_of_sa': 'Yes', 'child_sa': {1: {'local_selectors': ['30.10.10.0/0 - 50.10.10.255/65535', '20.10.10.0/0 - 40.10.10.255/65535'], 'remote_selectors': ['172.17.2.0/0 - 172.17.2.255/65535', '172.17.2.0/0 - 172.17.3.255/65535'], 'esp_spi_in': '0x232CB82D', 'esp_spi_out': '0x30767B6E', 'ah_spi_in': '0x0', 'ah_spi_out': '0x0', 'cpi_in': '0x0', 'cpi_out': '0x0', 'child_encr': 'AES-CBC', 'keysize': 256, 'esp_hmac': 'SHA256', 'ah_hmac': 'None', 'compression': 'IPCOMP_NONE', 'mode': 'tunnel'}, 2: {'local_selectors': ['20.10.10.0/0 - 40.10.10.255/65535'], 'remote_selectors': ['50.20.20.0/0 - 60.20.20.255/65535'], 'esp_spi_in': '0x232CB82D', 'esp_spi_out': '0x30767B6E', 'ah_spi_in': '0x0', 'ah_spi_out': '0x0', 'cpi_in': '0x0', 'cpi_out': '0x0', 'child_encr': 'AES-CBC', 'keysize': 256, 'esp_hmac': 'SHA256', 'ah_hmac': 'None', 'compression': 'IPCOMP_NONE', 'mode': 'tunnel'}}}}, 'IPv6': {1: {'session_id': 5, 'status': 'UP-ACTIVE', 'ike_count': 1, 'child_count': 1, 'tunnel_id': 1, 'local_ip': '1.1.1::1', 'local_port': 500, 'remote_ip': '1.1.1::2', 'remote_port': 500, 'fvrf': 'none', 'ivrf': 'none', 'session_status': 'READY', 'encryption': 'AES-CBC', 'key_length': 256, 'prf': 'SHA256', 'hash_algo': 'SHA256', 'dh_group': 14, 'auth_sign': 'PSK', 'auth_verify': 'PSK', 'lifetime': 86400, 'activetime': 38157, 'ce_id': 1008, 'id': 3, 'local_spi': '6F86196AB2C574E5', 'remote_spi': '74AD695CF23C4806', 'local_id': '1.1.1::1', 'remote_id': '1.1.1::2', 'local_mesg_id': 2, 'remote_mesg_id': 0, 'local_next_id': 2, 'remote_next_id': 0, 'local_queued': 2, 'remote_queued': 0, 'local_window': 5, 'remote_window': 5, 'dpd_time': 0, 'dpd_retry': 0, 'fragmentation': 'no', 'dynamic_route': 'enabled', 'nat_detected': 'no', 'cts_sgt': 'disabled', 'initiator_of_sa': 'Yes', 'child_sa': {1: {'local_selectors': ['30.10.10::0/0 - 50.10.10::255/65535', '20.10.10::0/0 - 40.10.10::255/65535'], 'remote_selectors': ['172.17.2::0/0 - 172.17.2::255/65535', '172.17.2::0/0 - 172.17.3::255/65535'], 'esp_spi_in': '0x232CB82D', 'esp_spi_out': '0x30767B6E', 'ah_spi_in': '0x0', 'ah_spi_out': '0x0', 'cpi_in': '0x0', 'cpi_out': '0x0', 'child_encr': 'AES-CBC', 'keysize': 256, 'esp_hmac': 'SHA256', 'ah_hmac': 'None', 'compression': 'IPCOMP_NONE', 'mode': 'tunnel'}, 2: {'local_selectors': ['20.10.10::0/0 - 40.10.10::255/65535'], 'remote_selectors': ['50.20.20::0/0 - 60.20.20::255/65535'], 'esp_spi_in': '0x232CB82D', 'esp_spi_out': '0x30767B6E', 'ah_spi_in': '0x0', 'ah_spi_out': '0x0', 'cpi_in': '0x0', 'cpi_out': '0x0', 'child_encr': 'AES-CBC', 'keysize': 256, 'esp_hmac': 'SHA256', 'ah_hmac': 'None', 'compression': 'IPCOMP_NONE', 'mode': 'tunnel'}}}}}} |
class Solution:
def addNegabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
p1, p2 = len(arr1)-1, len(arr2)-1
carry = 0
result = []
while p1 >= 0 or p2 >= 0 or carry:
bit_sum = 0
if p1 >= 0:
bit_sum += arr1[p1]
p1 -= 1
if p2 >= 0:
bit_sum += arr2[p2]
p2 -= 1
bit_sum += carry
result.append(bit_sum % 2)
# the difference between base 2 and base -2
# The parenthese (bit_sum // 2) is absolutely necessary!
carry = - (bit_sum // 2)
# remove the leading zeros
while len(result) > 1 and result[-1] == 0:
result.pop()
return result[::-1]
| class Solution:
def add_negabinary(self, arr1: List[int], arr2: List[int]) -> List[int]:
(p1, p2) = (len(arr1) - 1, len(arr2) - 1)
carry = 0
result = []
while p1 >= 0 or p2 >= 0 or carry:
bit_sum = 0
if p1 >= 0:
bit_sum += arr1[p1]
p1 -= 1
if p2 >= 0:
bit_sum += arr2[p2]
p2 -= 1
bit_sum += carry
result.append(bit_sum % 2)
carry = -(bit_sum // 2)
while len(result) > 1 and result[-1] == 0:
result.pop()
return result[::-1] |
"""
File: anagram.py
Name: Dennis Hsu
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each word listed below:
* arm -> 3 anagrams
* contains -> 5 anagrams
* stop -> 6 anagrams
* tesla -> 10 anagrams
* spear -> 12 anagrams
"""
# Constants
FILE = 'dictionary.txt' # This is the filename of an English dictionary
EXIT = '-1' # Code to stop the loop
DATABASE = [] # Used to stored candidate words.
ALL_CHAR = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z'] # All english alphabet.
def main():
"""
Check if input is quit code.
If not, then star load dictionary and search anagram.
"""
while True:
word = input('Welcome to stanCode "Anagram Generator" (or -1 to quit)\nFind anagrams for:')
word = word.lower()
if word == '-1': # quit code
return
else:
if read_dictionary(word):
if word in DATABASE:
ans_list = [] # reset answer list when change input word.
find_anagrams(word, ans_list)
else:
print('This word not exists, pleas enter again.')
def read_dictionary(word):
global DATABASE
with open(FILE, 'r') as f:
for line in f:
word_data = line.strip()
DATABASE.append(word_data) # load file.
if word in DATABASE:
trim_dictionary(word) # cut down searching range.
return True
else:
return False
def trim_dictionary(word):
global DATABASE
print('read')
char_list = [] # store character from destructed input word.
word_len = len(word)
for char in word:
char_list.append(char)
another_char = list(filter(lambda e: e not in char_list, ALL_CHAR)) # all character not inside boggle board.
for char in another_char:
DATABASE = list(filter(lambda e: char not in e, DATABASE)) # filter words which contain another_char.
DATABASE = list(filter(lambda e: len(e) >= word_len, DATABASE)) # filter words shorter than input word units.
def find_anagrams(s, ans_list):
"""
:param ans_list: (list) used to store anagram words.
:param s: (string) resource word input from user.
"""
find_anagrams_helper(s, '', ans_list)
print(f'{len(ans_list)} anagram:', ans_list)
def find_anagrams_helper(s, sub_s, ans_list):
"""
Do recursion until find all anagram words.
:param s: (string) resource word input from user.
:param sub_s: (string) sub_string of resource word.
:param ans_list: (list) used to store anagram words.
:return:
"""
if len(s) == len(sub_s): # base point.
if sub_s in DATABASE: # check answer.
if sub_s not in ans_list: # prevent from repeat answer.
print('Found:', sub_s)
print('Searching...')
ans_list.append(sub_s)
pass
else:
for char in s:
if char in sub_s and sub_s.count(char) == s.count(char): # avoid to use over times of any char.
pass
else:
sub_s = sub_s + char # combine next character as sub_string.
if has_prefix(sub_s): # check whether are words start with sub_s.
find_anagrams_helper(s, sub_s, ans_list)
sub_s = sub_s[0:len(sub_s) - 1]
else: # no word start with sub_s
sub_s = sub_s[0:len(sub_s) - 1]
def has_prefix(sub_s):
"""
Test possibility of sub_s before doing recursion.
:param sub_s: sub_string of input word from its head.
:return: (boolean) whether word stars with sub_s.
"""
for word in DATABASE:
if word.startswith(sub_s):
return True
if __name__ == '__main__':
main()
| """
File: anagram.py
Name: Dennis Hsu
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each word listed below:
* arm -> 3 anagrams
* contains -> 5 anagrams
* stop -> 6 anagrams
* tesla -> 10 anagrams
* spear -> 12 anagrams
"""
file = 'dictionary.txt'
exit = '-1'
database = []
all_char = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
def main():
"""
Check if input is quit code.
If not, then star load dictionary and search anagram.
"""
while True:
word = input('Welcome to stanCode "Anagram Generator" (or -1 to quit)\nFind anagrams for:')
word = word.lower()
if word == '-1':
return
elif read_dictionary(word):
if word in DATABASE:
ans_list = []
find_anagrams(word, ans_list)
else:
print('This word not exists, pleas enter again.')
def read_dictionary(word):
global DATABASE
with open(FILE, 'r') as f:
for line in f:
word_data = line.strip()
DATABASE.append(word_data)
if word in DATABASE:
trim_dictionary(word)
return True
else:
return False
def trim_dictionary(word):
global DATABASE
print('read')
char_list = []
word_len = len(word)
for char in word:
char_list.append(char)
another_char = list(filter(lambda e: e not in char_list, ALL_CHAR))
for char in another_char:
database = list(filter(lambda e: char not in e, DATABASE))
database = list(filter(lambda e: len(e) >= word_len, DATABASE))
def find_anagrams(s, ans_list):
"""
:param ans_list: (list) used to store anagram words.
:param s: (string) resource word input from user.
"""
find_anagrams_helper(s, '', ans_list)
print(f'{len(ans_list)} anagram:', ans_list)
def find_anagrams_helper(s, sub_s, ans_list):
"""
Do recursion until find all anagram words.
:param s: (string) resource word input from user.
:param sub_s: (string) sub_string of resource word.
:param ans_list: (list) used to store anagram words.
:return:
"""
if len(s) == len(sub_s):
if sub_s in DATABASE:
if sub_s not in ans_list:
print('Found:', sub_s)
print('Searching...')
ans_list.append(sub_s)
pass
else:
for char in s:
if char in sub_s and sub_s.count(char) == s.count(char):
pass
else:
sub_s = sub_s + char
if has_prefix(sub_s):
find_anagrams_helper(s, sub_s, ans_list)
sub_s = sub_s[0:len(sub_s) - 1]
else:
sub_s = sub_s[0:len(sub_s) - 1]
def has_prefix(sub_s):
"""
Test possibility of sub_s before doing recursion.
:param sub_s: sub_string of input word from its head.
:return: (boolean) whether word stars with sub_s.
"""
for word in DATABASE:
if word.startswith(sub_s):
return True
if __name__ == '__main__':
main() |
class FourCal:
def setdata(self,first,second):
self.first=first
self.second=second
def add(self):
result=self.first+self.second
return result
def mul(self):
result=self.first*self.second
return result
def sub(self):
result=self.first-self.second
return result
def div(self):
result=self.first/self.second
return result
print("/////////////////")
calculator=FourCal()
calculator.setdata(4,2)
print(calculator.add())
print(calculator.div())
print(calculator.sub())
print(calculator.mul())
Char=str(calculator.add())
print(Char)
f=open("/git/test.txt",'w')
data=str(calculator.mul())
f.write(data)
f.close()
| class Fourcal:
def setdata(self, first, second):
self.first = first
self.second = second
def add(self):
result = self.first + self.second
return result
def mul(self):
result = self.first * self.second
return result
def sub(self):
result = self.first - self.second
return result
def div(self):
result = self.first / self.second
return result
print('/////////////////')
calculator = four_cal()
calculator.setdata(4, 2)
print(calculator.add())
print(calculator.div())
print(calculator.sub())
print(calculator.mul())
char = str(calculator.add())
print(Char)
f = open('/git/test.txt', 'w')
data = str(calculator.mul())
f.write(data)
f.close() |
# pyre-ignore-all-errors
# TODO: Change `pyre-ignore-all-errors` to `pyre-strict` on line 1, so we get
# to see all type errors in this file.
# TypeVars can also take a "bound" argument. Suppose we have a class hierachy like this:
class Pet:
name: str
def __init__(self, name: str) -> None:
self.name = name
class Dog(Pet):
pass
class Cat(Pet):
pass
# And we have a function that is supposed to operate on any subclasses of Pet:
def make_cute(pet):
original_name = pet.name
new_name = f"Cute {original_name}"
pet.name = new_name
return pet
# It's apparent that the function has the same parameter and return type, so we
# might want to use a type var.
# TODO: Try annotating the function above with a simple typevar and see what
# happens -- why do you think the type checker complains?
# TODO: Now, add a "bound" argument to your typevar like this:
# T = TypeVar("T", bound=Pet)
# This basically tells the type checker that within the function body, T is
# guaranteed to be a subclass of Pet, which makes it possible for us to access
# its `name` field within the function. Try invoking the function with an int
# or string and see what happens!
# Such trick is often useful, for example, when you use the builder pattern.
def verify_dog(dog: Dog) -> None:
...
def verify_cat(cat: Cat) -> None:
...
def test() -> None:
verify_dog(make_cute(Dog("Fido")))
verify_cat(make_cute(Dog("Fido")))
| class Pet:
name: str
def __init__(self, name: str) -> None:
self.name = name
class Dog(Pet):
pass
class Cat(Pet):
pass
def make_cute(pet):
original_name = pet.name
new_name = f'Cute {original_name}'
pet.name = new_name
return pet
def verify_dog(dog: Dog) -> None:
...
def verify_cat(cat: Cat) -> None:
...
def test() -> None:
verify_dog(make_cute(dog('Fido')))
verify_cat(make_cute(dog('Fido'))) |
def part_1():
file = open('input.txt', 'r')
highest_id = 0
for lineWithOptionNewLine in file:
line = lineWithOptionNewLine.strip('\n')
left = 0
right = 127
for letter in line[:-3]:
mid = (left + right) // 2
if letter == "F":
right = mid
else:
left = mid + 1
row = left
left = 0
right = 7
for letter in line[-3:]:
mid = (left + right) // 2
if letter == "L":
right = mid
else:
left = mid + 1
col = left
id = row * 8 + col
highest_id = max(highest_id, id)
return highest_id
print(part_1()) | def part_1():
file = open('input.txt', 'r')
highest_id = 0
for line_with_option_new_line in file:
line = lineWithOptionNewLine.strip('\n')
left = 0
right = 127
for letter in line[:-3]:
mid = (left + right) // 2
if letter == 'F':
right = mid
else:
left = mid + 1
row = left
left = 0
right = 7
for letter in line[-3:]:
mid = (left + right) // 2
if letter == 'L':
right = mid
else:
left = mid + 1
col = left
id = row * 8 + col
highest_id = max(highest_id, id)
return highest_id
print(part_1()) |
"""Add custom options to py.test."""
def pytest_addoption(parser):
"""Add option to recreate tox environments."""
parser.addoption(
"--tox-recreate",
action="store_true",
default=False,
help="Recreate the tox environments for click and toil modes.",
)
parser.addoption(
"--tox-develop",
action="store_true",
default=False,
help="Run tox with --develop for click and toil modes (tests will run "
"much faster!)."
)
parser.addoption(
"--tox-pytest-args",
default=None,
type=str,
help="Parameters to be passed to pytest inside tox "
"(e.g. -s /tests/test_commands)."
)
parser.addoption(
"--test-container",
action="store_true",
default=False,
help="Run tox inside the project container."
)
| """Add custom options to py.test."""
def pytest_addoption(parser):
"""Add option to recreate tox environments."""
parser.addoption('--tox-recreate', action='store_true', default=False, help='Recreate the tox environments for click and toil modes.')
parser.addoption('--tox-develop', action='store_true', default=False, help='Run tox with --develop for click and toil modes (tests will run much faster!).')
parser.addoption('--tox-pytest-args', default=None, type=str, help='Parameters to be passed to pytest inside tox (e.g. -s /tests/test_commands).')
parser.addoption('--test-container', action='store_true', default=False, help='Run tox inside the project container.') |
"""
Given two strings X and Y, print the shortest string that has both X and Y as subsequences.
If multiple shortest supersequence exists, print any one of them.
Examples:
Input: X = "AGGTAB", Y = "GXTXAYB"
Output: "AGXGTXAYB" OR "AGGXTXAYB"
OR Any string that represents shortest
supersequence of X and Y
Input: X = "HELLO", Y = "GEEK"
Output: "GEHEKLLO" OR "GHEEKLLO"
OR Any string that represents shortest
supersequence of X and Y
"""
def printSCS(x, y):
n, m = len(x), len(y)
dp = [[0 for _ in range(m+1)] for _ in range(n+1)]
for i in range(1, n+1):
for j in range(1, m+1):
if x[i-1] == y[j-1]:
dp[i][j] = 1 + dp[i-1][j-1]
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
scs = ""
while n > 0 and m > 0:
if x[n-1] == y[m-1]:
scs = x[n-1] + scs
n -= 1
m -= 1
else:
if dp[n-1][m] > dp[n][m-1]:
scs = x[n-1] + scs
n -= 1
else:
scs = y[m-1] + scs
m -= 1
# print(scs)
while n > 0:
scs = x[n-1] + scs
n -= 1
while m > 0:
scs = y[m-1] + scs
m -= 1
return scs
if __name__ == "__main__":
print(printSCS("cab", "abac"))
print(printSCS("AGGTAB", "GXTXAYB"))
print(printSCS("HELLO", "GEEK")) | """
Given two strings X and Y, print the shortest string that has both X and Y as subsequences.
If multiple shortest supersequence exists, print any one of them.
Examples:
Input: X = "AGGTAB", Y = "GXTXAYB"
Output: "AGXGTXAYB" OR "AGGXTXAYB"
OR Any string that represents shortest
supersequence of X and Y
Input: X = "HELLO", Y = "GEEK"
Output: "GEHEKLLO" OR "GHEEKLLO"
OR Any string that represents shortest
supersequence of X and Y
"""
def print_scs(x, y):
(n, m) = (len(x), len(y))
dp = [[0 for _ in range(m + 1)] for _ in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
if x[i - 1] == y[j - 1]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
scs = ''
while n > 0 and m > 0:
if x[n - 1] == y[m - 1]:
scs = x[n - 1] + scs
n -= 1
m -= 1
elif dp[n - 1][m] > dp[n][m - 1]:
scs = x[n - 1] + scs
n -= 1
else:
scs = y[m - 1] + scs
m -= 1
while n > 0:
scs = x[n - 1] + scs
n -= 1
while m > 0:
scs = y[m - 1] + scs
m -= 1
return scs
if __name__ == '__main__':
print(print_scs('cab', 'abac'))
print(print_scs('AGGTAB', 'GXTXAYB'))
print(print_scs('HELLO', 'GEEK')) |
fac_no_faction = 0
fac_commoners = 1
fac_outlaws = 2
fac_neutral = 3
fac_player_faction = 4
fac_player_supporters_faction = 5
fac_britain = 6
fac_france = 7
fac_prussia = 8
fac_russia = 9
fac_austria = 10
fac_kingdoms_end = 11
fac_kingdom_6 = 12
fac_kingdom_7 = 13
fac_kingdom_8 = 14
fac_kingdom_9 = 15
fac_kingdom_10 = 16
fac_british_ranks = 17
fac_french_ranks = 18
fac_prussian_ranks = 19
fac_russian_ranks = 20
fac_austrian_ranks = 21
| fac_no_faction = 0
fac_commoners = 1
fac_outlaws = 2
fac_neutral = 3
fac_player_faction = 4
fac_player_supporters_faction = 5
fac_britain = 6
fac_france = 7
fac_prussia = 8
fac_russia = 9
fac_austria = 10
fac_kingdoms_end = 11
fac_kingdom_6 = 12
fac_kingdom_7 = 13
fac_kingdom_8 = 14
fac_kingdom_9 = 15
fac_kingdom_10 = 16
fac_british_ranks = 17
fac_french_ranks = 18
fac_prussian_ranks = 19
fac_russian_ranks = 20
fac_austrian_ranks = 21 |
# -*- coding: utf-8 -*-
def main():
one = plus(2,3)
print("Hello Python!:"&str(one))
def plus(x,y):
return x+y
if __name__ == "__main__":
main()
| def main():
one = plus(2, 3)
print('Hello Python!:' & str(one))
def plus(x, y):
return x + y
if __name__ == '__main__':
main() |
pkgname = "evince"
pkgver = "42.1"
pkgrel = 0
build_style = "meson"
# dvi needs kpathsea, which is in texlive
# does anyone actually need dvi?
configure_args = [
"-Dintrospection=true", "-Dgtk_doc=false",
"-Dcomics=enabled", "-Dps=enabled", "-Ddvi=disabled",
]
hostmakedepends = [
"meson", "pkgconf", "gobject-introspection", "glib-devel", "itstool",
"gettext-tiny", "perl-xml-parser", "adwaita-icon-theme",
]
makedepends = [
"gtk+3-devel", "libglib-devel", "libhandy-devel", "nautilus-devel",
"dbus-devel", "libsecret-devel", "gstreamer-devel", "libspectre-devel",
"libarchive-devel", "libpoppler-glib-devel", "gst-plugins-base-devel",
"gsettings-desktop-schemas-devel", "libtiff-devel", "libgxps-devel",
"gspell-devel", "djvulibre-devel", "adwaita-icon-theme",
]
depends = ["hicolor-icon-theme"]
pkgdesc = "GNOME document viewer"
maintainer = "q66 <q66@chimera-linux.org>"
license = "GPL-2.0-or-later"
url = "https://wiki.gnome.org/Apps/Evince"
source = f"$(GNOME_SITE)/{pkgname}/{pkgver[:-2]}/{pkgname}-{pkgver}.tar.xz"
sha256 = "b24767bb3d5103b4e35b0e15cf033dbe2488f88700cdd882d22a43adeec2e80a"
@subpackage("evince-libs")
def _libs(self):
return self.default_libs()
@subpackage("evince-devel")
def _devel(self):
return self.default_devel()
| pkgname = 'evince'
pkgver = '42.1'
pkgrel = 0
build_style = 'meson'
configure_args = ['-Dintrospection=true', '-Dgtk_doc=false', '-Dcomics=enabled', '-Dps=enabled', '-Ddvi=disabled']
hostmakedepends = ['meson', 'pkgconf', 'gobject-introspection', 'glib-devel', 'itstool', 'gettext-tiny', 'perl-xml-parser', 'adwaita-icon-theme']
makedepends = ['gtk+3-devel', 'libglib-devel', 'libhandy-devel', 'nautilus-devel', 'dbus-devel', 'libsecret-devel', 'gstreamer-devel', 'libspectre-devel', 'libarchive-devel', 'libpoppler-glib-devel', 'gst-plugins-base-devel', 'gsettings-desktop-schemas-devel', 'libtiff-devel', 'libgxps-devel', 'gspell-devel', 'djvulibre-devel', 'adwaita-icon-theme']
depends = ['hicolor-icon-theme']
pkgdesc = 'GNOME document viewer'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'GPL-2.0-or-later'
url = 'https://wiki.gnome.org/Apps/Evince'
source = f'$(GNOME_SITE)/{pkgname}/{pkgver[:-2]}/{pkgname}-{pkgver}.tar.xz'
sha256 = 'b24767bb3d5103b4e35b0e15cf033dbe2488f88700cdd882d22a43adeec2e80a'
@subpackage('evince-libs')
def _libs(self):
return self.default_libs()
@subpackage('evince-devel')
def _devel(self):
return self.default_devel() |
def gcd(a, b):
if (b == 0):
return a
else:
return gcd(b, a%b)
T = input('')
for _ in xrange(T):
b,a = map(int, raw_input('').split())
print(gcd(a, b))
| def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
t = input('')
for _ in xrange(T):
(b, a) = map(int, raw_input('').split())
print(gcd(a, b)) |
# -*- coding: utf-8 -*-
#
# Copyright 2019 SoloKeys Developers
#
# Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
# http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
# http://opensource.org/licenses/MIT>, at your option. This file may not be
# copied, modified, or distributed except according to those terms.
def to_websafe(data):
data = data.replace("+", "-")
data = data.replace("/", "_")
data = data.replace("=", "")
return data
def from_websafe(data):
data = data.replace("-", "+")
data = data.replace("_", "/")
return data + "=="[: (3 * len(data)) % 4]
| def to_websafe(data):
data = data.replace('+', '-')
data = data.replace('/', '_')
data = data.replace('=', '')
return data
def from_websafe(data):
data = data.replace('-', '+')
data = data.replace('_', '/')
return data + '=='[:3 * len(data) % 4] |
def numberOfSubarrays(nums, k: int):
odd_indices = []
for idx, x in enumerate(nums):
if x % 2 == 1:
odd_indices.append(idx)
count_over_odds = 0
for start in range(len(odd_indices) - k + 1):
valid_slice = odd_indices[start: start + k]
count = 1
head = 1
tail = 1
if start != 0:
head = odd_indices[start] - odd_indices[start - 1]
else:
head += odd_indices[0]
if start + k != len(odd_indices):
tail = odd_indices[start + k] - odd_indices[start + k - 1]
else:
tail += (len(nums) - odd_indices[-1] - 1)
count *= head
count *= tail
count_over_odds += count
return count_over_odds
if __name__ == "__main__":
print(numberOfSubarrays([45627,50891,94884,11286,35337,46414,62029,20247,72789,89158,54203,79628,25920,16832,47469,80909], 1))
| def number_of_subarrays(nums, k: int):
odd_indices = []
for (idx, x) in enumerate(nums):
if x % 2 == 1:
odd_indices.append(idx)
count_over_odds = 0
for start in range(len(odd_indices) - k + 1):
valid_slice = odd_indices[start:start + k]
count = 1
head = 1
tail = 1
if start != 0:
head = odd_indices[start] - odd_indices[start - 1]
else:
head += odd_indices[0]
if start + k != len(odd_indices):
tail = odd_indices[start + k] - odd_indices[start + k - 1]
else:
tail += len(nums) - odd_indices[-1] - 1
count *= head
count *= tail
count_over_odds += count
return count_over_odds
if __name__ == '__main__':
print(number_of_subarrays([45627, 50891, 94884, 11286, 35337, 46414, 62029, 20247, 72789, 89158, 54203, 79628, 25920, 16832, 47469, 80909], 1)) |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
def share_price(invested: int, changes: list) -> str:
"""
Calculates, and returns the current price of your share,
given the following two arguments:
1. invested(number), the amount of money you initially
invested in the given share
2. changes(array of numbers), contains your shares daily
movement percentages
The returned number, should be in string format, and it's
precision should be fixed at 2 decimal numbers.
:param invested:
:param changes:
:return:
"""
for c in changes:
invested = invested + ((invested * c) / 100.00)
return '{:.2f}'.format(invested)
| def share_price(invested: int, changes: list) -> str:
"""
Calculates, and returns the current price of your share,
given the following two arguments:
1. invested(number), the amount of money you initially
invested in the given share
2. changes(array of numbers), contains your shares daily
movement percentages
The returned number, should be in string format, and it's
precision should be fixed at 2 decimal numbers.
:param invested:
:param changes:
:return:
"""
for c in changes:
invested = invested + invested * c / 100.0
return '{:.2f}'.format(invested) |
SAMPLE_INPUT_FILE = "sample_input_day_20_aoc21.txt"
PUZZLE_INPUT_FILE = "puzzle_input_day_20_aoc21.txt"
NUM_ENHANCEMENTS = 50
def parse_input(dir_file: str) -> tuple[str, list]:
"""
Args:
dir_file (str): location of .txt file to pull data from
Returns:
"""
alg, im = '', []
with open(dir_file, "r") as file:
lines = file.read().splitlines()
alg = lines[0]
im = lines[2:]
return alg, im
def convert_algorithm_to_bool(input_algorithm: str) -> str:
output_algorithm = ""
for character in input_algorithm:
if character == "#":
output_algorithm += "1"
elif character == ".":
output_algorithm += "0"
return output_algorithm
def convert_image_to_bool(input_image: list) -> list:
output_image = [[None] * len(input_image) for i in range(len(input_image[0]))]
for index_row, row in enumerate(image):
for index_col, col in enumerate(row):
if col == "#":
output_image[index_row][index_col] = 1
elif col == ".":
output_image[index_row][index_col] = 0
return output_image
def binary_to_int(binary_value: str) -> int:
return int(binary_value, 2)
def new_pixel_value(pixel_value: int, enhance_algorithm: str) -> int:
return int(enhance_algorithm[pixel_value])
def surrounding_pixels_binary_value(arr: list, x: int, y: int) -> str:
pixel_binary_value = ''
indices = [(x-1, y-1), (x-1, y), (x-1, y+1),
(x, y-1), (x, y), (x, y+1),
(x+1, y-1), (x+1, y), (x+1, y+1)]
for (x_i, y_i) in indices:
if 0 <= x_i < len(arr) and 0 <= y_i < len(arr[x]):
pixel_binary_value += str(arr[x_i][y_i])
else:
# if position isn't valid, use value of x, y coordinate
pixel_binary_value += str(arr[x][y])
return pixel_binary_value
def create_canvas(input_image: list, num_enhance: int) -> list:
canvas = [[0] * (len(input_image) + 2 * num_enhance) for i in range((len(input_image[0]) + 2 * num_enhance))]
for index_row, row in enumerate(canvas):
for index_col, col in enumerate(canvas):
if num_enhance <= index_row < len(canvas) - num_enhance and num_enhance <= index_col < len(canvas[0]) - num_enhance:
canvas[index_row][index_col] = input_image[index_row - num_enhance][index_col - num_enhance]
return canvas
def enhance_image(enhance_algorithm: str, input_image: list) -> list:
output_image = [[0] * len(input_image) for i in range(len(input_image[0]))]
for index_row, row in enumerate(input_image):
for index_col, col in enumerate(row):
output_image[index_row][index_col] = new_pixel_value(binary_to_int((surrounding_pixels_binary_value(input_image, index_row, index_col))), enhance_algorithm)
return output_image
def count_light_pixels(input_image: list) -> int:
return sum(sum(input_image, []))
algorithm, image = parse_input(PUZZLE_INPUT_FILE)
algorithm = convert_algorithm_to_bool(algorithm)
image = convert_image_to_bool(image)
image = create_canvas(image, NUM_ENHANCEMENTS)
'''
for i in image:
print(i)
print()
'''
for i in range(NUM_ENHANCEMENTS):
image = enhance_image(algorithm, image)
'''
for j in image:
print(j)
print()
print(count_light_pixels(image))
print()
'''
print(count_light_pixels(image)) | sample_input_file = 'sample_input_day_20_aoc21.txt'
puzzle_input_file = 'puzzle_input_day_20_aoc21.txt'
num_enhancements = 50
def parse_input(dir_file: str) -> tuple[str, list]:
"""
Args:
dir_file (str): location of .txt file to pull data from
Returns:
"""
(alg, im) = ('', [])
with open(dir_file, 'r') as file:
lines = file.read().splitlines()
alg = lines[0]
im = lines[2:]
return (alg, im)
def convert_algorithm_to_bool(input_algorithm: str) -> str:
output_algorithm = ''
for character in input_algorithm:
if character == '#':
output_algorithm += '1'
elif character == '.':
output_algorithm += '0'
return output_algorithm
def convert_image_to_bool(input_image: list) -> list:
output_image = [[None] * len(input_image) for i in range(len(input_image[0]))]
for (index_row, row) in enumerate(image):
for (index_col, col) in enumerate(row):
if col == '#':
output_image[index_row][index_col] = 1
elif col == '.':
output_image[index_row][index_col] = 0
return output_image
def binary_to_int(binary_value: str) -> int:
return int(binary_value, 2)
def new_pixel_value(pixel_value: int, enhance_algorithm: str) -> int:
return int(enhance_algorithm[pixel_value])
def surrounding_pixels_binary_value(arr: list, x: int, y: int) -> str:
pixel_binary_value = ''
indices = [(x - 1, y - 1), (x - 1, y), (x - 1, y + 1), (x, y - 1), (x, y), (x, y + 1), (x + 1, y - 1), (x + 1, y), (x + 1, y + 1)]
for (x_i, y_i) in indices:
if 0 <= x_i < len(arr) and 0 <= y_i < len(arr[x]):
pixel_binary_value += str(arr[x_i][y_i])
else:
pixel_binary_value += str(arr[x][y])
return pixel_binary_value
def create_canvas(input_image: list, num_enhance: int) -> list:
canvas = [[0] * (len(input_image) + 2 * num_enhance) for i in range(len(input_image[0]) + 2 * num_enhance)]
for (index_row, row) in enumerate(canvas):
for (index_col, col) in enumerate(canvas):
if num_enhance <= index_row < len(canvas) - num_enhance and num_enhance <= index_col < len(canvas[0]) - num_enhance:
canvas[index_row][index_col] = input_image[index_row - num_enhance][index_col - num_enhance]
return canvas
def enhance_image(enhance_algorithm: str, input_image: list) -> list:
output_image = [[0] * len(input_image) for i in range(len(input_image[0]))]
for (index_row, row) in enumerate(input_image):
for (index_col, col) in enumerate(row):
output_image[index_row][index_col] = new_pixel_value(binary_to_int(surrounding_pixels_binary_value(input_image, index_row, index_col)), enhance_algorithm)
return output_image
def count_light_pixels(input_image: list) -> int:
return sum(sum(input_image, []))
(algorithm, image) = parse_input(PUZZLE_INPUT_FILE)
algorithm = convert_algorithm_to_bool(algorithm)
image = convert_image_to_bool(image)
image = create_canvas(image, NUM_ENHANCEMENTS)
'\nfor i in image:\n print(i)\nprint()\n'
for i in range(NUM_ENHANCEMENTS):
image = enhance_image(algorithm, image)
'\n for j in image:\n print(j)\n \n print()\n print(count_light_pixels(image))\n print()\n'
print(count_light_pixels(image)) |
#Question Link <https://leetcode.com/problems/trapping-rain-water/>
class Solution:
def trap(self, height):
left, right = 0, len(height) - 1
ans = left_max = right_max = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
ans += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
ans += right_max - height[right]
right -= 1
return ans | class Solution:
def trap(self, height):
(left, right) = (0, len(height) - 1)
ans = left_max = right_max = 0
while left < right:
if height[left] < height[right]:
left_max = max(left_max, height[left])
ans += left_max - height[left]
left += 1
else:
right_max = max(right_max, height[right])
ans += right_max - height[right]
right -= 1
return ans |
"""
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a=[*open(0)][1].split()
print(max(a.count(x)for x in{*a})) | """
*
* Author: Juarez Paulino(coderemite)
* Email: juarez.paulino@gmail.com
*
"""
a = [*open(0)][1].split()
print(max((a.count(x) for x in {*a}))) |
# Project Euler #21: Amicable numbers
def sum_of_divisors(n):
sd = 1 # 1 is a divisors1
i = 2
i2 = i * i
while i2 <= n:
if n % i == 0:
sd += i + n // i
if i2 == n:
sd -= i
i += 1
i2 = i * i
return sd
print(sum_of_divisors(220))
print(sum_of_divisors(284))
def main():
N = 10000 # project euler
N = 300 # numsed testing
i = 2
s = 0
while i <= N:
j = sum_of_divisors(i)
if j < i:
pass
elif j == i:
pass
else:
k = sum_of_divisors(j)
if i == k:
s += i + j
i += 1
print(s)
main() | def sum_of_divisors(n):
sd = 1
i = 2
i2 = i * i
while i2 <= n:
if n % i == 0:
sd += i + n // i
if i2 == n:
sd -= i
i += 1
i2 = i * i
return sd
print(sum_of_divisors(220))
print(sum_of_divisors(284))
def main():
n = 10000
n = 300
i = 2
s = 0
while i <= N:
j = sum_of_divisors(i)
if j < i:
pass
elif j == i:
pass
else:
k = sum_of_divisors(j)
if i == k:
s += i + j
i += 1
print(s)
main() |
#!/usr/bin/env python3
#This program will write Hello World !
print("Hello World!")
| print('Hello World!') |
#!/usr/bin/python3
# -*- coding: utf8 -*-
class Round:
def __init__(self, x1: int, y1: int, x2: int, y2: int, context, **kwargs):
"""
This widget allows you to create circles or ovals
:param x1: int
:param y1: int
:param x2: int
:param y2: int
:param context: => context tkinter (here canvas)
:param kwargs: Can be composed of (all optional) :{
"square_fill": color of square (str ex:"red" or color hex ex:"#FF0000")
"fill": color of round (str ex:"red" or color hex ex:"#FF0000")
"width": frame width (int)
"fill_mouse": color of the circle if the mouse hovers it
(str ex:"red" or color hex ex:"#FF0000")
"square_fill_mouse": color of the square if the mouse hovers it
(str ex:"red" or color hex ex:"#FF0000")
"command": couple of command action and effect (action, effet) or
(action, effet, action, effet, etc..) ex:
("<Button-1>", "self.quit_gui")
}
"""
# Initializes mandatory attributes
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.context = context
# Init optional attributes
self.square_fill = kwargs.get("square_fill", None)
self.fill = kwargs.get("fill", "grey")
self.width = kwargs.get("width", 1)
self.fill_mouse = kwargs.get("fill_mouse", self.fill)
self.square_fill_mouse = kwargs.get("square_fill_mouse", self.square_fill)
# Init command
command = kwargs.get("command", None)
self.command = {}
if command is not None:
index = 0
count = int(len(command) / 2)
if count == 1:
c = command[index + 1]
self.command[command[index]] = c
else:
for i in range(count):
a = command[index + 1]
self.command[command[index]] = a
index += 2
# Init other attribut
self.active_focus = False
self.item_tk = []
self.x = 0
self.y = 0
self.item_name = "round"
def draw(self):
if len(self.item_tk) > 0:
for item in self.item_tk:
self.context.delete(item)
self.item_tk = []
if self.square_fill is not None:
item = self.context.create_rectangle(
self.x1,
self.y1,
self.x2,
self.y2,
fill=self.square_fill,
width=self.width,
)
self.item_tk.append(item)
item = self.context.create_oval(
self.x1, self.y1, self.x2, self.y2, fill=self.fill, width=self.width
)
self.item_tk.append(item)
def draw_focus(self):
if self.square_fill is not None or self.fill_mouse is not None:
if len(self.item_tk) > 0:
for item in self.item_tk:
self.context.delete(item)
self.item_tk = []
if self.square_fill is not None:
item = self.context.create_rectangle(
self.x1,
self.y1,
self.x2,
self.y2,
fill=self.square_fill_mouse,
width=self.width,
)
self.item_tk.append(item)
if self.fill_mouse is not None:
item = self.context.create_oval(
self.x1,
self.y1,
self.x2,
self.y2,
fill=self.fill_mouse,
width=self.width,
)
self.item_tk.append(item)
def update(self, **kwargs):
self.fill = kwargs.get("fill", self.fill)
self.fill_mouse = kwargs.get("fill_mouse", self.fill)
if self.x1 < self.x < self.x2 and self.y1 < self.y < self.y2:
self.draw_focus()
else:
self.draw()
def motion(self, x, y):
self.x = x
self.y = y
if self.x1 < x < self.x2 and self.y1 < y < self.y2:
if not self.active_focus:
self.draw_focus()
self.active_focus = True
else:
if self.active_focus:
self.draw()
self.active_focus = False
def commande(self, x, y, action):
if action in self.command:
if self.x1 < x < self.x2 and self.y1 < y < self.y2:
self.command[action]()
| class Round:
def __init__(self, x1: int, y1: int, x2: int, y2: int, context, **kwargs):
"""
This widget allows you to create circles or ovals
:param x1: int
:param y1: int
:param x2: int
:param y2: int
:param context: => context tkinter (here canvas)
:param kwargs: Can be composed of (all optional) :{
"square_fill": color of square (str ex:"red" or color hex ex:"#FF0000")
"fill": color of round (str ex:"red" or color hex ex:"#FF0000")
"width": frame width (int)
"fill_mouse": color of the circle if the mouse hovers it
(str ex:"red" or color hex ex:"#FF0000")
"square_fill_mouse": color of the square if the mouse hovers it
(str ex:"red" or color hex ex:"#FF0000")
"command": couple of command action and effect (action, effet) or
(action, effet, action, effet, etc..) ex:
("<Button-1>", "self.quit_gui")
}
"""
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.context = context
self.square_fill = kwargs.get('square_fill', None)
self.fill = kwargs.get('fill', 'grey')
self.width = kwargs.get('width', 1)
self.fill_mouse = kwargs.get('fill_mouse', self.fill)
self.square_fill_mouse = kwargs.get('square_fill_mouse', self.square_fill)
command = kwargs.get('command', None)
self.command = {}
if command is not None:
index = 0
count = int(len(command) / 2)
if count == 1:
c = command[index + 1]
self.command[command[index]] = c
else:
for i in range(count):
a = command[index + 1]
self.command[command[index]] = a
index += 2
self.active_focus = False
self.item_tk = []
self.x = 0
self.y = 0
self.item_name = 'round'
def draw(self):
if len(self.item_tk) > 0:
for item in self.item_tk:
self.context.delete(item)
self.item_tk = []
if self.square_fill is not None:
item = self.context.create_rectangle(self.x1, self.y1, self.x2, self.y2, fill=self.square_fill, width=self.width)
self.item_tk.append(item)
item = self.context.create_oval(self.x1, self.y1, self.x2, self.y2, fill=self.fill, width=self.width)
self.item_tk.append(item)
def draw_focus(self):
if self.square_fill is not None or self.fill_mouse is not None:
if len(self.item_tk) > 0:
for item in self.item_tk:
self.context.delete(item)
self.item_tk = []
if self.square_fill is not None:
item = self.context.create_rectangle(self.x1, self.y1, self.x2, self.y2, fill=self.square_fill_mouse, width=self.width)
self.item_tk.append(item)
if self.fill_mouse is not None:
item = self.context.create_oval(self.x1, self.y1, self.x2, self.y2, fill=self.fill_mouse, width=self.width)
self.item_tk.append(item)
def update(self, **kwargs):
self.fill = kwargs.get('fill', self.fill)
self.fill_mouse = kwargs.get('fill_mouse', self.fill)
if self.x1 < self.x < self.x2 and self.y1 < self.y < self.y2:
self.draw_focus()
else:
self.draw()
def motion(self, x, y):
self.x = x
self.y = y
if self.x1 < x < self.x2 and self.y1 < y < self.y2:
if not self.active_focus:
self.draw_focus()
self.active_focus = True
elif self.active_focus:
self.draw()
self.active_focus = False
def commande(self, x, y, action):
if action in self.command:
if self.x1 < x < self.x2 and self.y1 < y < self.y2:
self.command[action]() |
archivo = open("DDSIVClases/archivo.txt", "r")
# imprime cada linea del archivo txt
for linea in archivo:
print(linea)
#linea2 = archivo.readline(2)
#print(linea2)
lineas = archivo.readline()
| archivo = open('DDSIVClases/archivo.txt', 'r')
for linea in archivo:
print(linea)
lineas = archivo.readline() |
query = """
SELECT L_SHIPMODE,
sum(CASE WHEN O_ORDERPRIORITY='1-URGENT'
OR O_ORDERPRIORITY='2-HIGH'
THEN 1 ELSE 0 END) AS HIGH_LINE_COUNT,
sum(CASE WHEN O_ORDERPRIORITY <> '1-URGENT'
AND O_ORDERPRIORITY <> '2-HIGH'
THEN 1 ELSE 0 END) AS LOW_LINE_COUNT
FROM orders,
lineitem
WHERE O_ORDERKEY = L_ORDERKEY
AND L_SHIPMODE IN ('MAIL', 'SHIP')
AND L_COMMITDATE < L_RECEIPTDATE
AND L_SHIPDATE < L_COMMITDATE
AND L_RECEIPTDATE >= '1994-01-01'
AND L_RECEIPTDATE < '1995-01-01'
GROUP BY L_SHIPMODE
ORDER BY L_SHIPMODE
"""
| query = "\nSELECT\tL_SHIPMODE,\n\tsum(CASE WHEN O_ORDERPRIORITY='1-URGENT'\n\tOR O_ORDERPRIORITY='2-HIGH'\n\tTHEN 1 ELSE 0 END) AS HIGH_LINE_COUNT,\n\tsum(CASE WHEN O_ORDERPRIORITY <> '1-URGENT' \n\t\tAND O_ORDERPRIORITY <> '2-HIGH' \n\t\tTHEN 1 ELSE 0 END) AS LOW_LINE_COUNT\nFROM\torders,\n\tlineitem\nWHERE\tO_ORDERKEY = L_ORDERKEY\n\tAND L_SHIPMODE IN ('MAIL', 'SHIP')\n\tAND L_COMMITDATE < L_RECEIPTDATE\n\tAND L_SHIPDATE < L_COMMITDATE\n\tAND L_RECEIPTDATE >= '1994-01-01'\n\tAND L_RECEIPTDATE < '1995-01-01'\nGROUP BY\tL_SHIPMODE\nORDER BY\tL_SHIPMODE\n" |
tree_count = 0
with open("input.txt") as file_handler:
for n, line in enumerate(file_handler):
if n == 0:
continue
if len(line.strip()) == 0:
continue
charPos = n*3
if charPos > len(line.strip()):
multiples = int(charPos / len(line.strip()))
charPos = charPos - (multiples * len(line.strip()))
char = line[charPos]
if char == "#":
tree_count += 1
print(tree_count)
| tree_count = 0
with open('input.txt') as file_handler:
for (n, line) in enumerate(file_handler):
if n == 0:
continue
if len(line.strip()) == 0:
continue
char_pos = n * 3
if charPos > len(line.strip()):
multiples = int(charPos / len(line.strip()))
char_pos = charPos - multiples * len(line.strip())
char = line[charPos]
if char == '#':
tree_count += 1
print(tree_count) |
class Solution(object):
def minSwapsCouples(self, row):
"""
:type row: List[int]
:rtype: int
"""
couple_num = (len(row) + 1) / 2
error_index = []
error_num = 0
for i in range(couple_num):
i = i * 2
if row[i] < row[i + 1]:
if row[i] % 2 != 0:
error_num += 1
error_index.append(i)
continue
elif row[i] + 1 != row[i + 1]:
error_num += 1
error_index.append(i)
continue
else:
if row[i + 1] % 2 != 0:
error_num += 1
error_index.append(i)
continue
elif row[i + 1] + 1 != row[i]:
error_num += 1
error_index.append(i)
continue
group_list = []
slod_index = []
for m in range(len(error_index)):
group_size = 1
if m in slod_index:
continue
point = m
while not(((row[error_index[point]] % 2 == 0) & ((row[error_index[point]] + 1) == row[error_index[point] + 1])) | (((row[error_index[point] + 1]) % 2 == 0) & (row[error_index[point]] == (row[error_index[point] + 1] + 1)))):
if row[error_index[point]] < row[error_index[point] + 1]:
if row[error_index[point]] % 2 == 0:
target = row[error_index[point]] + 1
for i in range(0, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
else:
target = row[error_index[point]] - 1
for i in range(0, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
else:
if row[error_index[point] + 1] % 2 == 0:
target = row[error_index[point] + 1] + 1
for i in range(1, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
else:
target = row[error_index[point] + 1] - 1
for i in range(1, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
group_list.append(group_size)
sum_change = 0
for i in group_list:
sum_change += i - 1
return sum_change
| class Solution(object):
def min_swaps_couples(self, row):
"""
:type row: List[int]
:rtype: int
"""
couple_num = (len(row) + 1) / 2
error_index = []
error_num = 0
for i in range(couple_num):
i = i * 2
if row[i] < row[i + 1]:
if row[i] % 2 != 0:
error_num += 1
error_index.append(i)
continue
elif row[i] + 1 != row[i + 1]:
error_num += 1
error_index.append(i)
continue
elif row[i + 1] % 2 != 0:
error_num += 1
error_index.append(i)
continue
elif row[i + 1] + 1 != row[i]:
error_num += 1
error_index.append(i)
continue
group_list = []
slod_index = []
for m in range(len(error_index)):
group_size = 1
if m in slod_index:
continue
point = m
while not (row[error_index[point]] % 2 == 0) & (row[error_index[point]] + 1 == row[error_index[point] + 1]) | (row[error_index[point] + 1] % 2 == 0) & (row[error_index[point]] == row[error_index[point] + 1] + 1):
if row[error_index[point]] < row[error_index[point] + 1]:
if row[error_index[point]] % 2 == 0:
target = row[error_index[point]] + 1
for i in range(0, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
else:
target = row[error_index[point]] - 1
for i in range(0, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point] + 1]
row[error_index[point] + 1] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif row[error_index[point] + 1] % 2 == 0:
target = row[error_index[point] + 1] + 1
for i in range(1, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
else:
target = row[error_index[point] + 1] - 1
for i in range(1, len(error_index)):
if i in slod_index:
continue
elif i == point:
continue
if target == row[error_index[i]]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i]]
row[error_index[i]] = temp
slod_index.append(point)
point = i
group_size += 1
break
elif target == row[error_index[i] + 1]:
temp = row[error_index[point]]
row[error_index[point]] = row[error_index[i] + 1]
row[error_index[i] + 1] = temp
slod_index.append(point)
point = i
group_size += 1
break
group_list.append(group_size)
sum_change = 0
for i in group_list:
sum_change += i - 1
return sum_change |
class Solution(object):
def findMissingRanges(self, nums, lower, upper):
"""
Find missing ranges by iterating through all nums
To account for inclusivity, we add lower -1 and upper +1 to the nums array
"""
all = [lower -1] + nums + [upper + 1]
res = []
for i in range(len(all)-1):
# Find difference
diff = all[i+1] - all[i]
# Add single element
if diff == 2:
res.append(str(all[i]+1))
# Add range
if diff > 2:
bound = 1
new = str(all[i]+1) + "->" + str(all[i+1] -bound)
res.append(new)
return res
z = Solution()
nums = [0, 1, 3, 50, 75]
lower = 0
upper = 75
print(nums)
print(z.findMissingRanges(nums, lower, upper))
| class Solution(object):
def find_missing_ranges(self, nums, lower, upper):
"""
Find missing ranges by iterating through all nums
To account for inclusivity, we add lower -1 and upper +1 to the nums array
"""
all = [lower - 1] + nums + [upper + 1]
res = []
for i in range(len(all) - 1):
diff = all[i + 1] - all[i]
if diff == 2:
res.append(str(all[i] + 1))
if diff > 2:
bound = 1
new = str(all[i] + 1) + '->' + str(all[i + 1] - bound)
res.append(new)
return res
z = solution()
nums = [0, 1, 3, 50, 75]
lower = 0
upper = 75
print(nums)
print(z.findMissingRanges(nums, lower, upper)) |
"""
FIT1008 Prac 5 Task 1
@purpose reverse.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140823
@created 20140821
"""
def reverse():
"""
@purpose: To read in a size n, then input a list of size n, then prints out
in reverse order
@param: none
@complexity: O(N) where N is the size of input for list
@precondition: A valid size is entered
@postcondition: Prints out the list in reverse order
"""
try:
the_list = []
i = 0
size = 0
size = int(input("Please input the size of the list: "))
if size <= 0:
print("Please input a valid length.")
else:
the_list = [0]*size
while i < size:
the_list[i] = (input("Item: "))
i += 1
i = size - 1
while i >= 0:
print(the_list[i], end=" ")
i -= 1
except:
print("Please input a valid length.")
if __name__ == "__main__":
reverse() | """
FIT1008 Prac 5 Task 1
@purpose reverse.py
@author Loh Hao Bin 25461257, Derwinn Ee 25216384
@modified 20140823
@created 20140821
"""
def reverse():
"""
@purpose: To read in a size n, then input a list of size n, then prints out
in reverse order
@param: none
@complexity: O(N) where N is the size of input for list
@precondition: A valid size is entered
@postcondition: Prints out the list in reverse order
"""
try:
the_list = []
i = 0
size = 0
size = int(input('Please input the size of the list: '))
if size <= 0:
print('Please input a valid length.')
else:
the_list = [0] * size
while i < size:
the_list[i] = input('Item: ')
i += 1
i = size - 1
while i >= 0:
print(the_list[i], end=' ')
i -= 1
except:
print('Please input a valid length.')
if __name__ == '__main__':
reverse() |
"""
Exception definitions for kastore.
"""
class KastoreException(Exception):
"""
Parent class of all Kastore specific exceptions.
"""
class FileFormatError(KastoreException):
"""
The provided file was not in the expected format.
"""
class StoreClosedError(KastoreException):
"""
The store has been closed and cannot be accessed.
"""
class VersionTooOldError(KastoreException):
"""
The provided file is too old to be read by the current version
of kastore.
"""
def __init__(self):
super().__init__(
"File version is too old. Please upgrade using the 'kastore upgrade' "
"command line utility")
class VersionTooNewError(KastoreException):
"""
The provided file is too old to be read by the current version
of kastore.
"""
def __init__(self):
super().__init__(
"File version is too new. Please upgrade your kastore library version "
"if you wish to read this file.")
| """
Exception definitions for kastore.
"""
class Kastoreexception(Exception):
"""
Parent class of all Kastore specific exceptions.
"""
class Fileformaterror(KastoreException):
"""
The provided file was not in the expected format.
"""
class Storeclosederror(KastoreException):
"""
The store has been closed and cannot be accessed.
"""
class Versiontooolderror(KastoreException):
"""
The provided file is too old to be read by the current version
of kastore.
"""
def __init__(self):
super().__init__("File version is too old. Please upgrade using the 'kastore upgrade' command line utility")
class Versiontoonewerror(KastoreException):
"""
The provided file is too old to be read by the current version
of kastore.
"""
def __init__(self):
super().__init__('File version is too new. Please upgrade your kastore library version if you wish to read this file.') |
class subtitle:
"""
Digests a YouTube subtitle file.
"""
def __init__(self, file):
try:
f = open(file, "r")
self._file = f
except IOError:
raise Exception("Cannot open subtitle file.")
def get_all_text(self):
"""
Parses the file into a single string.
:returns: String with entire subtitle transcript
"""
text = ""
for number, line in enumerate(self._file, 1):
if(number == 2 or ((number - 2) % 3) == 0):
text = text + " " + line
return text | class Subtitle:
"""
Digests a YouTube subtitle file.
"""
def __init__(self, file):
try:
f = open(file, 'r')
self._file = f
except IOError:
raise exception('Cannot open subtitle file.')
def get_all_text(self):
"""
Parses the file into a single string.
:returns: String with entire subtitle transcript
"""
text = ''
for (number, line) in enumerate(self._file, 1):
if number == 2 or (number - 2) % 3 == 0:
text = text + ' ' + line
return text |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.