content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
''' This is a sample input, you can change it of course
but you have to follow rules of the questions '''
compressed_string = "2[1[b]10[c]]a"
def decompress(str=compressed_string):
string = ""
number_stack = []
replace_index_stack = []
bracket_index_stack = []
i = 0
while i < len(str):
if str[i] == "[":
# storing indexes in coressponding stacks
replace_index_stack.insert(0, i - len(string))
number_stack.insert(0, int(string))
bracket_index_stack.insert(0, i+1)
string = ""
elif str[i] == "]":
# updating base string with uncompressed part
temp = str[bracket_index_stack[0]:i] * number_stack[0]
str = str.replace(str[replace_index_stack[0]:i+1], temp)
# updating index to next position from decompressed part
i = replace_index_stack[0]+len(temp)
# poping the top item from stacks which is used already
number_stack.pop(0)
replace_index_stack.pop(0)
bracket_index_stack.pop(0)
string = ""
continue
else:
string += str[i]
i += 1
return str
print(decompress())
|
""" This is a sample input, you can change it of course
but you have to follow rules of the questions """
compressed_string = '2[1[b]10[c]]a'
def decompress(str=compressed_string):
string = ''
number_stack = []
replace_index_stack = []
bracket_index_stack = []
i = 0
while i < len(str):
if str[i] == '[':
replace_index_stack.insert(0, i - len(string))
number_stack.insert(0, int(string))
bracket_index_stack.insert(0, i + 1)
string = ''
elif str[i] == ']':
temp = str[bracket_index_stack[0]:i] * number_stack[0]
str = str.replace(str[replace_index_stack[0]:i + 1], temp)
i = replace_index_stack[0] + len(temp)
number_stack.pop(0)
replace_index_stack.pop(0)
bracket_index_stack.pop(0)
string = ''
continue
else:
string += str[i]
i += 1
return str
print(decompress())
|
# Problem 6 MIT Midterm #
# The function isMyNumber is used to hide a secret number (integer).
# It takes an integer guess as a parameter and compares it to the secret number.
# It returns:
# -1 if the parameter x is less than the secret number
# 0 if the parameter x is correct
# 1 if the parameter x is greater than the secret number
def isMyNumber(guess):
"""
Procedure that hides a secret number.
:param guess: integer number
:return:
-1 if guess is less than the secret number
0 if guess is equal to the secret number
1 if guess is greater than the secret number
"""
secretnum = 5
if guess == secretnum:
return 0
elif guess < secretnum:
return -1
else:
return 1
# The following function, jumpAndBackPedal, attempts to guess a secret number.
# The only way it can interact with the secret number is through the isMyNumber function explained above
# Unfortunately, the implementation given does not correctly return the secret number.
# Please fix the errors in the code such that jumpAndBackpedal correctly returns the secret number.
def jumpAndBackpedal(isMyNumber):
"""
:param isMyNumber: function that hides a secret number
:return: secret number
"""
# start guess
guess = 0
# if isMyNumber returns 0, guess is secretnumber
if isMyNumber(guess) == 0:
return guess
# if isMyNumber does not return 0, guess is not yet correct
else:
# keep guessing until right guess
foundNumber = False
while not foundNumber:
# if guess is too high, isMyNumber returns 1
# so guess needs to be decreased
if isMyNumber(guess) == 1:
guess = guess - 1
# else if guess is too low, isMyNumber returns -1
# so guess needs to be increased
elif isMyNumber(guess) == -1:
guess = guess + 1
# else if finally guess is secret number, isMyNumber returns 0
else:
# break loop with flag
foundNumber = True
return guess
# print secret number, retuned
print (jumpAndBackpedal(isMyNumber))
|
def is_my_number(guess):
"""
Procedure that hides a secret number.
:param guess: integer number
:return:
-1 if guess is less than the secret number
0 if guess is equal to the secret number
1 if guess is greater than the secret number
"""
secretnum = 5
if guess == secretnum:
return 0
elif guess < secretnum:
return -1
else:
return 1
def jump_and_backpedal(isMyNumber):
"""
:param isMyNumber: function that hides a secret number
:return: secret number
"""
guess = 0
if is_my_number(guess) == 0:
return guess
else:
found_number = False
while not foundNumber:
if is_my_number(guess) == 1:
guess = guess - 1
elif is_my_number(guess) == -1:
guess = guess + 1
else:
found_number = True
return guess
print(jump_and_backpedal(isMyNumber))
|
def add(a,b):
return a+b
def sub(a,b):
return a-b
def multiply(a,b):
return a*b
def div(a,b):
return a/b
|
def add(a, b):
return a + b
def sub(a, b):
return a - b
def multiply(a, b):
return a * b
def div(a, b):
return a / b
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def add(self, data):
if self.head is None:
self.head = Node(data)
else:
temp = self.head
self.head = Node(data)
self.head.next = temp
def reverse(self, node):
if node.next is None:
self.head = node
return
self.reverse(node.next)
temp = node.next
temp.next = node
node.next = None
def printList(self):
if self.head is None:
print("LinkedList is empty")
else:
temp = self.head
while(temp):
print(temp.data)
temp = temp.next
llist = LinkedList()
for i in range(0, 5):
llist.add(i)
llist.reverse(llist.head)
llist.printList()
|
class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def add(self, data):
if self.head is None:
self.head = node(data)
else:
temp = self.head
self.head = node(data)
self.head.next = temp
def reverse(self, node):
if node.next is None:
self.head = node
return
self.reverse(node.next)
temp = node.next
temp.next = node
node.next = None
def print_list(self):
if self.head is None:
print('LinkedList is empty')
else:
temp = self.head
while temp:
print(temp.data)
temp = temp.next
llist = linked_list()
for i in range(0, 5):
llist.add(i)
llist.reverse(llist.head)
llist.printList()
|
#!/usr/bin/python
x = int(raw_input("Ingrese el input1: "))
print(not x)
|
x = int(raw_input('Ingrese el input1: '))
print(not x)
|
'''
Visit the link : https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Hurdle%202&url=worlds%2Ftutorial_en%2Fhurdle2.json
'''
def turn_right():
turn_left()
turn_left()
turn_left()
def complete():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
while not at_goal():
complete()
|
"""
Visit the link : https://reeborg.ca/reeborg.html?lang=en&mode=python&menu=worlds%2Fmenus%2Freeborg_intro_en.json&name=Hurdle%202&url=worlds%2Ftutorial_en%2Fhurdle2.json
"""
def turn_right():
turn_left()
turn_left()
turn_left()
def complete():
move()
turn_left()
move()
turn_right()
move()
turn_right()
move()
turn_left()
while not at_goal():
complete()
|
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
DEPS = [
'bisect_tester_staging',
'chromium',
'chromium_tests',
'recipe_engine/path',
'recipe_engine/properties',
'recipe_engine/step',
]
def RunSteps(api):
api.path.c.dynamic_paths['bisect_results'] = api.path['start_dir'].join(
'bisect_results')
api.chromium.set_config('chromium')
test = api.chromium_tests.steps.BisectTestStaging()
test.pre_run(api, '')
try:
test.run(api, '')
finally:
api.step('details', [])
api.step.active_result.presentation.logs['details'] = [
'compile_targets: %r' % test.compile_targets(api),
'uses_local_devices: %r' % test.uses_local_devices,
]
def GenTests(api):
bisect_config = {
'test_type': 'perf',
'command': './tools/perf/run_benchmark -v '
'--browser=android-chromium --output-format=valueset '
'page_cycler_v2.intl_ar_fa_he',
'metric': 'warm_times/page_load_time',
'repeat_count': '2',
'max_time_minutes': '5',
'truncate_percent': '25',
'bug_id': '425582',
'gs_bucket': 'chrome-perf',
'builder_host': 'master4.golo.chromium.org',
'builder_port': '8341'
}
yield (
api.test('basic') +
api.properties(
bisect_config=bisect_config,
buildername='test_buildername',
bot_id='test_bot_id')
)
|
deps = ['bisect_tester_staging', 'chromium', 'chromium_tests', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/step']
def run_steps(api):
api.path.c.dynamic_paths['bisect_results'] = api.path['start_dir'].join('bisect_results')
api.chromium.set_config('chromium')
test = api.chromium_tests.steps.BisectTestStaging()
test.pre_run(api, '')
try:
test.run(api, '')
finally:
api.step('details', [])
api.step.active_result.presentation.logs['details'] = ['compile_targets: %r' % test.compile_targets(api), 'uses_local_devices: %r' % test.uses_local_devices]
def gen_tests(api):
bisect_config = {'test_type': 'perf', 'command': './tools/perf/run_benchmark -v --browser=android-chromium --output-format=valueset page_cycler_v2.intl_ar_fa_he', 'metric': 'warm_times/page_load_time', 'repeat_count': '2', 'max_time_minutes': '5', 'truncate_percent': '25', 'bug_id': '425582', 'gs_bucket': 'chrome-perf', 'builder_host': 'master4.golo.chromium.org', 'builder_port': '8341'}
yield (api.test('basic') + api.properties(bisect_config=bisect_config, buildername='test_buildername', bot_id='test_bot_id'))
|
"""
Problem Statement: Print Indentation Correctly
Given a string "(hello word (bye bye))"
Need to print:
(
hello
word
(
bye
bye
)
)
Language: Python
Written by: Mostofa Adib Shakib
References:
=> https://leetcode.com/discuss/interview-question/409902/Snap-or-phone-or-print-indentation-correctly
"""
def printIndentationCorrectly(s):
n = len(s)
i=0
count = 0
while i < n:
char = s[i]
if char == ' ':
i+=1
elif char == '(':
print(count * ' ' + char)
count += 1
i+=1
elif char == ')':
count -=1
print(count * ' ' + char)
i+=1
else:
j = i
while j < n and s[j] != ' ' and s[j] != ')':
j+=1
print(count * ' ' + s[i:j])
i = j
# Driver Code
testStringOne = "(hello word (bye bye))"
testStringTwo = '( (hi))'
printIndentationCorrectly(testStringOne)
printIndentationCorrectly(testStringTwo)
|
"""
Problem Statement: Print Indentation Correctly
Given a string "(hello word (bye bye))"
Need to print:
(
hello
word
(
bye
bye
)
)
Language: Python
Written by: Mostofa Adib Shakib
References:
=> https://leetcode.com/discuss/interview-question/409902/Snap-or-phone-or-print-indentation-correctly
"""
def print_indentation_correctly(s):
n = len(s)
i = 0
count = 0
while i < n:
char = s[i]
if char == ' ':
i += 1
elif char == '(':
print(count * ' ' + char)
count += 1
i += 1
elif char == ')':
count -= 1
print(count * ' ' + char)
i += 1
else:
j = i
while j < n and s[j] != ' ' and (s[j] != ')'):
j += 1
print(count * ' ' + s[i:j])
i = j
test_string_one = '(hello word (bye bye))'
test_string_two = '( (hi))'
print_indentation_correctly(testStringOne)
print_indentation_correctly(testStringTwo)
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
# $builtin-init-module$
# These values are injected by our boot process. flake8 has no knowledge about
# their definitions and will complain without these circular assignments.
_Unbound = _Unbound # noqa: F821
def _ContextVar_guard(obj):
_builtin()
def _Token_guard(obj):
_builtin()
def _builtin():
"""This function acts as a marker to `freeze_modules.py` it should never
actually be called."""
_unimplemented()
def _address(c):
_builtin()
def _anyset_check(obj):
_builtin()
def _async_generator_finalizer(obj):
_builtin()
def _async_generator_guard(obj):
_builtin()
def _async_generator_op_iter_get_state(obj):
_builtin()
def _base_exception_cause(self):
_builtin()
def _base_exception_context(self):
_builtin()
def _base_exception_set_cause(self, value):
_builtin()
def _base_exception_set_context(self, value):
_builtin()
def _base_exception_set_traceback(self, value):
_builtin()
def _base_exception_traceback(self):
_builtin()
def _bool_check(self):
"$intrinsic$"
_builtin()
def _bool_guard(self):
"$intrinsic$"
_builtin()
def _bound_method(fn, owner):
_builtin()
def _bound_method_guard(obj):
_builtin()
def _builtin_type(name):
"""Returns the builtin type with name `name`. This even works before the
type is initialized via a `class` statement and is intended to be used when
a builtin type definition requires to reference itself."""
_builtin()
def _byte_guard(obj):
_builtin()
def _bytearray_append(obj, item):
_builtin()
def _bytearray_check(obj):
"$intrinsic$"
_builtin()
def _bytearray_clear(obj):
_builtin()
def _bytearray_contains(obj, key):
_builtin()
def _bytearray_contains_byteslike(obj, key):
_builtin()
def _bytearray_copy(obj):
_builtin()
def _bytearray_delitem(self, key):
_builtin()
def _bytearray_delslice(self, start, stop, step):
_builtin()
def _bytearray_getitem(self, key):
_builtin()
def _bytearray_getslice(self, start, stop, step):
_builtin()
def _bytearray_guard(obj):
"$intrinsic$"
_builtin()
def _bytearray_join(self, iterable):
_builtin()
def _bytearray_len(self):
"$intrinsic$"
_builtin()
def _bytearray_ljust(self, width, fillbyte):
_builtin()
def _bytearray_rjust(self, width, fillbyte):
_builtin()
def _bytearray_setitem(self, key, value):
_builtin()
def _bytearray_setslice(self, start, stop, step, value):
_builtin()
def _bytes_check(obj):
"$intrinsic$"
_builtin()
def _bytes_contains(obj, key):
_builtin()
def _bytes_decode(obj, encoding):
_builtin()
def _bytes_decode_ascii(obj):
_builtin()
def _bytes_decode_utf_8(obj):
_builtin()
def _bytes_from_bytes(cls, value):
_builtin()
def _bytes_from_ints(source):
_builtin()
def _bytes_getitem(self, index):
_builtin()
def _bytes_getslice(self, start, stop, step):
_builtin()
def _bytes_guard(obj):
"$intrinsic$"
_builtin()
def _bytes_join(self, iterable):
_builtin()
def _bytes_len(self):
"$intrinsic$"
_builtin()
def _bytes_ljust(self, width, fillbyte):
_builtin()
def _bytes_maketrans(frm, to):
_builtin()
def _bytes_repeat(self, count):
_builtin()
def _bytes_replace(self, old, new, count):
_builtin()
def _bytes_split(self, sep, maxsplit):
_builtin()
def _bytes_split_whitespace(self, maxsplit):
_builtin()
def _byteslike_check(obj):
"$intrinsic$"
_builtin()
def _byteslike_compare_digest(a, b):
_builtin()
def _byteslike_count(self, sub, start, end):
_builtin()
def _byteslike_endswith(self, suffix, start, end):
_builtin()
def _byteslike_find_byteslike(self, sub, start, end):
_builtin()
def _byteslike_find_int(self, sub, start, end):
_builtin()
def _byteslike_guard(obj):
"$intrinsic$"
_builtin()
def _byteslike_rfind_byteslike(self, sub, start, end):
_builtin()
def _byteslike_rfind_int(self, sub, start, end):
_builtin()
def _byteslike_startswith(self, prefix, start, end):
_builtin()
def _caller_function():
_builtin()
def _caller_locals():
_builtin()
def _classmethod(function):
_builtin()
def _classmethod_isabstract(self):
_builtin()
def _code_check(obj):
_builtin()
def _code_guard(c):
_builtin()
def _code_new(
cls,
argcount,
posonlyargcount,
kwonlyargcount,
nlocals,
stacksize,
flags,
code,
consts,
names,
varnames,
filename,
name,
firstlineno,
lnotab,
freevars,
cellvars,
):
_builtin()
def _code_set_filename(code, filename):
_builtin()
def _complex_check(obj):
"$intrinsic$"
_builtin()
def _complex_checkexact(obj):
_builtin()
def _complex_imag(c):
_builtin()
def _complex_new(cls, imag, real):
_builtin()
def _complex_real(c):
_builtin()
def _compute_mro(type):
_builtin()
def _deque_guard(obj):
"$intrinsic$"
_builtin()
def _dict_check(obj):
"$intrinsic$"
_builtin()
def _dict_check_exact(obj):
"$intrinsic$"
_builtin()
# TODO(T56301601): Move this into a type-specific file.
def _dict_get(self, key, default=None):
_builtin()
def _dict_guard(obj):
"$intrinsic$"
_builtin()
def _dict_items_guard(self):
_builtin()
def _dict_keys_guard(self):
_builtin()
def _dict_len(self):
"$intrinsic$"
_builtin()
# TODO(T56301601): Move this into a type-specific file.
def _dict_setitem(self, key, value):
_builtin()
# TODO(T56301601): Move this into a type-specific file.
def _dict_update(self, other, kwargs):
_builtin()
def _divmod(number, divisor):
_builtin()
def _exec(code, module, implicit_globals):
_builtin()
def _float_check(obj):
"$intrinsic$"
_builtin()
def _float_check_exact(obj):
"$intrinsic$"
_builtin()
def _float_divmod(number, divisor):
_builtin()
def _float_format(
value, format_code, precision, skip_sign, add_dot_0, use_alt_formatting
):
_builtin()
def _float_guard(obj):
"$intrinsic$"
_builtin()
def _float_new_from_byteslike(cls, obj):
_builtin()
def _float_new_from_float(cls, obj):
_builtin()
def _float_new_from_str(cls, obj):
_builtin()
def _float_signbit(value):
_builtin()
def _frozenset_check(obj):
"$intrinsic$"
_builtin()
def _frozenset_guard(obj):
"$intrinsic$"
_builtin()
def _function_annotations(obj):
_builtin()
def _function_closure(obj):
_builtin()
def _function_defaults(obj):
_builtin()
def _function_globals(obj):
_builtin()
def _function_guard(obj):
"$intrinsic$"
_builtin()
def _function_kwdefaults(obj):
_builtin()
def _function_lineno(function, pc):
_builtin()
def _function_new(self, code, mod, name, defaults, closure):
_builtin()
def _function_set_annotations(obj, annotations):
_builtin()
def _function_set_defaults(obj, defaults):
_builtin()
def _function_set_kwdefaults(obj, kwdefaults):
_builtin()
def _gc():
_builtin()
def _get_asyncgen_hooks():
_builtin()
def _get_member_byte(addr):
_builtin()
def _get_member_char(addr):
_builtin()
def _get_member_double(addr):
_builtin()
def _get_member_float(addr):
_builtin()
def _get_member_int(addr):
_builtin()
def _get_member_long(addr):
_builtin()
def _get_member_pyobject(addr, name):
_builtin()
def _get_member_short(addr):
_builtin()
def _get_member_string(addr):
_builtin()
def _get_member_ubyte(addr):
_builtin()
def _get_member_uint(addr):
_builtin()
def _get_member_ulong(addr):
_builtin()
def _get_member_ushort(addr):
_builtin()
def _heap_dump(filename):
_builtin()
def _instance_dunder_dict_set(obj, dict):
_builtin()
def _instance_delattr(obj, name):
_builtin()
def _instance_getattr(obj, name):
_builtin()
def _instance_guard(obj):
_builtin()
def _instance_overflow_dict(obj):
_builtin()
def _instance_setattr(obj, name, value):
_builtin()
def _instancemethod_func(obj):
_builtin()
def _int_check(obj):
"$intrinsic$"
_builtin()
def _int_check_exact(obj):
"$intrinsic$"
_builtin()
def _int_ctor(cls, x=_Unbound, base=_Unbound):
_builtin()
def _int_ctor_obj(cls, x):
_builtin()
def _int_from_bytes(cls, bytes, byteorder_big, signed):
_builtin()
def _int_guard(obj):
"$intrinsic$"
_builtin()
def _int_new_from_byteslike(cls, x, base):
_builtin()
def _int_new_from_int(cls, value):
_builtin()
def _int_new_from_str(cls, x, base):
_builtin()
def _jit(func):
"""Compile the function's body to native code. Return the function. Useful
as a decorator:
@_jit
def foo:
pass
"""
_builtin()
def _jit_fromlist(funcs):
"""Compile a list of function objects to native code."""
for func in funcs:
_jit(func)
def _jit_fromtype(type):
_type_guard(type)
for item in type.__dict__.values():
_jit(item)
def _jit_iscompiled(func):
"""Return True if the given function is compiled and False otherwise."""
_builtin()
def _list_append(self, item):
"$intrinsic$"
_builtin()
def _list_check(obj):
"$intrinsic$"
_builtin()
def _list_check_exact(obj):
"$intrinsic$"
_builtin()
def _list_ctor(cls, iterable=()):
_builtin()
def _list_delitem(self, key):
_builtin()
def _list_delslice(self, start, stop, step):
_builtin()
def _list_extend(self, other):
_builtin()
def _list_getitem(self, key):
"$intrinsic$"
_builtin()
def _list_getslice(self, start, stop, step):
_builtin()
def _list_guard(obj):
"$intrinsic$"
_builtin()
def _list_len(self):
"$intrinsic$"
_builtin()
def _list_new(size, fill=None):
_builtin()
def _list_setitem(self, key, value):
"$intrinsic$"
_builtin()
def _list_setslice(self, start, stop, step, value):
_builtin()
def _list_sort(list):
_builtin()
def _list_sort_by_key(list):
_builtin()
def _list_swap(list, i, j):
_builtin()
def _lt(a, b):
"Same as a < b."
return a < b
def _lt_key(obj, other):
return _tuple_getitem(obj, 0) < _tuple_getitem(other, 0)
def _mappingproxy_guard(obj):
_builtin()
def _mappingproxy_mapping(obj):
_builtin()
def _mappingproxy_set_mapping(obj, mapping):
_builtin()
def _memoryview_check(obj):
_builtin()
def _memoryview_getitem(obj, key):
_builtin()
def _memoryview_getslice(self, start, stop, step):
_builtin()
def _memoryview_guard(obj):
"$intrinsic$"
_builtin()
def _memoryview_itemsize(obj):
_builtin()
def _memoryview_nbytes(self):
_builtin()
def _memoryview_setitem(self, key, value):
_builtin()
def _memoryview_setslice(self, start, stop, step, value):
_builtin()
def _memoryview_start(self):
_builtin()
def _mmap_check(obj):
_builtin()
def _module_dir(module):
_builtin()
def _module_proxy(module):
_builtin()
def _module_proxy_check(obj):
_builtin()
def _module_proxy_guard(module):
_builtin()
def _module_proxy_keys(self):
_builtin()
def _module_proxy_setitem(self, key, value):
_builtin()
def _module_proxy_values(self):
_builtin()
def _iter(self):
_builtin()
def _object_class_set(obj, name):
_builtin()
def _object_keys(self):
_builtin()
def _object_type_getattr(obj, name):
"""Looks up the named attribute on the object's type, resolving descriptors.
Behaves like _PyObject_LookupSpecial."""
_builtin()
def _object_type_hasattr(obj, name):
_builtin()
def _os_write(fd, buf):
_builtin()
def _os_error_subclass_from_errno(errno):
_builtin()
def _profiler_install(new_thread_func, call_func, return_func):
_builtin()
def _profiler_exclude(callable):
"""Call `callable` and disable opcode counting in the current thread for the
duration of the call."""
_builtin()
def _property(fget=None, fset=None, fdel=None, doc=None):
"""Has the same effect as property(), but can be used for bootstrapping."""
_builtin()
def _property_isabstract(self):
_builtin()
def _pyobject_offset(instance, offset):
_builtin()
def _range_check(obj):
"$intrinsic$"
_builtin()
def _range_guard(obj):
"$intrinsic$"
_builtin()
def _range_len(self):
_builtin()
def _readline(prompt):
_builtin()
def _repr_enter(obj):
_builtin()
def _repr_leave(obj):
_builtin()
def _seq_index(obj):
"$intrinsic$"
_builtin()
def _seq_iterable(obj):
"$intrinsic$"
_builtin()
def _seq_set_index(obj, index):
"$intrinsic$"
_builtin()
def _seq_set_iterable(obj, iterable):
"$intrinsic$"
_builtin()
def _set_check(obj):
"$intrinsic$"
_builtin()
def _set_function_flag_iterable_coroutine(code):
_builtin()
def _set_guard(obj):
"$intrinsic$"
_builtin()
def _set_len(self):
"$intrinsic$"
_builtin()
def _set_member_double(addr, value):
_builtin()
def _set_member_float(addr, value):
_builtin()
def _set_member_integral(addr, value, num_bytes):
_builtin()
def _set_member_integral_unsigned(addr, value, num_bytes):
_builtin()
def _set_member_pyobject(addr, value):
_builtin()
def _slice_check(obj):
"$intrinsic$"
_builtin()
def _slice_guard(obj):
"$intrinsic$"
_builtin()
def _slice_start(start, step, length):
_builtin()
def _staticmethod(func):
_builtin()
def _slice_start_long(start, step, length):
_builtin()
def _slice_step(step):
_builtin()
def _slice_step_long(step):
_builtin()
def _slice_stop(stop, step, length):
_builtin()
def _slice_stop_long(stop, step, length):
_builtin()
def _staticmethod_isabstract(self):
_builtin()
def _stop_iteration_ctor(cls, *args):
_builtin()
def _str_array_clear(self):
_builtin()
def _str_array_ctor(cls, source=_Unbound):
_builtin()
def _str_array_iadd(self, other):
_builtin()
def _str_center(self, width, fillchar):
_builtin()
def _str_check(obj):
"$intrinsic$"
_builtin()
def _str_check_exact(obj):
"$intrinsic$"
_builtin()
def _str_compare_digest(a, b):
_builtin()
def _str_count(self, sub, start, end):
_builtin()
def _str_ctor(cls, obj=_Unbound, encoding=_Unbound, errors=_Unbound):
"$intrinsic$"
_builtin()
def _str_ctor_obj(cls, obj):
_builtin()
def _str_encode(self, encoding):
_builtin()
def _str_encode_ascii(self):
_builtin()
def _str_endswith(self, suffix, start, end):
_builtin()
def _str_getitem(self, key):
_builtin()
def _str_getslice(self, start, stop, step):
_builtin()
def _str_guard(obj):
"$intrinsic$"
_builtin()
def _str_ischr(obj):
_builtin()
def _str_join(sep, iterable):
_builtin()
def _str_ljust(self, width, fillchar):
_builtin()
def _str_escape_non_ascii(s):
_builtin()
def _str_find(self, sub, start, end):
_builtin()
def _str_from_str(cls, value):
_builtin()
def _str_len(self):
"$intrinsic$"
_builtin()
def _str_mod_fast_path(self, other):
_builtin()
def _str_partition(self, sep):
_builtin()
def _str_replace(self, old, newstr, count):
_builtin()
def _str_rfind(self, sub, start, end):
_builtin()
def _str_rjust(self, width, fillchar):
_builtin()
def _str_rpartition(self, sep):
_builtin()
def _str_split(self, sep, maxsplit):
_builtin()
def _str_splitlines(self, keepends):
_builtin()
def _str_startswith(self, prefix, start, end):
_builtin()
def _str_translate(obj, table):
_builtin()
def _structseq_getitem(structseq, index):
_builtin()
def _structseq_new_type(name, field_names, is_heaptype=True, num_in_sequence=_Unbound):
_builtin()
def _structseq_setitem(structseq, index, value):
_builtin()
def _super(cls):
_builtin()
def _super_ctor(cls, type=_Unbound, type_or_obj=_Unbound):
_builtin()
def _traceback_frame_get(self):
_builtin()
def _traceback_lineno_get(self):
_builtin()
def _traceback_next_get(self):
_builtin()
def _traceback_next_set(self, new_next):
_builtin()
def _tuple_check(obj):
"$intrinsic$"
_builtin()
def _tuple_check_exact(obj):
"$intrinsic$"
_builtin()
def _tuple_getitem(self, index):
"$intrinsic$"
_builtin()
def _tuple_getslice(self, start, stop, step):
_builtin()
def _tuple_guard(obj):
"$intrinsic$"
_builtin()
def _tuple_len(self):
"$intrinsic$"
_builtin()
def _tuple_new(cls, old_tuple):
_builtin()
def _type(obj):
"$intrinsic$"
_builtin()
def _type_ctor(cls, obj):
_builtin()
def _type_abstractmethods_del(self):
_builtin()
def _type_abstractmethods_get(self):
_builtin()
def _type_abstractmethods_set(self, value):
_builtin()
def _type_bases_del(self):
_builtin()
def _type_bases_get(self):
_builtin()
def _type_bases_set(self, value):
_builtin()
def _type_check(obj):
"$intrinsic$"
_builtin()
def _type_check_exact(obj):
"$intrinsic$"
_builtin()
def _type_dunder_call(self, *args, **kwargs):
_builtin()
def _type_guard(obj):
"$intrinsic$"
_builtin()
def _type_issubclass(subclass, superclass):
"$intrinsic$"
_builtin()
def _type_module_get(self):
_builtin()
def _type_module_set(self, value):
_builtin()
def _type_name_get(self):
_builtin()
def _type_name_set(self, value):
_builtin()
def _type_proxy(type_obj):
_builtin()
def _type_new(cls, name, bases, dict, is_heaptype):
_builtin()
def _type_proxy_check(obj):
_builtin()
def _type_proxy_get(self, key, default):
_builtin()
def _type_proxy_guard(obj):
_builtin()
def _type_proxy_keys(self):
_builtin()
def _type_proxy_len(self):
_builtin()
def _type_proxy_values(self):
_builtin()
def _type_qualname_get(self):
_builtin()
def _type_qualname_set(self, value):
_builtin()
def _type_subclass_guard(subclass, superclass):
"$intrinsic$"
_builtin()
def _unimplemented():
"""Prints a message and a stacktrace, and stops the program execution."""
_builtin()
def _warn(message, category=None, stacklevel=1, source=None):
"""Calls warnings.warn."""
_builtin()
def _weakref_callback(self):
_builtin()
def _weakref_check(self):
"$intrinsic$"
_builtin()
def _weakref_guard(self):
"$intrinsic$"
_builtin()
def _weakref_referent(self):
_builtin()
maxunicode = maxunicode # noqa: F821
|
__unbound = _Unbound
def __context_var_guard(obj):
_builtin()
def __token_guard(obj):
_builtin()
def _builtin():
"""This function acts as a marker to `freeze_modules.py` it should never
actually be called."""
_unimplemented()
def _address(c):
_builtin()
def _anyset_check(obj):
_builtin()
def _async_generator_finalizer(obj):
_builtin()
def _async_generator_guard(obj):
_builtin()
def _async_generator_op_iter_get_state(obj):
_builtin()
def _base_exception_cause(self):
_builtin()
def _base_exception_context(self):
_builtin()
def _base_exception_set_cause(self, value):
_builtin()
def _base_exception_set_context(self, value):
_builtin()
def _base_exception_set_traceback(self, value):
_builtin()
def _base_exception_traceback(self):
_builtin()
def _bool_check(self):
"""$intrinsic$"""
_builtin()
def _bool_guard(self):
"""$intrinsic$"""
_builtin()
def _bound_method(fn, owner):
_builtin()
def _bound_method_guard(obj):
_builtin()
def _builtin_type(name):
"""Returns the builtin type with name `name`. This even works before the
type is initialized via a `class` statement and is intended to be used when
a builtin type definition requires to reference itself."""
_builtin()
def _byte_guard(obj):
_builtin()
def _bytearray_append(obj, item):
_builtin()
def _bytearray_check(obj):
"""$intrinsic$"""
_builtin()
def _bytearray_clear(obj):
_builtin()
def _bytearray_contains(obj, key):
_builtin()
def _bytearray_contains_byteslike(obj, key):
_builtin()
def _bytearray_copy(obj):
_builtin()
def _bytearray_delitem(self, key):
_builtin()
def _bytearray_delslice(self, start, stop, step):
_builtin()
def _bytearray_getitem(self, key):
_builtin()
def _bytearray_getslice(self, start, stop, step):
_builtin()
def _bytearray_guard(obj):
"""$intrinsic$"""
_builtin()
def _bytearray_join(self, iterable):
_builtin()
def _bytearray_len(self):
"""$intrinsic$"""
_builtin()
def _bytearray_ljust(self, width, fillbyte):
_builtin()
def _bytearray_rjust(self, width, fillbyte):
_builtin()
def _bytearray_setitem(self, key, value):
_builtin()
def _bytearray_setslice(self, start, stop, step, value):
_builtin()
def _bytes_check(obj):
"""$intrinsic$"""
_builtin()
def _bytes_contains(obj, key):
_builtin()
def _bytes_decode(obj, encoding):
_builtin()
def _bytes_decode_ascii(obj):
_builtin()
def _bytes_decode_utf_8(obj):
_builtin()
def _bytes_from_bytes(cls, value):
_builtin()
def _bytes_from_ints(source):
_builtin()
def _bytes_getitem(self, index):
_builtin()
def _bytes_getslice(self, start, stop, step):
_builtin()
def _bytes_guard(obj):
"""$intrinsic$"""
_builtin()
def _bytes_join(self, iterable):
_builtin()
def _bytes_len(self):
"""$intrinsic$"""
_builtin()
def _bytes_ljust(self, width, fillbyte):
_builtin()
def _bytes_maketrans(frm, to):
_builtin()
def _bytes_repeat(self, count):
_builtin()
def _bytes_replace(self, old, new, count):
_builtin()
def _bytes_split(self, sep, maxsplit):
_builtin()
def _bytes_split_whitespace(self, maxsplit):
_builtin()
def _byteslike_check(obj):
"""$intrinsic$"""
_builtin()
def _byteslike_compare_digest(a, b):
_builtin()
def _byteslike_count(self, sub, start, end):
_builtin()
def _byteslike_endswith(self, suffix, start, end):
_builtin()
def _byteslike_find_byteslike(self, sub, start, end):
_builtin()
def _byteslike_find_int(self, sub, start, end):
_builtin()
def _byteslike_guard(obj):
"""$intrinsic$"""
_builtin()
def _byteslike_rfind_byteslike(self, sub, start, end):
_builtin()
def _byteslike_rfind_int(self, sub, start, end):
_builtin()
def _byteslike_startswith(self, prefix, start, end):
_builtin()
def _caller_function():
_builtin()
def _caller_locals():
_builtin()
def _classmethod(function):
_builtin()
def _classmethod_isabstract(self):
_builtin()
def _code_check(obj):
_builtin()
def _code_guard(c):
_builtin()
def _code_new(cls, argcount, posonlyargcount, kwonlyargcount, nlocals, stacksize, flags, code, consts, names, varnames, filename, name, firstlineno, lnotab, freevars, cellvars):
_builtin()
def _code_set_filename(code, filename):
_builtin()
def _complex_check(obj):
"""$intrinsic$"""
_builtin()
def _complex_checkexact(obj):
_builtin()
def _complex_imag(c):
_builtin()
def _complex_new(cls, imag, real):
_builtin()
def _complex_real(c):
_builtin()
def _compute_mro(type):
_builtin()
def _deque_guard(obj):
"""$intrinsic$"""
_builtin()
def _dict_check(obj):
"""$intrinsic$"""
_builtin()
def _dict_check_exact(obj):
"""$intrinsic$"""
_builtin()
def _dict_get(self, key, default=None):
_builtin()
def _dict_guard(obj):
"""$intrinsic$"""
_builtin()
def _dict_items_guard(self):
_builtin()
def _dict_keys_guard(self):
_builtin()
def _dict_len(self):
"""$intrinsic$"""
_builtin()
def _dict_setitem(self, key, value):
_builtin()
def _dict_update(self, other, kwargs):
_builtin()
def _divmod(number, divisor):
_builtin()
def _exec(code, module, implicit_globals):
_builtin()
def _float_check(obj):
"""$intrinsic$"""
_builtin()
def _float_check_exact(obj):
"""$intrinsic$"""
_builtin()
def _float_divmod(number, divisor):
_builtin()
def _float_format(value, format_code, precision, skip_sign, add_dot_0, use_alt_formatting):
_builtin()
def _float_guard(obj):
"""$intrinsic$"""
_builtin()
def _float_new_from_byteslike(cls, obj):
_builtin()
def _float_new_from_float(cls, obj):
_builtin()
def _float_new_from_str(cls, obj):
_builtin()
def _float_signbit(value):
_builtin()
def _frozenset_check(obj):
"""$intrinsic$"""
_builtin()
def _frozenset_guard(obj):
"""$intrinsic$"""
_builtin()
def _function_annotations(obj):
_builtin()
def _function_closure(obj):
_builtin()
def _function_defaults(obj):
_builtin()
def _function_globals(obj):
_builtin()
def _function_guard(obj):
"""$intrinsic$"""
_builtin()
def _function_kwdefaults(obj):
_builtin()
def _function_lineno(function, pc):
_builtin()
def _function_new(self, code, mod, name, defaults, closure):
_builtin()
def _function_set_annotations(obj, annotations):
_builtin()
def _function_set_defaults(obj, defaults):
_builtin()
def _function_set_kwdefaults(obj, kwdefaults):
_builtin()
def _gc():
_builtin()
def _get_asyncgen_hooks():
_builtin()
def _get_member_byte(addr):
_builtin()
def _get_member_char(addr):
_builtin()
def _get_member_double(addr):
_builtin()
def _get_member_float(addr):
_builtin()
def _get_member_int(addr):
_builtin()
def _get_member_long(addr):
_builtin()
def _get_member_pyobject(addr, name):
_builtin()
def _get_member_short(addr):
_builtin()
def _get_member_string(addr):
_builtin()
def _get_member_ubyte(addr):
_builtin()
def _get_member_uint(addr):
_builtin()
def _get_member_ulong(addr):
_builtin()
def _get_member_ushort(addr):
_builtin()
def _heap_dump(filename):
_builtin()
def _instance_dunder_dict_set(obj, dict):
_builtin()
def _instance_delattr(obj, name):
_builtin()
def _instance_getattr(obj, name):
_builtin()
def _instance_guard(obj):
_builtin()
def _instance_overflow_dict(obj):
_builtin()
def _instance_setattr(obj, name, value):
_builtin()
def _instancemethod_func(obj):
_builtin()
def _int_check(obj):
"""$intrinsic$"""
_builtin()
def _int_check_exact(obj):
"""$intrinsic$"""
_builtin()
def _int_ctor(cls, x=_Unbound, base=_Unbound):
_builtin()
def _int_ctor_obj(cls, x):
_builtin()
def _int_from_bytes(cls, bytes, byteorder_big, signed):
_builtin()
def _int_guard(obj):
"""$intrinsic$"""
_builtin()
def _int_new_from_byteslike(cls, x, base):
_builtin()
def _int_new_from_int(cls, value):
_builtin()
def _int_new_from_str(cls, x, base):
_builtin()
def _jit(func):
"""Compile the function's body to native code. Return the function. Useful
as a decorator:
@_jit
def foo:
pass
"""
_builtin()
def _jit_fromlist(funcs):
"""Compile a list of function objects to native code."""
for func in funcs:
_jit(func)
def _jit_fromtype(type):
_type_guard(type)
for item in type.__dict__.values():
_jit(item)
def _jit_iscompiled(func):
"""Return True if the given function is compiled and False otherwise."""
_builtin()
def _list_append(self, item):
"""$intrinsic$"""
_builtin()
def _list_check(obj):
"""$intrinsic$"""
_builtin()
def _list_check_exact(obj):
"""$intrinsic$"""
_builtin()
def _list_ctor(cls, iterable=()):
_builtin()
def _list_delitem(self, key):
_builtin()
def _list_delslice(self, start, stop, step):
_builtin()
def _list_extend(self, other):
_builtin()
def _list_getitem(self, key):
"""$intrinsic$"""
_builtin()
def _list_getslice(self, start, stop, step):
_builtin()
def _list_guard(obj):
"""$intrinsic$"""
_builtin()
def _list_len(self):
"""$intrinsic$"""
_builtin()
def _list_new(size, fill=None):
_builtin()
def _list_setitem(self, key, value):
"""$intrinsic$"""
_builtin()
def _list_setslice(self, start, stop, step, value):
_builtin()
def _list_sort(list):
_builtin()
def _list_sort_by_key(list):
_builtin()
def _list_swap(list, i, j):
_builtin()
def _lt(a, b):
"""Same as a < b."""
return a < b
def _lt_key(obj, other):
return _tuple_getitem(obj, 0) < _tuple_getitem(other, 0)
def _mappingproxy_guard(obj):
_builtin()
def _mappingproxy_mapping(obj):
_builtin()
def _mappingproxy_set_mapping(obj, mapping):
_builtin()
def _memoryview_check(obj):
_builtin()
def _memoryview_getitem(obj, key):
_builtin()
def _memoryview_getslice(self, start, stop, step):
_builtin()
def _memoryview_guard(obj):
"""$intrinsic$"""
_builtin()
def _memoryview_itemsize(obj):
_builtin()
def _memoryview_nbytes(self):
_builtin()
def _memoryview_setitem(self, key, value):
_builtin()
def _memoryview_setslice(self, start, stop, step, value):
_builtin()
def _memoryview_start(self):
_builtin()
def _mmap_check(obj):
_builtin()
def _module_dir(module):
_builtin()
def _module_proxy(module):
_builtin()
def _module_proxy_check(obj):
_builtin()
def _module_proxy_guard(module):
_builtin()
def _module_proxy_keys(self):
_builtin()
def _module_proxy_setitem(self, key, value):
_builtin()
def _module_proxy_values(self):
_builtin()
def _iter(self):
_builtin()
def _object_class_set(obj, name):
_builtin()
def _object_keys(self):
_builtin()
def _object_type_getattr(obj, name):
"""Looks up the named attribute on the object's type, resolving descriptors.
Behaves like _PyObject_LookupSpecial."""
_builtin()
def _object_type_hasattr(obj, name):
_builtin()
def _os_write(fd, buf):
_builtin()
def _os_error_subclass_from_errno(errno):
_builtin()
def _profiler_install(new_thread_func, call_func, return_func):
_builtin()
def _profiler_exclude(callable):
"""Call `callable` and disable opcode counting in the current thread for the
duration of the call."""
_builtin()
def _property(fget=None, fset=None, fdel=None, doc=None):
"""Has the same effect as property(), but can be used for bootstrapping."""
_builtin()
def _property_isabstract(self):
_builtin()
def _pyobject_offset(instance, offset):
_builtin()
def _range_check(obj):
"""$intrinsic$"""
_builtin()
def _range_guard(obj):
"""$intrinsic$"""
_builtin()
def _range_len(self):
_builtin()
def _readline(prompt):
_builtin()
def _repr_enter(obj):
_builtin()
def _repr_leave(obj):
_builtin()
def _seq_index(obj):
"""$intrinsic$"""
_builtin()
def _seq_iterable(obj):
"""$intrinsic$"""
_builtin()
def _seq_set_index(obj, index):
"""$intrinsic$"""
_builtin()
def _seq_set_iterable(obj, iterable):
"""$intrinsic$"""
_builtin()
def _set_check(obj):
"""$intrinsic$"""
_builtin()
def _set_function_flag_iterable_coroutine(code):
_builtin()
def _set_guard(obj):
"""$intrinsic$"""
_builtin()
def _set_len(self):
"""$intrinsic$"""
_builtin()
def _set_member_double(addr, value):
_builtin()
def _set_member_float(addr, value):
_builtin()
def _set_member_integral(addr, value, num_bytes):
_builtin()
def _set_member_integral_unsigned(addr, value, num_bytes):
_builtin()
def _set_member_pyobject(addr, value):
_builtin()
def _slice_check(obj):
"""$intrinsic$"""
_builtin()
def _slice_guard(obj):
"""$intrinsic$"""
_builtin()
def _slice_start(start, step, length):
_builtin()
def _staticmethod(func):
_builtin()
def _slice_start_long(start, step, length):
_builtin()
def _slice_step(step):
_builtin()
def _slice_step_long(step):
_builtin()
def _slice_stop(stop, step, length):
_builtin()
def _slice_stop_long(stop, step, length):
_builtin()
def _staticmethod_isabstract(self):
_builtin()
def _stop_iteration_ctor(cls, *args):
_builtin()
def _str_array_clear(self):
_builtin()
def _str_array_ctor(cls, source=_Unbound):
_builtin()
def _str_array_iadd(self, other):
_builtin()
def _str_center(self, width, fillchar):
_builtin()
def _str_check(obj):
"""$intrinsic$"""
_builtin()
def _str_check_exact(obj):
"""$intrinsic$"""
_builtin()
def _str_compare_digest(a, b):
_builtin()
def _str_count(self, sub, start, end):
_builtin()
def _str_ctor(cls, obj=_Unbound, encoding=_Unbound, errors=_Unbound):
"""$intrinsic$"""
_builtin()
def _str_ctor_obj(cls, obj):
_builtin()
def _str_encode(self, encoding):
_builtin()
def _str_encode_ascii(self):
_builtin()
def _str_endswith(self, suffix, start, end):
_builtin()
def _str_getitem(self, key):
_builtin()
def _str_getslice(self, start, stop, step):
_builtin()
def _str_guard(obj):
"""$intrinsic$"""
_builtin()
def _str_ischr(obj):
_builtin()
def _str_join(sep, iterable):
_builtin()
def _str_ljust(self, width, fillchar):
_builtin()
def _str_escape_non_ascii(s):
_builtin()
def _str_find(self, sub, start, end):
_builtin()
def _str_from_str(cls, value):
_builtin()
def _str_len(self):
"""$intrinsic$"""
_builtin()
def _str_mod_fast_path(self, other):
_builtin()
def _str_partition(self, sep):
_builtin()
def _str_replace(self, old, newstr, count):
_builtin()
def _str_rfind(self, sub, start, end):
_builtin()
def _str_rjust(self, width, fillchar):
_builtin()
def _str_rpartition(self, sep):
_builtin()
def _str_split(self, sep, maxsplit):
_builtin()
def _str_splitlines(self, keepends):
_builtin()
def _str_startswith(self, prefix, start, end):
_builtin()
def _str_translate(obj, table):
_builtin()
def _structseq_getitem(structseq, index):
_builtin()
def _structseq_new_type(name, field_names, is_heaptype=True, num_in_sequence=_Unbound):
_builtin()
def _structseq_setitem(structseq, index, value):
_builtin()
def _super(cls):
_builtin()
def _super_ctor(cls, type=_Unbound, type_or_obj=_Unbound):
_builtin()
def _traceback_frame_get(self):
_builtin()
def _traceback_lineno_get(self):
_builtin()
def _traceback_next_get(self):
_builtin()
def _traceback_next_set(self, new_next):
_builtin()
def _tuple_check(obj):
"""$intrinsic$"""
_builtin()
def _tuple_check_exact(obj):
"""$intrinsic$"""
_builtin()
def _tuple_getitem(self, index):
"""$intrinsic$"""
_builtin()
def _tuple_getslice(self, start, stop, step):
_builtin()
def _tuple_guard(obj):
"""$intrinsic$"""
_builtin()
def _tuple_len(self):
"""$intrinsic$"""
_builtin()
def _tuple_new(cls, old_tuple):
_builtin()
def _type(obj):
"""$intrinsic$"""
_builtin()
def _type_ctor(cls, obj):
_builtin()
def _type_abstractmethods_del(self):
_builtin()
def _type_abstractmethods_get(self):
_builtin()
def _type_abstractmethods_set(self, value):
_builtin()
def _type_bases_del(self):
_builtin()
def _type_bases_get(self):
_builtin()
def _type_bases_set(self, value):
_builtin()
def _type_check(obj):
"""$intrinsic$"""
_builtin()
def _type_check_exact(obj):
"""$intrinsic$"""
_builtin()
def _type_dunder_call(self, *args, **kwargs):
_builtin()
def _type_guard(obj):
"""$intrinsic$"""
_builtin()
def _type_issubclass(subclass, superclass):
"""$intrinsic$"""
_builtin()
def _type_module_get(self):
_builtin()
def _type_module_set(self, value):
_builtin()
def _type_name_get(self):
_builtin()
def _type_name_set(self, value):
_builtin()
def _type_proxy(type_obj):
_builtin()
def _type_new(cls, name, bases, dict, is_heaptype):
_builtin()
def _type_proxy_check(obj):
_builtin()
def _type_proxy_get(self, key, default):
_builtin()
def _type_proxy_guard(obj):
_builtin()
def _type_proxy_keys(self):
_builtin()
def _type_proxy_len(self):
_builtin()
def _type_proxy_values(self):
_builtin()
def _type_qualname_get(self):
_builtin()
def _type_qualname_set(self, value):
_builtin()
def _type_subclass_guard(subclass, superclass):
"""$intrinsic$"""
_builtin()
def _unimplemented():
"""Prints a message and a stacktrace, and stops the program execution."""
_builtin()
def _warn(message, category=None, stacklevel=1, source=None):
"""Calls warnings.warn."""
_builtin()
def _weakref_callback(self):
_builtin()
def _weakref_check(self):
"""$intrinsic$"""
_builtin()
def _weakref_guard(self):
"""$intrinsic$"""
_builtin()
def _weakref_referent(self):
_builtin()
maxunicode = maxunicode
|
def longestCommonSubsequence(str1, str2):
if not str1 or not str2:
return []
dp = [[0 for _ in range(len(str2))] for __ in range(len(str1))]
commons = []
inc = 0
for i in range(len(str1)):
if str1[i] == str2[0]:
inc = 1
dp[i][0] = inc
inc = 0
for j in range(len(str2)):
if str2[j] == str1[0]:
inc = 1
dp[0][j] = inc
for i in range(1, len(str1)):
for j in range(1, len(str2)):
if str1[i] == str2[j]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
row = len(str1) - 1
col = len(str2) - 1
while row >= 0 and col >= 0:
if col - 1 >= 0 and dp[row][col] == dp[row][col - 1]:
col -= 1
elif row - 1 >= 0 and dp[row][col] == dp[row - 1][col]:
row -= 1
else:
if str1[row] == str2[col]:
commons.insert(0, str1[row])
row -= 1
col -= 1
return commons
|
def longest_common_subsequence(str1, str2):
if not str1 or not str2:
return []
dp = [[0 for _ in range(len(str2))] for __ in range(len(str1))]
commons = []
inc = 0
for i in range(len(str1)):
if str1[i] == str2[0]:
inc = 1
dp[i][0] = inc
inc = 0
for j in range(len(str2)):
if str2[j] == str1[0]:
inc = 1
dp[0][j] = inc
for i in range(1, len(str1)):
for j in range(1, len(str2)):
if str1[i] == str2[j]:
dp[i][j] = 1 + dp[i - 1][j - 1]
else:
dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])
row = len(str1) - 1
col = len(str2) - 1
while row >= 0 and col >= 0:
if col - 1 >= 0 and dp[row][col] == dp[row][col - 1]:
col -= 1
elif row - 1 >= 0 and dp[row][col] == dp[row - 1][col]:
row -= 1
else:
if str1[row] == str2[col]:
commons.insert(0, str1[row])
row -= 1
col -= 1
return commons
|
# -*- coding: utf-8 -*-
class Node:
def __init__(self, node_type):
self.type = node_type
self.node_problems = []
@property
def name(self):
return ""
@property
def problems(self):
return self.node_problems
class ValueNode(Node):
def __init__(self, node_type, value):
super().__init__(node_type)
self.value = value
class ParentNode(Node):
def __init__(self, node_type):
super().__init__(node_type)
self.__children = []
self.__children_map = {}
@property
def problems(self):
pbs = self.node_problems.copy()
for chld in self.__children:
pbs.extend(chld.problems)
return pbs
def _get_children(self, name=None):
if name is None:
return self.__children
else:
return self.__children_map.get(name, [])
def _add_child(self, child):
self.__children.append(child)
if child.name not in self.__children_map:
self.__children_map[child.name] = [child]
else:
self.__children_map[child.name].append(child)
|
class Node:
def __init__(self, node_type):
self.type = node_type
self.node_problems = []
@property
def name(self):
return ''
@property
def problems(self):
return self.node_problems
class Valuenode(Node):
def __init__(self, node_type, value):
super().__init__(node_type)
self.value = value
class Parentnode(Node):
def __init__(self, node_type):
super().__init__(node_type)
self.__children = []
self.__children_map = {}
@property
def problems(self):
pbs = self.node_problems.copy()
for chld in self.__children:
pbs.extend(chld.problems)
return pbs
def _get_children(self, name=None):
if name is None:
return self.__children
else:
return self.__children_map.get(name, [])
def _add_child(self, child):
self.__children.append(child)
if child.name not in self.__children_map:
self.__children_map[child.name] = [child]
else:
self.__children_map[child.name].append(child)
|
'''
https://leetcode.com/problems/maximum-subarray/
'''
class Solution(object):
def maxSubArray(self, nums):
if len(nums) == 1:
return nums[0]
m = nums[0]
h = {0:nums[0]}
for i in range(1, len(nums)):
# we loop through the array and store the longest subarray which ends at element i-1 (inclusive)
# adding the element at index i to the maximum sum at index i - 1 would result in a higher sum than simply
# starting a new array with length 1 (only including one element, arr[i]), then we update the dictionary
# to account for the inclusion of the element at index i.
# if the element at index[i] + the value of the max subarray at i-1 is not higher than
# the value of arr[i], we simply start a new array at arr[i], becuase that new array would, by definition,
# be of a greater value than whatever array ended at index i-1.
# example:
# arr [1,4,-6,8,1]
# h [1,5,-1,8,9]
#notice how at index 0,1 and 2, we add element i to the previous sum,
# but at index 3, we do not add the element to the previous indexed sum, we
# simply set the max array value to the value of the element. becuase max(8, 8 + (-1)) = 8.
#and for index 4, we also add the item at i to the previous sum
h[i] = max(nums[i], nums[i] + h[i-1])
if h[i] > m: # we see if the max sum at index i is higher than the currently recorded max sum
# if True, we update the max sum.
m = h[i]
# we return the max sum (int)
return m
|
"""
https://leetcode.com/problems/maximum-subarray/
"""
class Solution(object):
def max_sub_array(self, nums):
if len(nums) == 1:
return nums[0]
m = nums[0]
h = {0: nums[0]}
for i in range(1, len(nums)):
h[i] = max(nums[i], nums[i] + h[i - 1])
if h[i] > m:
m = h[i]
return m
|
input = open('input.txt', 'r').read().split("\n")
# Part 1
x = 0
depth = 0
for line in input:
line_elements = line.split(' ')
cmd = line_elements[0]
distance = int(line_elements[1])
if cmd == 'forward':
x += distance
elif cmd == 'down':
depth += distance
else:
depth += -distance
print('X: ' + str(x))
print('Depth: ' + str(depth))
# Part 2
aim = 0
horizontal = 0
depth = 0
for line in input:
line_elements = line.split(' ')
cmd = line_elements[0]
value = int(line_elements[1])
if cmd == 'forward':
horizontal += value
depth += aim * value
elif cmd == 'down':
aim += value
else:
aim += -value
print('Part 2')
print('X: ' + str(x))
print('Depth: ' + str(depth))
print('Answer: ' + str(x * depth))
|
input = open('input.txt', 'r').read().split('\n')
x = 0
depth = 0
for line in input:
line_elements = line.split(' ')
cmd = line_elements[0]
distance = int(line_elements[1])
if cmd == 'forward':
x += distance
elif cmd == 'down':
depth += distance
else:
depth += -distance
print('X: ' + str(x))
print('Depth: ' + str(depth))
aim = 0
horizontal = 0
depth = 0
for line in input:
line_elements = line.split(' ')
cmd = line_elements[0]
value = int(line_elements[1])
if cmd == 'forward':
horizontal += value
depth += aim * value
elif cmd == 'down':
aim += value
else:
aim += -value
print('Part 2')
print('X: ' + str(x))
print('Depth: ' + str(depth))
print('Answer: ' + str(x * depth))
|
_base_ = [
'../../_base_/models/swav/r50.py',
'../../_base_/datasets/imagenet/swav_mcrop-2-6_sz224_96_bs32.py',
'../../_base_/default_runtime.py',
]
# model settings
model = dict(
type='SwAV',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(3,), # no conv-1, x-1: stage-x
norm_cfg=dict(type='SyncBN'),
style='pytorch'),
neck=dict(
type='SwAVNeck',
in_channels=2048, hid_channels=2048, out_channels=128,
with_avg_pool=True),
head=dict(
type='SwAVHead',
feat_dim=128, # equal to neck['out_channels']
epsilon=0.05,
temperature=0.1,
num_crops=[2, 6],)
)
# interval for accumulate gradient
update_interval = 8 # total: 8 x bs64 x 8 accumulates = bs4096
# additional hooks
custom_hooks = [
dict(type='SwAVHook',
priority='VERY_HIGH',
batch_size=64,
epoch_queue_starts=15,
crops_for_assign=[0, 1],
feat_dim=128,
queue_length=3840)
]
# optimizer
optimizer = dict(
type='LARS',
lr=0.6 * 16, # lr=0.6 / bs256
momentum=0.9, weight_decay=1e-6,
paramwise_options={
'(bn|ln|gn)(\d+)?.(weight|bias)': dict(weight_decay=0., lars_exclude=True),
'bias': dict(weight_decay=0., lars_exclude=True),
})
# apex
use_fp16 = True
fp16 = dict(type='apex', loss_scale=dict(init_scale=512., mode='dynamic'))
# optimizer args
optimizer_config = dict(
update_interval=update_interval, use_fp16=use_fp16, grad_clip=None,
cancel_grad=dict(prototypes=2503), # cancel grad of `prototypes` for 1 ep
)
# lr scheduler
lr_config = dict(
policy='CosineAnnealing',
by_epoch=False, min_lr=6e-4,
warmup='linear',
warmup_iters=10, warmup_by_epoch=True,
warmup_ratio=1e-5,
)
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=200)
|
_base_ = ['../../_base_/models/swav/r50.py', '../../_base_/datasets/imagenet/swav_mcrop-2-6_sz224_96_bs32.py', '../../_base_/default_runtime.py']
model = dict(type='SwAV', backbone=dict(type='ResNet', depth=50, num_stages=4, out_indices=(3,), norm_cfg=dict(type='SyncBN'), style='pytorch'), neck=dict(type='SwAVNeck', in_channels=2048, hid_channels=2048, out_channels=128, with_avg_pool=True), head=dict(type='SwAVHead', feat_dim=128, epsilon=0.05, temperature=0.1, num_crops=[2, 6]))
update_interval = 8
custom_hooks = [dict(type='SwAVHook', priority='VERY_HIGH', batch_size=64, epoch_queue_starts=15, crops_for_assign=[0, 1], feat_dim=128, queue_length=3840)]
optimizer = dict(type='LARS', lr=0.6 * 16, momentum=0.9, weight_decay=1e-06, paramwise_options={'(bn|ln|gn)(\\d+)?.(weight|bias)': dict(weight_decay=0.0, lars_exclude=True), 'bias': dict(weight_decay=0.0, lars_exclude=True)})
use_fp16 = True
fp16 = dict(type='apex', loss_scale=dict(init_scale=512.0, mode='dynamic'))
optimizer_config = dict(update_interval=update_interval, use_fp16=use_fp16, grad_clip=None, cancel_grad=dict(prototypes=2503))
lr_config = dict(policy='CosineAnnealing', by_epoch=False, min_lr=0.0006, warmup='linear', warmup_iters=10, warmup_by_epoch=True, warmup_ratio=1e-05)
runner = dict(type='EpochBasedRunner', max_epochs=200)
|
# File: vmray_consts.py
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
VMRAY_JSON_SERVER = "vmray_server"
VMRAY_JSON_API_KEY = "vmray_api_key"
VMRAY_JSON_DISABLE_CERT = "disable_cert_verification"
VMRAY_ERR_SERVER_CONNECTION = "Could not connect to server. {}"
VMRAY_ERR_CONNECTIVITY_TEST = "Connectivity test failed"
VMRAY_SUCC_CONNECTIVITY_TEST = "Connectivity test passed"
VMRAY_ERR_UNSUPPORTED_HASH = "Unsupported hash"
VMRAY_ERR_SAMPLE_NOT_FOUND = "Could not find sample"
VMRAY_ERR_OPEN_ZIP = "Could not open zip file"
VMRAY_ERR_ADD_VAULT = "Could not add file to vault"
VMRAY_ERR_MULTIPART = "File is a multipart sample. Multipart samples are not supported"
VMRAY_ERR_MALFORMED_ZIP = "Malformed zip"
VMRAY_ERR_SUBMIT_FILE = "Could not submit file"
VMRAY_ERR_GET_SUBMISSION = "Could not get submission"
VMRAY_ERR_SUBMISSION_NOT_FINISHED = "Submission is not finished"
VMRAY_ERR_NO_SUBMISSIONS = "Sample has no submissions"
VMRAY_ERR_FILE_EXISTS = "File already exists"
VMRAY_ERR_REST_API = "REST API Error"
VMRAY_ERR_CODE_MSG = "Error code unavailable"
VMRAY_ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters"
VMRAY_PARSE_ERR_MSG = "Unable to parse the error message. Please check the asset configuration and|or action parameters"
VMRAY_ERR_SERVER_RES = "Error processing server response. {}"
VMRAY_INVALID_INTEGER_ERR_MSG = "Please provide a valid integer value in the {}"
VMRAY_NEGATIVE_INTEGER_ERR_MSG = "Please provide a valid non-negative integer value in the {}"
ACTION_ID_VMRAY_GET_FILE = "get_file"
ACTION_ID_VMRAY_DETONATE_FILE = "detonate_file"
ACTION_ID_VMRAY_DETONATE_URL = "detonate_url"
ACTION_ID_VMRAY_GET_REPORT = "get_report"
ACTION_ID_VMRAY_GET_INFO = "get_info"
VMRAY_DEFAULT_PASSWORD = b"infected"
DEFAULT_TIMEOUT = 60 * 10
VMRAY_SEVERITY_NOT_SUSPICIOUS = "not_suspicious"
VMRAY_SEVERITY_SUSPICIOUS = "suspicious"
VMRAY_SEVERITY_MALICIOUS = "malicious"
VMRAY_SEVERITY_BLACKLISTED = "blacklisted"
VMRAY_SEVERITY_WHITELISTED = "whitelisted"
VMRAY_SEVERITY_UNKNOWN = "unknown"
VMRAY_SEVERITY_ERROR = "error"
SAMPLE_TYPE_MAPPING = {
"Apple Script": "apple script",
"Archive": "archive",
"CFB File": "compound binary file",
"Email (EML)": "email",
"Email (MSG)": "email",
"Excel Document": "xls",
"HTML Application": "html application",
"HTML Application (Shell Link)": "html application",
"HTML Document": "html document",
"Hanword Document": "hanword document",
"JScript": "jscript",
"Java Archive": "jar",
"Java Class": "java class",
"macOS App": "macos app",
"macOS Executable": "macos executable",
"macOS PKG": "macos installer",
"MHTML Document": "mhtml document",
"MSI Setup": "msi",
"Macromedia Flash": "flash",
"Microsoft Access Database": "mdb",
"Microsoft Project Document": "mpp",
"Microsoft Publisher Document": "pub",
"Microsoft Visio Document": "vsd",
"PDF Document": "pdf",
"PowerShell Script": "powershell",
"PowerShell Script (Shell Link)": "powershell",
"Powerpoint Document": "ppt",
"Python Script": "python script",
"RTF Document": "rtf",
"Shell Script": "shell script",
"URL": "url",
"VBScript": "vbscript",
"Windows ActiveX Control (x86-32)": "pe file",
"Windows ActiveX Control (x86-64)": "pe file",
"Windows Batch File": "batch file",
"Windows Batch File (Shell Link)": "batch file",
"Windows DLL (x86-32)": "dll",
"Windows DLL (x86-64)": "dll",
"Windows Driver (x86-32)": "pe file",
"Windows Driver (x86-64)": "pe file",
"Windows Exe (Shell Link)": "pe file",
"Windows Exe (x86-32)": "pe file",
"Windows Exe (x86-64)": "pe file",
"Windows Help File": "windows help file",
"Windows Script File": "windows script file",
"Word Document": "doc",
}
|
vmray_json_server = 'vmray_server'
vmray_json_api_key = 'vmray_api_key'
vmray_json_disable_cert = 'disable_cert_verification'
vmray_err_server_connection = 'Could not connect to server. {}'
vmray_err_connectivity_test = 'Connectivity test failed'
vmray_succ_connectivity_test = 'Connectivity test passed'
vmray_err_unsupported_hash = 'Unsupported hash'
vmray_err_sample_not_found = 'Could not find sample'
vmray_err_open_zip = 'Could not open zip file'
vmray_err_add_vault = 'Could not add file to vault'
vmray_err_multipart = 'File is a multipart sample. Multipart samples are not supported'
vmray_err_malformed_zip = 'Malformed zip'
vmray_err_submit_file = 'Could not submit file'
vmray_err_get_submission = 'Could not get submission'
vmray_err_submission_not_finished = 'Submission is not finished'
vmray_err_no_submissions = 'Sample has no submissions'
vmray_err_file_exists = 'File already exists'
vmray_err_rest_api = 'REST API Error'
vmray_err_code_msg = 'Error code unavailable'
vmray_err_msg_unavailable = 'Error message unavailable. Please check the asset configuration and|or action parameters'
vmray_parse_err_msg = 'Unable to parse the error message. Please check the asset configuration and|or action parameters'
vmray_err_server_res = 'Error processing server response. {}'
vmray_invalid_integer_err_msg = 'Please provide a valid integer value in the {}'
vmray_negative_integer_err_msg = 'Please provide a valid non-negative integer value in the {}'
action_id_vmray_get_file = 'get_file'
action_id_vmray_detonate_file = 'detonate_file'
action_id_vmray_detonate_url = 'detonate_url'
action_id_vmray_get_report = 'get_report'
action_id_vmray_get_info = 'get_info'
vmray_default_password = b'infected'
default_timeout = 60 * 10
vmray_severity_not_suspicious = 'not_suspicious'
vmray_severity_suspicious = 'suspicious'
vmray_severity_malicious = 'malicious'
vmray_severity_blacklisted = 'blacklisted'
vmray_severity_whitelisted = 'whitelisted'
vmray_severity_unknown = 'unknown'
vmray_severity_error = 'error'
sample_type_mapping = {'Apple Script': 'apple script', 'Archive': 'archive', 'CFB File': 'compound binary file', 'Email (EML)': 'email', 'Email (MSG)': 'email', 'Excel Document': 'xls', 'HTML Application': 'html application', 'HTML Application (Shell Link)': 'html application', 'HTML Document': 'html document', 'Hanword Document': 'hanword document', 'JScript': 'jscript', 'Java Archive': 'jar', 'Java Class': 'java class', 'macOS App': 'macos app', 'macOS Executable': 'macos executable', 'macOS PKG': 'macos installer', 'MHTML Document': 'mhtml document', 'MSI Setup': 'msi', 'Macromedia Flash': 'flash', 'Microsoft Access Database': 'mdb', 'Microsoft Project Document': 'mpp', 'Microsoft Publisher Document': 'pub', 'Microsoft Visio Document': 'vsd', 'PDF Document': 'pdf', 'PowerShell Script': 'powershell', 'PowerShell Script (Shell Link)': 'powershell', 'Powerpoint Document': 'ppt', 'Python Script': 'python script', 'RTF Document': 'rtf', 'Shell Script': 'shell script', 'URL': 'url', 'VBScript': 'vbscript', 'Windows ActiveX Control (x86-32)': 'pe file', 'Windows ActiveX Control (x86-64)': 'pe file', 'Windows Batch File': 'batch file', 'Windows Batch File (Shell Link)': 'batch file', 'Windows DLL (x86-32)': 'dll', 'Windows DLL (x86-64)': 'dll', 'Windows Driver (x86-32)': 'pe file', 'Windows Driver (x86-64)': 'pe file', 'Windows Exe (Shell Link)': 'pe file', 'Windows Exe (x86-32)': 'pe file', 'Windows Exe (x86-64)': 'pe file', 'Windows Help File': 'windows help file', 'Windows Script File': 'windows script file', 'Word Document': 'doc'}
|
IDENTIFIER = 'everything'
NEWSPAPER_DIR = 'newspapers_everything'
RESULTS_DIR = 'results_everything'
MIN_FREQUENCY = 50
EPOCHS = 40
MODEL_OPTIONS = {
'vector_size': 100,
'alpha': 0.1,
'window': 8,
'sample': 0.00001,
'workers': 8
}
VOCABULARY = f'{IDENTIFIER}.dict'
|
identifier = 'everything'
newspaper_dir = 'newspapers_everything'
results_dir = 'results_everything'
min_frequency = 50
epochs = 40
model_options = {'vector_size': 100, 'alpha': 0.1, 'window': 8, 'sample': 1e-05, 'workers': 8}
vocabulary = f'{IDENTIFIER}.dict'
|
a, b, c = map(int, input().split())
x = max(a, b, c)
total = a + b + c
if x % 2 != total % 2:
x += 1
print((3 * x - total) // 2)
|
(a, b, c) = map(int, input().split())
x = max(a, b, c)
total = a + b + c
if x % 2 != total % 2:
x += 1
print((3 * x - total) // 2)
|
class BentPlateTestingTool(object):
""" BentPlateTestingTool() """
def CreateByFaces(self, part1, face1, part2, face2):
""" CreateByFaces(self: BentPlateTestingTool,part1: Part,face1: IList[Point],part2: Part,face2: IList[Point]) -> BentPlate """
pass
|
class Bentplatetestingtool(object):
""" BentPlateTestingTool() """
def create_by_faces(self, part1, face1, part2, face2):
""" CreateByFaces(self: BentPlateTestingTool,part1: Part,face1: IList[Point],part2: Part,face2: IList[Point]) -> BentPlate """
pass
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def __init__(self):
self.rst = list()
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
# Recursive method
self.inorder_traverse(root)
return self.rst
# TODO: Iteration method
def inorder_traverse(self, root):
if root:
self.inorder_traverse(root.left)
if root.val is not None:
self.rst.append(root.val)
self.inorder_traverse(root.right)
|
class Solution:
def __init__(self):
self.rst = list()
def inorder_traversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
self.inorder_traverse(root)
return self.rst
def inorder_traverse(self, root):
if root:
self.inorder_traverse(root.left)
if root.val is not None:
self.rst.append(root.val)
self.inorder_traverse(root.right)
|
count = 0
sum = 0
while True:
X = float(input(''))
if X >= 0 and X <= 10:
count += 1
sum += X
if count == 2:
average = sum / count
print('media = %0.2f' %average)
break
else:
print('nota invalida')
|
count = 0
sum = 0
while True:
x = float(input(''))
if X >= 0 and X <= 10:
count += 1
sum += X
if count == 2:
average = sum / count
print('media = %0.2f' % average)
break
else:
print('nota invalida')
|
commands = []
while True:
try: line = input()
except: break
if not line: break
commands.append(line.split())
for starting_a in range(155, 160):
d = {'a': starting_a, 'b': 0, 'c': 0, 'd': 0}
i = 0
out = []
while len(out) < 100:
if commands[i][0] == 'inc' and commands[i+1][0] == 'dec' and commands[i+2][0] == 'jnz' and commands[i+1][1] == commands[i+2][1] and commands[i+2][2] == '-2':
d[commands[i][1]] += d[commands[i+1][1]]
d[commands[i+1][1]] = 0
i += 3
continue
elif commands[i][0] == 'cpy':
a, b = commands[i][1:]
if a.isalpha():
d[b] = d[a]
elif b.isalpha():
d[b] = int(a)
elif commands[i][0] == 'inc':
d[commands[i][1]] += 1
elif commands[i][0] == 'dec':
d[commands[i][1]] -= 1
elif commands[i][0] == 'jnz':
a, b = commands[i][1:]
if a.isalpha():
if d[a] != 0:
i += (d[b] if b.isalpha() else int(b)) - 1
else:
if int(a) != 0:
i += (d[b] if b.isalpha() else int(b)) - 1
elif commands[i][0] == 'tgl':
a = commands[i][1]
if a.isalpha(): a = d[a]
else: a = int(a)
if i + a >= 0 and i + a < len(commands):
command = commands[i + a][0]
if command == 'inc': command = 'dec'
elif command == 'dec': command = 'inc'
elif command == 'jnz': command = 'cpy'
elif command == 'cpy': command = 'jnz'
elif command == 'tgl': command = 'inc'
commands[i + a][0] = command
elif commands[i][0] == 'out':
out.append(d[commands[i][1]])
i += 1
if out == [i % 2 for i in range(100)]:
print(starting_a)
|
commands = []
while True:
try:
line = input()
except:
break
if not line:
break
commands.append(line.split())
for starting_a in range(155, 160):
d = {'a': starting_a, 'b': 0, 'c': 0, 'd': 0}
i = 0
out = []
while len(out) < 100:
if commands[i][0] == 'inc' and commands[i + 1][0] == 'dec' and (commands[i + 2][0] == 'jnz') and (commands[i + 1][1] == commands[i + 2][1]) and (commands[i + 2][2] == '-2'):
d[commands[i][1]] += d[commands[i + 1][1]]
d[commands[i + 1][1]] = 0
i += 3
continue
elif commands[i][0] == 'cpy':
(a, b) = commands[i][1:]
if a.isalpha():
d[b] = d[a]
elif b.isalpha():
d[b] = int(a)
elif commands[i][0] == 'inc':
d[commands[i][1]] += 1
elif commands[i][0] == 'dec':
d[commands[i][1]] -= 1
elif commands[i][0] == 'jnz':
(a, b) = commands[i][1:]
if a.isalpha():
if d[a] != 0:
i += (d[b] if b.isalpha() else int(b)) - 1
elif int(a) != 0:
i += (d[b] if b.isalpha() else int(b)) - 1
elif commands[i][0] == 'tgl':
a = commands[i][1]
if a.isalpha():
a = d[a]
else:
a = int(a)
if i + a >= 0 and i + a < len(commands):
command = commands[i + a][0]
if command == 'inc':
command = 'dec'
elif command == 'dec':
command = 'inc'
elif command == 'jnz':
command = 'cpy'
elif command == 'cpy':
command = 'jnz'
elif command == 'tgl':
command = 'inc'
commands[i + a][0] = command
elif commands[i][0] == 'out':
out.append(d[commands[i][1]])
i += 1
if out == [i % 2 for i in range(100)]:
print(starting_a)
|
tiles = [
(17, 20946, 50678), # https://www.openstreetmap.org/way/215472849
(17, 20959, 50673), # https://www.openstreetmap.org/node/1713279804
(17, 20961, 50675), # https://www.openstreetmap.org/node/3188857553
(17, 20969, 50656), # https://www.openstreetmap.org/node/3396659022
(17, 21013, 50637), # https://www.openstreetmap.org/node/1467717312
(17, 21019, 50617), # https://www.openstreetmap.org/node/2286100659
(17, 21028, 50645), # https://www.openstreetmap.org/node/3711137981
(17, 38597, 49266), # https://www.openstreetmap.org/node/3810578539
(17, 38598, 49259), # http://www.openstreetmap.org/node/2678466844
(17, 38600, 49261), # https://www.openstreetmap.org/node/1429062988
(17, 38601, 49258), # https://www.openstreetmap.org/node/1058296287
]
for z, x, y in tiles:
assert_has_feature(
z, x, y, 'pois',
{ 'kind': 'toys' })
|
tiles = [(17, 20946, 50678), (17, 20959, 50673), (17, 20961, 50675), (17, 20969, 50656), (17, 21013, 50637), (17, 21019, 50617), (17, 21028, 50645), (17, 38597, 49266), (17, 38598, 49259), (17, 38600, 49261), (17, 38601, 49258)]
for (z, x, y) in tiles:
assert_has_feature(z, x, y, 'pois', {'kind': 'toys'})
|
def method1(n: int) -> int:
c = 0
while n:
c += n & 1
n >>= 1
return c
def method2(n: int) -> int:
if n == 0:
return 0
else:
return (n & 1) + method2(n >> 1)
if __name__ == "__main__":
"""
from timeit import timeit
print(timeit(lambda: method1(9), number=10000)) # 0.0034751240000332473
print(timeit(lambda: method2(9), number=10000)) # 0.006590511000013066
"""
|
def method1(n: int) -> int:
c = 0
while n:
c += n & 1
n >>= 1
return c
def method2(n: int) -> int:
if n == 0:
return 0
else:
return (n & 1) + method2(n >> 1)
if __name__ == '__main__':
'\n from timeit import timeit\n print(timeit(lambda: method1(9), number=10000)) # 0.0034751240000332473\n print(timeit(lambda: method2(9), number=10000)) # 0.006590511000013066\n '
|
'''
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Input: num1 = [3], nums2 = [3]
Output: 1
Input: [1,2], [4,6]
Output: 0
Input: nums1 = [0,0,0,0], nums2 = [0,0,0,0,0]
Output: 4
Precondition:
len(nums1) = m
len(nums2) = n
m, n >= 1
C1: single elements in both, same
C2: single elements in both, not same
C3: 0 as a result
C4: result > 0
C5: result = len(min(m,n))
Algo:
Brute Force: O(mn*min(m,n))
For each element in nums1, try to find same element in nums2 O(mn)
if found, extend as long as possible
return the longest size
DP:
dp[i][j]: common prefix length for nums1[i:] and nums2[j:]
dp[i][j] = dp[i+1][j+1] if nums1[i] = nums2[j]
dp[m][n] = 0
result: max of all possible i,j in dp[i][j]
Runtime: O(mn)
Space: O(mn)
'''
class Solution:
def findLength(self, nums1: List[int], nums2: List[int]) -> int:
m = len(nums1)
n = len(nums2)
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if nums1[i] == nums2[j]:
dp[i][j] = dp[i+1][j+1] + 1
return max(max(x) for x in dp)
|
"""
Given two integer arrays nums1 and nums2, return the maximum length of a subarray that appears in both arrays.
Input: nums1 = [1,2,3,2,1], nums2 = [3,2,1,4,7]
Output: 3
Explanation: The repeated subarray with maximum length is [3,2,1].
Input: num1 = [3], nums2 = [3]
Output: 1
Input: [1,2], [4,6]
Output: 0
Input: nums1 = [0,0,0,0], nums2 = [0,0,0,0,0]
Output: 4
Precondition:
len(nums1) = m
len(nums2) = n
m, n >= 1
C1: single elements in both, same
C2: single elements in both, not same
C3: 0 as a result
C4: result > 0
C5: result = len(min(m,n))
Algo:
Brute Force: O(mn*min(m,n))
For each element in nums1, try to find same element in nums2 O(mn)
if found, extend as long as possible
return the longest size
DP:
dp[i][j]: common prefix length for nums1[i:] and nums2[j:]
dp[i][j] = dp[i+1][j+1] if nums1[i] = nums2[j]
dp[m][n] = 0
result: max of all possible i,j in dp[i][j]
Runtime: O(mn)
Space: O(mn)
"""
class Solution:
def find_length(self, nums1: List[int], nums2: List[int]) -> int:
m = len(nums1)
n = len(nums2)
dp = [[0 for _ in range(n + 1)] for _ in range(m + 1)]
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
if nums1[i] == nums2[j]:
dp[i][j] = dp[i + 1][j + 1] + 1
return max((max(x) for x in dp))
|
def data_generator_enabled(request):
return {'DATA_GENERATOR_ENABLED': True}
|
def data_generator_enabled(request):
return {'DATA_GENERATOR_ENABLED': True}
|
class Encoders:
def __init__(self, aStar):
self.aStar = aStar
self.countLeft = 0
self.countRight = 0
self.lastCountLeft = 0
self.lastCountRight = 0
self.countSignLeft = 1
self.countSignRight = -1
self.aStar.reset_encoders()
def readCounts(self):
countLeft, countRight = self.aStar.read_encoders()
diffLeft = (countLeft - self.lastCountLeft) % 0x10000
if diffLeft >= 0x8000:
diffLeft -= 0x10000
diffRight = (countRight - self.lastCountRight) % 0x10000
if diffRight >= 0x8000:
diffRight -= 0x10000
self.countLeft += self.countSignLeft * diffLeft
self.countRight += self.countSignRight * diffRight
self.lastCountLeft = countLeft
self.lastCountRight = countRight
return self.countLeft, self.countRight
def reset(self):
self.countLeft = 0
self.countRight = 0
|
class Encoders:
def __init__(self, aStar):
self.aStar = aStar
self.countLeft = 0
self.countRight = 0
self.lastCountLeft = 0
self.lastCountRight = 0
self.countSignLeft = 1
self.countSignRight = -1
self.aStar.reset_encoders()
def read_counts(self):
(count_left, count_right) = self.aStar.read_encoders()
diff_left = (countLeft - self.lastCountLeft) % 65536
if diffLeft >= 32768:
diff_left -= 65536
diff_right = (countRight - self.lastCountRight) % 65536
if diffRight >= 32768:
diff_right -= 65536
self.countLeft += self.countSignLeft * diffLeft
self.countRight += self.countSignRight * diffRight
self.lastCountLeft = countLeft
self.lastCountRight = countRight
return (self.countLeft, self.countRight)
def reset(self):
self.countLeft = 0
self.countRight = 0
|
def DectoHex(n):
if isinstance(n,int) == True:
hexnum = hex(n)[2:]
return hexnum.upper()
else:
intnum = int(n)
hexnum = hex(intnum)[2:]
return hexnum.upper()
|
def decto_hex(n):
if isinstance(n, int) == True:
hexnum = hex(n)[2:]
return hexnum.upper()
else:
intnum = int(n)
hexnum = hex(intnum)[2:]
return hexnum.upper()
|
params = [
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 85.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'alpha',
'title': 'Stolaroff',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.0,
'xend': 15.0,
'xnumber': 10,
'validation': False,
'validationcase': 'Stolaroff2018',
'batterytechnology': 'current'
},
{
'validation': False,
'validationcase': 'Ostler2009',
'drone': True,
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 89.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'power',
'title': 'Ostler2009',
'simulationtype': 'simple',
'xbegin': 0.0,
'xend': 30.0,
'xnumber': 20,
'batterytechnology': 'current'
},
{
'drone': True,
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 89.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'endurance',
'title': 'FreeFLY_Alta8',
'simulationtype': 'simple',
'xbegin': 0.0,
'xend': 10.0,
'xnumber': 100,
'validation': False,
'validationcase': 'FreeFLYAlta8',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'endurance',
'title': 'FreeFLY_Alta8',
'simulationtype': 'simple',
'xbegin': 0.0,
'xend': 1.0,
'xnumber': 20,
'validation': False,
'validationcase': 'FireFLY6Pro',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 90.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'power',
'title': 'First_test',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.5,
'xend': 1.5,
'xnumber': 10,
'validation': False,
'validationcase': 'Dorling2017_3S',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 90.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'power',
'title': 'First_test',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.5,
'xend': 1.5,
'xnumber': 10,
'validation': False,
'validationcase': 'Dorling2017_4S',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'power',
'title': 'DiFranco',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.0,
'xend': 16.0,
'xnumber': 20,
'validation': False,
'validationcase': 'DiFranco2016',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 100.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'missionspeed',
'ylabel': 'power',
'title': 'Stolaroff',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.0,
'xend': 16.0,
'xnumber': 20,
'validation': False,
'validationcase': 'Chang2016',
'batterytechnology': 'current'
},
{
'dronename': 'drone',
'stateofhealth': 90.0,
'startstateofcharge': 100.0,
'altitude': 100.0,
'temperaturesealevel': 15.0,
'rain': False,
'dropsize': 0.0,
'liquidwatercontent': 1.0,
'temperature': 15.0,
'wind': False,
'windspeed': 0.0,
'winddirection': 0.0,
'relativehumidity': 0.0,
'icing': False,
'timestep': 1,
'plot': True,
'xlabel': 'payload',
'ylabel': 'endurance',
'title': 'Abdilla 2015 Endurance vs Payload Validation Test',
'simulationtype': 'simple',
'model': 'abdilla',
'xbegin': 0.4,
'xend': 0.55,
'xnumber': 20,
'validation': False,
'validationcase': 'Abdilla2015endurance',
'batterytechnology': 'current'
}
]
|
params = [{'dronename': 'drone', 'stateofhealth': 100.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 85.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'missionspeed', 'ylabel': 'alpha', 'title': 'Stolaroff', 'simulationtype': 'simple', 'model': 'abdilla', 'xbegin': 0.0, 'xend': 15.0, 'xnumber': 10, 'validation': False, 'validationcase': 'Stolaroff2018', 'batterytechnology': 'current'}, {'validation': False, 'validationcase': 'Ostler2009', 'drone': True, 'dronename': 'drone', 'stateofhealth': 100.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 89.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'missionspeed', 'ylabel': 'power', 'title': 'Ostler2009', 'simulationtype': 'simple', 'xbegin': 0.0, 'xend': 30.0, 'xnumber': 20, 'batterytechnology': 'current'}, {'drone': True, 'dronename': 'drone', 'stateofhealth': 100.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 89.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'payload', 'ylabel': 'endurance', 'title': 'FreeFLY_Alta8', 'simulationtype': 'simple', 'xbegin': 0.0, 'xend': 10.0, 'xnumber': 100, 'validation': False, 'validationcase': 'FreeFLYAlta8', 'batterytechnology': 'current'}, {'dronename': 'drone', 'stateofhealth': 100.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 0.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'payload', 'ylabel': 'endurance', 'title': 'FreeFLY_Alta8', 'simulationtype': 'simple', 'xbegin': 0.0, 'xend': 1.0, 'xnumber': 20, 'validation': False, 'validationcase': 'FireFLY6Pro', 'batterytechnology': 'current'}, {'dronename': 'drone', 'stateofhealth': 90.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 0.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'payload', 'ylabel': 'power', 'title': 'First_test', 'simulationtype': 'simple', 'model': 'abdilla', 'xbegin': 0.5, 'xend': 1.5, 'xnumber': 10, 'validation': False, 'validationcase': 'Dorling2017_3S', 'batterytechnology': 'current'}, {'dronename': 'drone', 'stateofhealth': 90.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 0.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'payload', 'ylabel': 'power', 'title': 'First_test', 'simulationtype': 'simple', 'model': 'abdilla', 'xbegin': 0.5, 'xend': 1.5, 'xnumber': 10, 'validation': False, 'validationcase': 'Dorling2017_4S', 'batterytechnology': 'current'}, {'dronename': 'drone', 'stateofhealth': 100.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 0.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'missionspeed', 'ylabel': 'power', 'title': 'DiFranco', 'simulationtype': 'simple', 'model': 'abdilla', 'xbegin': 0.0, 'xend': 16.0, 'xnumber': 20, 'validation': False, 'validationcase': 'DiFranco2016', 'batterytechnology': 'current'}, {'dronename': 'drone', 'stateofhealth': 100.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 0.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'missionspeed', 'ylabel': 'power', 'title': 'Stolaroff', 'simulationtype': 'simple', 'model': 'abdilla', 'xbegin': 0.0, 'xend': 16.0, 'xnumber': 20, 'validation': False, 'validationcase': 'Chang2016', 'batterytechnology': 'current'}, {'dronename': 'drone', 'stateofhealth': 90.0, 'startstateofcharge': 100.0, 'altitude': 100.0, 'temperaturesealevel': 15.0, 'rain': False, 'dropsize': 0.0, 'liquidwatercontent': 1.0, 'temperature': 15.0, 'wind': False, 'windspeed': 0.0, 'winddirection': 0.0, 'relativehumidity': 0.0, 'icing': False, 'timestep': 1, 'plot': True, 'xlabel': 'payload', 'ylabel': 'endurance', 'title': 'Abdilla 2015 Endurance vs Payload Validation Test', 'simulationtype': 'simple', 'model': 'abdilla', 'xbegin': 0.4, 'xend': 0.55, 'xnumber': 20, 'validation': False, 'validationcase': 'Abdilla2015endurance', 'batterytechnology': 'current'}]
|
__ = "-=> FILL ME IN! <=-"
def assert_equal(expected, actual):
assert expected == actual, '%r == %r' % (expected, actual)
# double quoted strings are strings
string = "Hello, world."
assert_equal(__, isinstance(string, str))
# single quoted strings are also strings
string = 'Goodbye, world.'
assert_equal(__, isinstance(string, str))
# triple quote strings are also strings
string = """Howdy, world!"""
assert_equal(__, isinstance(string, str))
# triple single quotes work too
string = '''Bonjour tout le monde!'''
assert_equal(__, isinstance(string, str))
# raw strings are also strings
string = r"Konnichi wa, world!"
assert_equal(__, isinstance(string, str))
# use single quotes to create string with double quotes
string = 'He said, "Go Away."'
assert_equal(__, string)
# use double quotes to create strings with single quotes
string = "Don't"
assert_equal(__, string)
# use backslash for escaping quotes in strings
a = "He said, \"Don't\""
b = 'He said, "Don\'t"'
assert_equal(__, (a == b))
# use backslash at the end of a line to continue onto the next line
string = "It was the best of times,\n\
as the worst of times."
assert_equal(__, len(string))
# triple quoted strings can span lines
string = """
Howdy,
world!
"""
assert_equal(__, len(string))
# triple quoted strings need less escaping
a = "Hello \"world\"."
b = """Hello "world"."""
assert_equal(__, (a == b))
# escaping quotes at the end of triple quoted string
string = """Hello "world\""""
assert_equal(__, string)
# plus concatenates strings
string = "Hello, " + "world"
assert_equal(__, string)
# adjacent strings are concatenated automatically
string = "Hello" ", " "world"
assert_equal(__, string)
# plus will not modify original strings
hi = "Hello, "
there = "world"
string = hi + there
assert_equal(__, hi)
assert_equal(__, there)
# plus equals will append to end of string
hi = "Hello, "
there = "world"
hi += there
assert_equal(__, hi)
# plus equals also leaves original string unmodified
original = "Hello, "
hi = original
there = "world"
hi += there
assert_equal(__, original)
# most strings interpret escape characters
string = "\n"
assert_equal('\n', string)
assert_equal("""\n""", string)
assert_equal(__, len(string))
# a character in string can be accesses like in list
string = "Hello"
assert_equal(__, string[1])
# you can check weather a character is in string
string = "Hello"
assert_equal(__, 'H' in string)
assert_equal(__, 'Z' in string)
|
__ = '-=> FILL ME IN! <=-'
def assert_equal(expected, actual):
assert expected == actual, '%r == %r' % (expected, actual)
string = 'Hello, world.'
assert_equal(__, isinstance(string, str))
string = 'Goodbye, world.'
assert_equal(__, isinstance(string, str))
string = 'Howdy, world!'
assert_equal(__, isinstance(string, str))
string = 'Bonjour tout le monde!'
assert_equal(__, isinstance(string, str))
string = 'Konnichi wa, world!'
assert_equal(__, isinstance(string, str))
string = 'He said, "Go Away."'
assert_equal(__, string)
string = "Don't"
assert_equal(__, string)
a = 'He said, "Don\'t"'
b = 'He said, "Don\'t"'
assert_equal(__, a == b)
string = 'It was the best of times,\nas the worst of times.'
assert_equal(__, len(string))
string = '\nHowdy,\nworld!\n'
assert_equal(__, len(string))
a = 'Hello "world".'
b = 'Hello "world".'
assert_equal(__, a == b)
string = 'Hello "world"'
assert_equal(__, string)
string = 'Hello, ' + 'world'
assert_equal(__, string)
string = 'Hello, world'
assert_equal(__, string)
hi = 'Hello, '
there = 'world'
string = hi + there
assert_equal(__, hi)
assert_equal(__, there)
hi = 'Hello, '
there = 'world'
hi += there
assert_equal(__, hi)
original = 'Hello, '
hi = original
there = 'world'
hi += there
assert_equal(__, original)
string = '\n'
assert_equal('\n', string)
assert_equal('\n', string)
assert_equal(__, len(string))
string = 'Hello'
assert_equal(__, string[1])
string = 'Hello'
assert_equal(__, 'H' in string)
assert_equal(__, 'Z' in string)
|
"""
>>> nCr(4, 2)
6
"""
def nCr(n, k):
# C = [[0] * (k+1) for i in range(n+1)]
# for i in range(n+1):
# C[i][0] = 1
# for i in range(1, k+1):
# C[0][i] = 0
# for i in range(1, n+1):
# for j in range(1, k+1):
# C[i][j] = C[i-1][j-1] + C[i-1][j]
# return C
C = [0] * (k+1)
C[0] = 1
for i in range(n):
print(i)
C_backup = C[:]
for j in range(1, k+1):
C[j] += C_backup[j-1]
return C[k]
print(nCr(4, 2))
print(nCr(5, 4))
print(nCr(6, 3))
|
"""
>>> nCr(4, 2)
6
"""
def n_cr(n, k):
c = [0] * (k + 1)
C[0] = 1
for i in range(n):
print(i)
c_backup = C[:]
for j in range(1, k + 1):
C[j] += C_backup[j - 1]
return C[k]
print(n_cr(4, 2))
print(n_cr(5, 4))
print(n_cr(6, 3))
|
skip_files = ["Fleece+CoreFoundation.h"]
excluded = ["FLStr","operatorslice","operatorFLSlice","FLMutableArray_Retain","FLMutableArray_Release","FLMutableDict_Retain","FLMutableDict_Release","FLEncoder_NewWritingToFile","FLSliceResult_Free"]
default_param_name = {"FLValue":"value","FLSliceResult":"slice","FLSlice":"slice","FLArray":"array","FLArrayIterator*":"i","FLDictIterator*":"i","FLDict":"dict","FLDictKey":"key","FLKeyPath":"keyPath","FLDictKey*":"dictKey","FLSharedKeys":"shared","FLEncoder":"encoder","long":"l","ulong":"u","bool":"b","float":"f","double":"d","FLError*":"outError","int64_t":"l","uint64_t":"u","FLString":"str","FLStringResult":"str"}
param_bridge_types = ["FLSlice", "FLString", "size_t", "size_t*"]
force_no_bridge = ["FLSlice_Compare", "FLSlice_Equal","FLSliceResult_Retain","FLSliceResult_Release","FLSlice_Copy","FLDoc_FromResultData"]
return_bridge_types = ["FLSliceResult", "FLSlice", "size_t", "FLString", "FLStringResult"]
type_map = {"int32_t":"int","uint32_t":"uint","int64_t":"long","uint64_t":"ulong","size_t":"UIntPtr","size_t*":"UIntPtr*","unsigned":"uint","FLValue":"FLValue*","FLDict":"FLDict*","FLArray":"FLArray*","FLEncoder":"FLEncoder*","FLSharedKeys":"FLSharedKeys*","FLKeyPath":"FLKeyPath*","FLDoc":"FLDoc*","FLDeepIterator":"FLDeepIterator*"}
literals = {"FLSlice_Compare":".nobridge .int FLSlice_Compare FLSlice:left FLSlice:right"}
reserved = ["string","base"]
|
skip_files = ['Fleece+CoreFoundation.h']
excluded = ['FLStr', 'operatorslice', 'operatorFLSlice', 'FLMutableArray_Retain', 'FLMutableArray_Release', 'FLMutableDict_Retain', 'FLMutableDict_Release', 'FLEncoder_NewWritingToFile', 'FLSliceResult_Free']
default_param_name = {'FLValue': 'value', 'FLSliceResult': 'slice', 'FLSlice': 'slice', 'FLArray': 'array', 'FLArrayIterator*': 'i', 'FLDictIterator*': 'i', 'FLDict': 'dict', 'FLDictKey': 'key', 'FLKeyPath': 'keyPath', 'FLDictKey*': 'dictKey', 'FLSharedKeys': 'shared', 'FLEncoder': 'encoder', 'long': 'l', 'ulong': 'u', 'bool': 'b', 'float': 'f', 'double': 'd', 'FLError*': 'outError', 'int64_t': 'l', 'uint64_t': 'u', 'FLString': 'str', 'FLStringResult': 'str'}
param_bridge_types = ['FLSlice', 'FLString', 'size_t', 'size_t*']
force_no_bridge = ['FLSlice_Compare', 'FLSlice_Equal', 'FLSliceResult_Retain', 'FLSliceResult_Release', 'FLSlice_Copy', 'FLDoc_FromResultData']
return_bridge_types = ['FLSliceResult', 'FLSlice', 'size_t', 'FLString', 'FLStringResult']
type_map = {'int32_t': 'int', 'uint32_t': 'uint', 'int64_t': 'long', 'uint64_t': 'ulong', 'size_t': 'UIntPtr', 'size_t*': 'UIntPtr*', 'unsigned': 'uint', 'FLValue': 'FLValue*', 'FLDict': 'FLDict*', 'FLArray': 'FLArray*', 'FLEncoder': 'FLEncoder*', 'FLSharedKeys': 'FLSharedKeys*', 'FLKeyPath': 'FLKeyPath*', 'FLDoc': 'FLDoc*', 'FLDeepIterator': 'FLDeepIterator*'}
literals = {'FLSlice_Compare': '.nobridge .int FLSlice_Compare FLSlice:left FLSlice:right'}
reserved = ['string', 'base']
|
"""This application overrides to django-machina's forum_conversation app."""
# pylint: disable=invalid-name
default_app_config = (
"ashley.machina_extensions.forum_conversation.apps.ForumConversationAppConfig"
)
|
"""This application overrides to django-machina's forum_conversation app."""
default_app_config = 'ashley.machina_extensions.forum_conversation.apps.ForumConversationAppConfig'
|
# [351] Android Unlock Patterns
# Description
# Given an Android 3x3 key lock screen and two integers m and n, where 1 <= m <= n <= 9,
# count the total number of unlock patterns of the Android lock screen, which consist
# of minimum of m keys and maximum n keys.
# Rules for a valid pattern:
# 1) Each pattern must connect at least m keys and at most n keys.
# 2) All the keys must be distinct.
# 3) If the line connecting two consecutive keys in the pattern passes through any other keys,
# the other keys must have previously selected in the pattern. No jumps through non selected key is allowed.
# 4) The order of keys used matters.
# Explanation:
# | 1 | 2 | 3 |
# | 4 | 5 | 6 |
# | 7 | 8 | 9 |
# Invalid move: 4 - 1 - 3 - 6
# Line 1 - 3 passes through key 2 which had not been selected in the pattern.
# Invalid move: 4 - 1 - 9 - 2
# Line 1 - 9 passes through key 5 which had not been selected in the pattern.
# Valid move: 2 - 4 - 1 - 3 - 6
# Line 1 - 3 is valid because it passes through key 2, which had been selected in the pattern
# Valid move: 6 - 5 - 4 - 1 - 9 - 2
# Line 1 - 9 is valid because it passes through key 5, which had been selected in the pattern.
# Example
# Example 1
# Input: m = 1, n = 1
# Output: 9
# Example 2
# Input: m = 1, n = 2
# Output: 65
class Solution:
"""
@param m: an integer
@param n: an integer
@return: the total number of unlock patterns of the Android lock screen
"""
def __init__(self):
self.count = 0
self.res = []
self.corners = [[0,0], [0,2], [2,0], [2, 2]]
def numberOfPatterns(self, m, n):
# Write your code here
nums = [i for i in range(9)]
self.dfs(m, n, [], 0, nums)
# for res in self.res:
# print(res)
return self.count
def dfs(self, m, n, curr, start, nums):
if len(curr) > n:
return
if m <= len(curr) <= n:
self.count += 1
self.res.append(curr[:])
for i in range(start, len(nums)):
if nums[i] not in curr:
curr.append(nums[i])
if self.valid(curr):
self.dfs(m, n, curr, 0, nums)
curr.pop()
def valid(self, points):
prev_x, prev_y = points[0] // 3, points[0] % 3
record = set([(prev_x, prev_y)])
for i in range(1, len(points)):
x, y = points[i] // 3, points[i] % 3
if not ( (abs(x - prev_x) == 1 and abs(y - prev_y) == 0) \
or (abs(x - prev_x) == 0 and abs(y - prev_y) == 1) \
or (abs(x - prev_x) == 1 and abs(y - prev_y) == 1) \
or (abs(x - prev_x) == 1 and abs(y - prev_y) == 2) \
or (abs(x - prev_x) == 2 and abs(y - prev_y) == 1) ):
if (abs(x - prev_x) == 0 and abs(y - prev_y) == 2):
if (x, max(y, prev_y) - 1) not in record:
return False
if (abs(x - prev_x) == 2 and abs(y - prev_y) == 0):
if (max(x, prev_x) - 1, y) not in record:
return False
if x + y == prev_x + prev_y or x - y == prev_x - prev_y:
if (1, 1) not in record:
return False
record.add((x, y))
prev_x, prev_y = x, y
return True
|
class Solution:
"""
@param m: an integer
@param n: an integer
@return: the total number of unlock patterns of the Android lock screen
"""
def __init__(self):
self.count = 0
self.res = []
self.corners = [[0, 0], [0, 2], [2, 0], [2, 2]]
def number_of_patterns(self, m, n):
nums = [i for i in range(9)]
self.dfs(m, n, [], 0, nums)
return self.count
def dfs(self, m, n, curr, start, nums):
if len(curr) > n:
return
if m <= len(curr) <= n:
self.count += 1
self.res.append(curr[:])
for i in range(start, len(nums)):
if nums[i] not in curr:
curr.append(nums[i])
if self.valid(curr):
self.dfs(m, n, curr, 0, nums)
curr.pop()
def valid(self, points):
(prev_x, prev_y) = (points[0] // 3, points[0] % 3)
record = set([(prev_x, prev_y)])
for i in range(1, len(points)):
(x, y) = (points[i] // 3, points[i] % 3)
if not (abs(x - prev_x) == 1 and abs(y - prev_y) == 0 or (abs(x - prev_x) == 0 and abs(y - prev_y) == 1) or (abs(x - prev_x) == 1 and abs(y - prev_y) == 1) or (abs(x - prev_x) == 1 and abs(y - prev_y) == 2) or (abs(x - prev_x) == 2 and abs(y - prev_y) == 1)):
if abs(x - prev_x) == 0 and abs(y - prev_y) == 2:
if (x, max(y, prev_y) - 1) not in record:
return False
if abs(x - prev_x) == 2 and abs(y - prev_y) == 0:
if (max(x, prev_x) - 1, y) not in record:
return False
if x + y == prev_x + prev_y or x - y == prev_x - prev_y:
if (1, 1) not in record:
return False
record.add((x, y))
(prev_x, prev_y) = (x, y)
return True
|
# SPDX-License-Identifier: BSD-3-Clause
# Copyright Contributors to the OpenColorIO Project.
class GroupTransform:
"""
GroupTransform
"""
def __init__(self):
pass
def getTransform(self, index):
pass
def getNumTransforms(self):
pass
def appendTransform(self, transform):
pass
|
class Grouptransform:
"""
GroupTransform
"""
def __init__(self):
pass
def get_transform(self, index):
pass
def get_num_transforms(self):
pass
def append_transform(self, transform):
pass
|
'''
Created on 27 Aug 2010
@author: dev
solr configurations
'''
solr_base_url = "http://solr:8983/solr/"
solr_urls = {
'all' : solr_base_url + 'all',
'locations' : solr_base_url + 'locations',
'comments' : solr_base_url + 'comments',
'images' : solr_base_url + 'images',
'works' : solr_base_url + 'works',
'people' : solr_base_url + 'people',
'manifestations' : solr_base_url + 'manifestations',
'institutions' : solr_base_url + 'institutions',
'resources' : solr_base_url + 'resources',
}
solr_urls_stage = {
'all' : solr_base_url + 'all_stage',
'locations' : solr_base_url + 'locations_stage',
'comments' : solr_base_url + 'comments_stage',
'images' : solr_base_url + 'images_stage',
'works' : solr_base_url + 'works_stage',
'people' : solr_base_url + 'people_stage',
'manifestations' : solr_base_url + 'manifestations_stage',
'institutions' : solr_base_url + 'institutions_stage',
'resources' : solr_base_url + 'resources_stage',
}
|
"""
Created on 27 Aug 2010
@author: dev
solr configurations
"""
solr_base_url = 'http://solr:8983/solr/'
solr_urls = {'all': solr_base_url + 'all', 'locations': solr_base_url + 'locations', 'comments': solr_base_url + 'comments', 'images': solr_base_url + 'images', 'works': solr_base_url + 'works', 'people': solr_base_url + 'people', 'manifestations': solr_base_url + 'manifestations', 'institutions': solr_base_url + 'institutions', 'resources': solr_base_url + 'resources'}
solr_urls_stage = {'all': solr_base_url + 'all_stage', 'locations': solr_base_url + 'locations_stage', 'comments': solr_base_url + 'comments_stage', 'images': solr_base_url + 'images_stage', 'works': solr_base_url + 'works_stage', 'people': solr_base_url + 'people_stage', 'manifestations': solr_base_url + 'manifestations_stage', 'institutions': solr_base_url + 'institutions_stage', 'resources': solr_base_url + 'resources_stage'}
|
def clean_version(
version: str,
*,
build: bool = False,
patch: bool = False,
commit: bool = False,
drop_v: bool = False,
flat: bool = False,
):
"Clean up and transform the many flavours of versions"
# 'v1.13.0-103-gb137d064e' --> 'v1.13-103'
if version in ["", "-"]:
return version
nibbles = version.split("-")
if not patch:
if nibbles[0] >= "1.10.0" and nibbles[0].endswith(".0"):
# remove the last ".0"
nibbles[0] = nibbles[0][0:-2]
if len(nibbles) == 1:
version = nibbles[0]
elif build and build != "dirty":
if not commit:
version = "-".join(nibbles[0:-1])
else:
version = "-".join(nibbles)
else:
# version = "-".join((nibbles[0], LATEST))
# HACK: this is not always right, but good enough most of the time
version = "latest"
if flat:
version = version.strip().replace(".", "_")
if drop_v:
version = version.lstrip("v")
else:
# prefix with `v` but not before latest
if not version.startswith("v") and version.lower() != "latest":
version = "v" + version
return version
|
def clean_version(version: str, *, build: bool=False, patch: bool=False, commit: bool=False, drop_v: bool=False, flat: bool=False):
"""Clean up and transform the many flavours of versions"""
if version in ['', '-']:
return version
nibbles = version.split('-')
if not patch:
if nibbles[0] >= '1.10.0' and nibbles[0].endswith('.0'):
nibbles[0] = nibbles[0][0:-2]
if len(nibbles) == 1:
version = nibbles[0]
elif build and build != 'dirty':
if not commit:
version = '-'.join(nibbles[0:-1])
else:
version = '-'.join(nibbles)
else:
version = 'latest'
if flat:
version = version.strip().replace('.', '_')
if drop_v:
version = version.lstrip('v')
elif not version.startswith('v') and version.lower() != 'latest':
version = 'v' + version
return version
|
print("Insert an in integer")
n = input()
nn = n + n
nnn = nn + n
result = int(n) + int(nn) + int(nnn)
print(result)
|
print('Insert an in integer')
n = input()
nn = n + n
nnn = nn + n
result = int(n) + int(nn) + int(nnn)
print(result)
|
"""
Metaclass of Response and Request
"""
class ResponseMeta(type):
"""
Meta class of Response
"""
response_class_by_response_type = {}
@classmethod
def register(mcs, clazz, typez):
"""
register son class to response_class_by_response_type
:param clazz: son class
:param typez: son class type
:return: None
"""
mcs.response_class_by_response_type[typez] = clazz
def __new__(mcs, name, base, attrs):
clazz = super().__new__(mcs, name, base, attrs)
if name not in ['Response', 'ResendResponse']:
mcs.register(clazz, attrs['TYPE'])
return clazz
class RequestMeta(type):
"""
Meta class of Request
"""
response_class_by_response_type = {}
@classmethod
def register(mcs, clazz, typez):
"""
register son class to response_class_by_response_type
:param clazz: son class
:param typez: son class type
:return: None
"""
mcs.response_class_by_response_type[typez] = clazz
def __new__(mcs, name, base, attrs):
clazz = super().__new__(mcs, name, base, attrs)
if name not in ['Request']:
mcs.register(clazz, attrs['TYPE'])
return clazz
|
"""
Metaclass of Response and Request
"""
class Responsemeta(type):
"""
Meta class of Response
"""
response_class_by_response_type = {}
@classmethod
def register(mcs, clazz, typez):
"""
register son class to response_class_by_response_type
:param clazz: son class
:param typez: son class type
:return: None
"""
mcs.response_class_by_response_type[typez] = clazz
def __new__(mcs, name, base, attrs):
clazz = super().__new__(mcs, name, base, attrs)
if name not in ['Response', 'ResendResponse']:
mcs.register(clazz, attrs['TYPE'])
return clazz
class Requestmeta(type):
"""
Meta class of Request
"""
response_class_by_response_type = {}
@classmethod
def register(mcs, clazz, typez):
"""
register son class to response_class_by_response_type
:param clazz: son class
:param typez: son class type
:return: None
"""
mcs.response_class_by_response_type[typez] = clazz
def __new__(mcs, name, base, attrs):
clazz = super().__new__(mcs, name, base, attrs)
if name not in ['Request']:
mcs.register(clazz, attrs['TYPE'])
return clazz
|
# ______________________________________________________________________________
# The Wumpus World
class Gold(Thing):
def __eq__(self, rhs):
'''All Gold are equal'''
return rhs.__class__ == Gold
pass
class Bump(Thing):
pass
class Glitter(Thing):
pass
class Pit(Thing):
pass
class Breeze(Thing):
pass
class Arrow(Thing):
pass
class Scream(Thing):
pass
class Wumpus(Agent):
screamed = False
pass
class Stench(Thing):
pass
class Explorer(Agent):
holding = []
has_arrow = True
killed_by = ""
direction = Direction("right")
def can_grab(self, thing):
'''Explorer can only grab gold'''
return thing.__class__ == Gold
class WumpusEnvironment(XYEnvironment):
pit_probability = 0.2 #Probability to spawn a pit in a location. (From Chapter 7.2)
#Room should be 4x4 grid of rooms. The extra 2 for walls
def __init__(self, agent_program, width=6, height=6):
super(WumpusEnvironment, self).__init__(width, height)
self.init_world(agent_program)
def init_world(self, program):
'''Spawn items to the world based on probabilities from the book'''
"WALLS"
self.add_walls()
"PITS"
for x in range(self.x_start, self.x_end):
for y in range(self.y_start, self.y_end):
if random.random() < self.pit_probability:
self.add_thing(Pit(), (x,y), True)
self.add_thing(Breeze(), (x - 1,y), True)
self.add_thing(Breeze(), (x,y - 1), True)
self.add_thing(Breeze(), (x + 1,y), True)
self.add_thing(Breeze(), (x,y + 1), True)
"WUMPUS"
w_x, w_y = self.random_location_inbounds(exclude = (1,1))
self.add_thing(Wumpus(lambda x: ""), (w_x, w_y), True)
self.add_thing(Stench(), (w_x - 1, w_y), True)
self.add_thing(Stench(), (w_x + 1, w_y), True)
self.add_thing(Stench(), (w_x, w_y - 1), True)
self.add_thing(Stench(), (w_x, w_y + 1), True)
"GOLD"
self.add_thing(Gold(), self.random_location_inbounds(exclude = (1,1)), True)
#self.add_thing(Gold(), (2,1), True) Making debugging a whole lot easier
"AGENT"
self.add_thing(Explorer(program), (1,1), True)
def get_world(self, show_walls = True):
'''returns the items in the world'''
result = []
x_start,y_start = (0,0) if show_walls else (1,1)
x_end,y_end = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x,y)))
result.append(row)
return result
def percepts_from(self, agent, location, tclass = Thing):
'''Returns percepts from a given location, and replaces some items with percepts from chapter 7.'''
thing_percepts = {
Gold: Glitter(),
Wall: Bump(),
Wumpus: Stench(),
Pit: Breeze()
}
'''Agents don't need to get their percepts'''
thing_percepts[agent.__class__] = None
'''Gold only glitters in its cell'''
if location != agent.location:
thing_percepts[Gold] = None
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things
if thing.location == location and isinstance(thing, tclass)]
return result if len(result) else [None]
def percept(self, agent):
'''Returns things in adjacent (not diagonal) cells of the agent.
Result format: [Left, Right, Up, Down, Center / Current location]'''
x,y = agent.location
result = []
result.append(self.percepts_from(agent, (x - 1,y)))
result.append(self.percepts_from(agent, (x + 1,y)))
result.append(self.percepts_from(agent, (x,y - 1)))
result.append(self.percepts_from(agent, (x,y + 1)))
result.append(self.percepts_from(agent, (x,y)))
'''The wumpus gives out a a loud scream once it's killed.'''
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
if len(wumpus) and not wumpus[0].alive and not wumpus[0].screamed:
result[-1].append(Scream())
wumpus[0].screamed = True
return result
def execute_action(self, agent, action):
'''Modify the state of the environment based on the agent's actions
Performance score taken directly out of the book'''
if isinstance(agent, Explorer) and self.in_danger(agent):
return
agent.bump = False
if action == 'TurnRight':
agent.direction = agent.direction + Direction.R
agent.performance -= 1
elif action == 'TurnLeft':
agent.direction = agent.direction + Direction.L
agent.performance -= 1
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
agent.performance -= 1
elif action == 'Grab':
things = [thing for thing in self.list_things_at(agent.location)
if agent.can_grab(thing)]
if len(things):
print("Grabbing", things[0].__class__.__name__)
if len(things):
agent.holding.append(things[0])
agent.performance -= 1
elif action == 'Climb':
if agent.location == (1,1): #Agent can only climb out of (1,1)
agent.performance += 1000 if Gold() in agent.holding else 0
self.delete_thing(agent)
elif action == 'Shoot':
'''The arrow travels straight down the path the agent is facing'''
if agent.has_arrow:
arrow_travel = agent.direction.move_forward(agent.location)
while(self.is_inbounds(arrow_travel)):
wumpus = [thing for thing in self.list_things_at(arrow_travel)
if isinstance(thing, Wumpus)]
if len(wumpus):
wumpus[0].alive = False
break
arrow_travel = agent.direction.move_forward(agent.location)
agent.has_arrow = False
def in_danger(self, agent):
'''Checks if Explorer is in danger (Pit or Wumpus), if he is, kill him'''
for thing in self.list_things_at(agent.location):
if isinstance(thing, Pit) or (isinstance(thing, Wumpus) and thing.alive):
agent.alive = False
agent.performance -= 1000
agent.killed_by = thing.__class__.__name__
return True
return False
def is_done(self):
'''The game is over when the Explorer is killed
or if he climbs out of the cave only at (1,1)'''
explorer = [agent for agent in self.agents if isinstance(agent, Explorer) ]
if len(explorer):
if explorer[0].alive:
return False
else:
print("Death by {} [-1000].".format(explorer[0].killed_by))
else:
print("Explorer climbed out {}."
.format("with Gold [+1000]!" if Gold() not in self.things else "without Gold [+0]"))
return True
#Almost done. Arrow needs to be implemented
|
class Gold(Thing):
def __eq__(self, rhs):
"""All Gold are equal"""
return rhs.__class__ == Gold
pass
class Bump(Thing):
pass
class Glitter(Thing):
pass
class Pit(Thing):
pass
class Breeze(Thing):
pass
class Arrow(Thing):
pass
class Scream(Thing):
pass
class Wumpus(Agent):
screamed = False
pass
class Stench(Thing):
pass
class Explorer(Agent):
holding = []
has_arrow = True
killed_by = ''
direction = direction('right')
def can_grab(self, thing):
"""Explorer can only grab gold"""
return thing.__class__ == Gold
class Wumpusenvironment(XYEnvironment):
pit_probability = 0.2
def __init__(self, agent_program, width=6, height=6):
super(WumpusEnvironment, self).__init__(width, height)
self.init_world(agent_program)
def init_world(self, program):
"""Spawn items to the world based on probabilities from the book"""
'WALLS'
self.add_walls()
'PITS'
for x in range(self.x_start, self.x_end):
for y in range(self.y_start, self.y_end):
if random.random() < self.pit_probability:
self.add_thing(pit(), (x, y), True)
self.add_thing(breeze(), (x - 1, y), True)
self.add_thing(breeze(), (x, y - 1), True)
self.add_thing(breeze(), (x + 1, y), True)
self.add_thing(breeze(), (x, y + 1), True)
'WUMPUS'
(w_x, w_y) = self.random_location_inbounds(exclude=(1, 1))
self.add_thing(wumpus(lambda x: ''), (w_x, w_y), True)
self.add_thing(stench(), (w_x - 1, w_y), True)
self.add_thing(stench(), (w_x + 1, w_y), True)
self.add_thing(stench(), (w_x, w_y - 1), True)
self.add_thing(stench(), (w_x, w_y + 1), True)
'GOLD'
self.add_thing(gold(), self.random_location_inbounds(exclude=(1, 1)), True)
'AGENT'
self.add_thing(explorer(program), (1, 1), True)
def get_world(self, show_walls=True):
"""returns the items in the world"""
result = []
(x_start, y_start) = (0, 0) if show_walls else (1, 1)
(x_end, y_end) = (self.width, self.height) if show_walls else (self.width - 1, self.height - 1)
for x in range(x_start, x_end):
row = []
for y in range(y_start, y_end):
row.append(self.list_things_at((x, y)))
result.append(row)
return result
def percepts_from(self, agent, location, tclass=Thing):
"""Returns percepts from a given location, and replaces some items with percepts from chapter 7."""
thing_percepts = {Gold: glitter(), Wall: bump(), Wumpus: stench(), Pit: breeze()}
"Agents don't need to get their percepts"
thing_percepts[agent.__class__] = None
'Gold only glitters in its cell'
if location != agent.location:
thing_percepts[Gold] = None
result = [thing_percepts.get(thing.__class__, thing) for thing in self.things if thing.location == location and isinstance(thing, tclass)]
return result if len(result) else [None]
def percept(self, agent):
"""Returns things in adjacent (not diagonal) cells of the agent.
Result format: [Left, Right, Up, Down, Center / Current location]"""
(x, y) = agent.location
result = []
result.append(self.percepts_from(agent, (x - 1, y)))
result.append(self.percepts_from(agent, (x + 1, y)))
result.append(self.percepts_from(agent, (x, y - 1)))
result.append(self.percepts_from(agent, (x, y + 1)))
result.append(self.percepts_from(agent, (x, y)))
"The wumpus gives out a a loud scream once it's killed."
wumpus = [thing for thing in self.things if isinstance(thing, Wumpus)]
if len(wumpus) and (not wumpus[0].alive) and (not wumpus[0].screamed):
result[-1].append(scream())
wumpus[0].screamed = True
return result
def execute_action(self, agent, action):
"""Modify the state of the environment based on the agent's actions
Performance score taken directly out of the book"""
if isinstance(agent, Explorer) and self.in_danger(agent):
return
agent.bump = False
if action == 'TurnRight':
agent.direction = agent.direction + Direction.R
agent.performance -= 1
elif action == 'TurnLeft':
agent.direction = agent.direction + Direction.L
agent.performance -= 1
elif action == 'Forward':
agent.bump = self.move_to(agent, agent.direction.move_forward(agent.location))
agent.performance -= 1
elif action == 'Grab':
things = [thing for thing in self.list_things_at(agent.location) if agent.can_grab(thing)]
if len(things):
print('Grabbing', things[0].__class__.__name__)
if len(things):
agent.holding.append(things[0])
agent.performance -= 1
elif action == 'Climb':
if agent.location == (1, 1):
agent.performance += 1000 if gold() in agent.holding else 0
self.delete_thing(agent)
elif action == 'Shoot':
'The arrow travels straight down the path the agent is facing'
if agent.has_arrow:
arrow_travel = agent.direction.move_forward(agent.location)
while self.is_inbounds(arrow_travel):
wumpus = [thing for thing in self.list_things_at(arrow_travel) if isinstance(thing, Wumpus)]
if len(wumpus):
wumpus[0].alive = False
break
arrow_travel = agent.direction.move_forward(agent.location)
agent.has_arrow = False
def in_danger(self, agent):
"""Checks if Explorer is in danger (Pit or Wumpus), if he is, kill him"""
for thing in self.list_things_at(agent.location):
if isinstance(thing, Pit) or (isinstance(thing, Wumpus) and thing.alive):
agent.alive = False
agent.performance -= 1000
agent.killed_by = thing.__class__.__name__
return True
return False
def is_done(self):
"""The game is over when the Explorer is killed
or if he climbs out of the cave only at (1,1)"""
explorer = [agent for agent in self.agents if isinstance(agent, Explorer)]
if len(explorer):
if explorer[0].alive:
return False
else:
print('Death by {} [-1000].'.format(explorer[0].killed_by))
else:
print('Explorer climbed out {}.'.format('with Gold [+1000]!' if gold() not in self.things else 'without Gold [+0]'))
return True
|
"""2019 Advent of Code, Day 1"""
with open("input", "r+") as file:
puzzle_input = file.readlines()
def mass(item):
"""Calculate the fuel required for an item, and the fuel required for that fuel, and so on"""
fuel = item // 3 - 2
if fuel < 0:
return 0
return fuel + mass(fuel)
SUM = 0
SUM_2 = 0
for module in puzzle_input:
SUM += int(module) // 3 - 2
SUM_2 += mass(int(module))
print(SUM, SUM_2)
|
"""2019 Advent of Code, Day 1"""
with open('input', 'r+') as file:
puzzle_input = file.readlines()
def mass(item):
"""Calculate the fuel required for an item, and the fuel required for that fuel, and so on"""
fuel = item // 3 - 2
if fuel < 0:
return 0
return fuel + mass(fuel)
sum = 0
sum_2 = 0
for module in puzzle_input:
sum += int(module) // 3 - 2
sum_2 += mass(int(module))
print(SUM, SUM_2)
|
class Command(object):
"""
By using the NAMES command, a user can list all nicknames that are
visible to him. For more details on what is visible and what is not,
see "Internet Relay Chat: Channel Management" [IRC-CHAN]. The
<channel> parameter specifies which channel(s) to return information
about. There is no error reply for bad channel names.
If no <channel> parameter is given, a list of all channels and their
occupants is returned. At the end of this list, a list of users who
are visible but either not on any channel or not on a visible channel
are listed as being on `channel' "*".
If the <target> parameter is specified, the request is forwarded to
that server which will generate the reply.
Wildcards are allowed in the <target> parameter.
Numerics:
ERR_TOOMANYMATCHES ERR_NOSUCHSERVER
RPL_NAMREPLY RPL_ENDOFNAMES
Examples:
NAMES #twilight_zone,#42 ; Command to list visible users on
#twilight_zone and #42
NAMES ; Command to list all visible
channels and users
"""
@staticmethod
def can_names(server, client, channel=None):
pass
"""
<- :gunslinger.shadowfire.org 353 kevin = #gopugs :kevin Sven fragtion FlaMeBeRg @GameBot ~@Russ!
<- :gunslinger.shadowfire.org 353 kevin = #gopugs :Lithium!~AndrewMoh@SF-3740E9DA.andrewmohawk.com Webtricity!web@staff.shadowfire.org
"""
@staticmethod
def on_names(server, client, channel=None):
chan = server.get_channel(channel)
# Send end of list
if not channel or not chan:
client.send_366("*")
return
# Send channel with empty users.
if client not in chan.users:
client.send_353(channel, [])
client.send_366(channel)
return
# Send proper names list now. Split into lists of max 6 users
users = chan.users
temp = []
for user in users:
temp.append(user.hostmask)
if len(temp) == 6:
client.send_353(channel, temp)
temp = []
client.send_353(channel, temp)
client.send_366(channel)
|
class Command(object):
"""
By using the NAMES command, a user can list all nicknames that are
visible to him. For more details on what is visible and what is not,
see "Internet Relay Chat: Channel Management" [IRC-CHAN]. The
<channel> parameter specifies which channel(s) to return information
about. There is no error reply for bad channel names.
If no <channel> parameter is given, a list of all channels and their
occupants is returned. At the end of this list, a list of users who
are visible but either not on any channel or not on a visible channel
are listed as being on `channel' "*".
If the <target> parameter is specified, the request is forwarded to
that server which will generate the reply.
Wildcards are allowed in the <target> parameter.
Numerics:
ERR_TOOMANYMATCHES ERR_NOSUCHSERVER
RPL_NAMREPLY RPL_ENDOFNAMES
Examples:
NAMES #twilight_zone,#42 ; Command to list visible users on
#twilight_zone and #42
NAMES ; Command to list all visible
channels and users
"""
@staticmethod
def can_names(server, client, channel=None):
pass
'\n <- :gunslinger.shadowfire.org 353 kevin = #gopugs :kevin Sven fragtion FlaMeBeRg @GameBot ~@Russ!\n<- :gunslinger.shadowfire.org 353 kevin = #gopugs :Lithium!~AndrewMoh@SF-3740E9DA.andrewmohawk.com Webtricity!web@staff.shadowfire.org\n '
@staticmethod
def on_names(server, client, channel=None):
chan = server.get_channel(channel)
if not channel or not chan:
client.send_366('*')
return
if client not in chan.users:
client.send_353(channel, [])
client.send_366(channel)
return
users = chan.users
temp = []
for user in users:
temp.append(user.hostmask)
if len(temp) == 6:
client.send_353(channel, temp)
temp = []
client.send_353(channel, temp)
client.send_366(channel)
|
print(divmod(100, 7))
print(7 > 2 and 1 > 6)
print(7 > 2 or 1 > 6)
number_list = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
print(number_list[2:8])
print(number_list[0:9:3])
print(number_list[0:10:3])
|
print(divmod(100, 7))
print(7 > 2 and 1 > 6)
print(7 > 2 or 1 > 6)
number_list = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
print(number_list[2:8])
print(number_list[0:9:3])
print(number_list[0:10:3])
|
# https://docs.python.org/3/library/functions.html#built-in-functions
my_results = [True, True, 2*2==4, True]
print(all(my_results)) # all statements in the sequence should be truthy to get True else we get False
my_results.append(False)
print(my_results)
print(all(my_results)) #In logic this is called universal quantor, all my)_results must be truthy for all to return True
print(any(my_results)) # any just needs one true result inside, existences kvantors, one or more items are true
print(len(my_results))
my_results.append(9000)
print("max", max(my_results)) # we only have 1 or 0 in my_results
my_results.append(-30)
print(my_results)
print("min", min(my_results))
print("summa", sum(my_results)) # well when summing booleans True is 1 and False is 0
# print(min(my_results))
|
my_results = [True, True, 2 * 2 == 4, True]
print(all(my_results))
my_results.append(False)
print(my_results)
print(all(my_results))
print(any(my_results))
print(len(my_results))
my_results.append(9000)
print('max', max(my_results))
my_results.append(-30)
print(my_results)
print('min', min(my_results))
print('summa', sum(my_results))
|
#!/usr/bin/env pyrate
build_output = ['makefile']
ex_d = executable('exampleM2_debug.bin', 'test.cpp foo.cpp', compiler_opts = '-O0')
ex_r = executable('exampleM2_release.bin', 'test.cpp foo.cpp', compiler_opts = '-O3')
default_targets = ex_r
|
build_output = ['makefile']
ex_d = executable('exampleM2_debug.bin', 'test.cpp foo.cpp', compiler_opts='-O0')
ex_r = executable('exampleM2_release.bin', 'test.cpp foo.cpp', compiler_opts='-O3')
default_targets = ex_r
|
class DescriptionError(Exception):
pass
class ParseError(DescriptionError):
pass
class GettingError(DescriptionError):
pass
|
class Descriptionerror(Exception):
pass
class Parseerror(DescriptionError):
pass
class Gettingerror(DescriptionError):
pass
|
MyAttr = 'eval:1'
My_Attr = 'eval:foo=1;bar=2;foo+bar'
attr_1 = 'tango:a/b/c/d'
attr_2 = 'a/b/c/d'
attr1 = 'eval:"Hello_World!!"'
foo = 'eval:/@Foo/True'
# 1foo = 'eval:2'
Foo = 'eval:False'
res_attr = 'res:attr1'
dev1 = 'tango:a/b/c' # invalid for attribute
dev2 = 'eval:@foo' # invalid for attribute
|
my_attr = 'eval:1'
my__attr = 'eval:foo=1;bar=2;foo+bar'
attr_1 = 'tango:a/b/c/d'
attr_2 = 'a/b/c/d'
attr1 = 'eval:"Hello_World!!"'
foo = 'eval:/@Foo/True'
foo = 'eval:False'
res_attr = 'res:attr1'
dev1 = 'tango:a/b/c'
dev2 = 'eval:@foo'
|
# Program to input a number and find it's sum of digits
n = int(input("Enter the number: "))
tot = 0
while(n>0):
d = n%10
tot = tot+d
n=n//10
print("Sum of Digits is:",tot)
|
n = int(input('Enter the number: '))
tot = 0
while n > 0:
d = n % 10
tot = tot + d
n = n // 10
print('Sum of Digits is:', tot)
|
def func():
print("func() in one.py")
print("TOP LEVEL ONE.PY")
if __name__ == "__main__":
print("one.py is being run directly")
else:
print("one.py has been imported")
|
def func():
print('func() in one.py')
print('TOP LEVEL ONE.PY')
if __name__ == '__main__':
print('one.py is being run directly')
else:
print('one.py has been imported')
|
class NessusObject(object):
def __init__(self, server):
self._id = None
self._server = server
def save(self):
if self._id is None:
return getattr(self._server, "create_%s" % self.__class__.__name__.lower())(self)
else:
return getattr(self._server, "update_%s" % self.__class__.__name__.lower())(self)
def delete(self):
if self._id is not None:
return getattr(self._server, "delete_%s" % self.__class__.__name__.lower())(self)
@property
def id(self):
return self._id
@id.setter
def id(self, _id):
self._id = _id
|
class Nessusobject(object):
def __init__(self, server):
self._id = None
self._server = server
def save(self):
if self._id is None:
return getattr(self._server, 'create_%s' % self.__class__.__name__.lower())(self)
else:
return getattr(self._server, 'update_%s' % self.__class__.__name__.lower())(self)
def delete(self):
if self._id is not None:
return getattr(self._server, 'delete_%s' % self.__class__.__name__.lower())(self)
@property
def id(self):
return self._id
@id.setter
def id(self, _id):
self._id = _id
|
#Find structs by field type.
#@author Rena
#@category Struct
#@keybinding
#@menupath
#@toolbar
StringColumnDisplay = ghidra.app.tablechooser.StringColumnDisplay
AddressableRowObject = ghidra.app.tablechooser.AddressableRowObject
TableChooserExecutor = ghidra.app.tablechooser.TableChooserExecutor
DTM = state.tool.getService(ghidra.app.services.DataTypeManagerService)
AF = currentProgram.getAddressFactory()
DT = currentProgram.getDataTypeManager()
listing = currentProgram.getListing()
mem = currentProgram.getMemory()
def addrToInt(addr):
return int(str(addr), 16)
def intToAddr(addr):
return AF.getAddress("0x%08X" % addr)
class Executor(TableChooserExecutor):
def getButtonName(self):
return "Edit Structure"
def execute(self, row):
DTM.edit(row.struc) # show the structure editor
return False # do not remove row
class StructNameColumn(StringColumnDisplay):
def getColumnName(self):
return "Struct Name"
def getColumnValue(self, row):
return row.struc.displayName
class StructLengthColumn(StringColumnDisplay):
def getColumnName(self):
return "Struct Size"
def getColumnValue(self, row):
return row.struc.length
class StructListResult(AddressableRowObject):
def __init__(self, struc):
self.struc = struc
def getAddress(self):
return intToAddr(self.struc.length)
def run():
# XXX find a way to make this UI better.
# criteria is eg:
# B8=*int (a struct with an int* at 0xB8)
# B8=* (a struct with any pointer at 0xB8)
# B8=2 (a struct with any field at 0xB8 with length 2)
# B8=*2 (a struct with a pointer at 0xB8 to something with length 2)
# B8 (a struct with any field starting at 0xB8)
params = askString("Find Struct", "Enter search criteria")
params = params.split(';')
monitor.initialize(len(params))
candidates = list(DT.allStructures)
def showResults():
executor = Executor()
tbl = createTableChooserDialog("Matching Structs", executor)
tbl.addCustomColumn(StructNameColumn())
tbl.addCustomColumn(StructLengthColumn())
#printf("show %d results\n", len(candidates))
for res in candidates:
#printf("%s\n", res.displayName)
tbl.add(StructListResult(res))
tbl.show()
tbl.setMessage("%d results" % len(candidates))
def removeResult(struc):
candidates.remove(struc)
#print("remove", struc.name, "#res", len(candidates))
def checkComponent(struc, comp, offset, typ):
# return True if match, False if not.
# does component match given offset/type?
if comp.offset != offset: return False
if typ is None: return True # match any type at this offset
# if this is a pointer, walk the dataType chain
# to reach the base type
tp = typ
dt = comp.dataType
while tp.startswith('*'):
if (not hasattr(dt, 'dataType')) or dt.dataType is None:
#printf("[X] %s.%s @%X type is %s\n", struc.name,
# comp.fieldName, offset, str(getattr(dt, 'dataType')))
return False
dt = dt.dataType
tp = tp[1:]
# check the name
# remove spaces for simplicity
tp = tp.replace(' ', '')
nm = dt.name.replace(' ', '')
if tp.isnumeric():
#printf("[%s] %s.%s @%X size is %d\n",
# "O" if dt.length == int(tp) else "X",
# struc.name, comp.fieldName, offset, dt.length)
if dt.length == int(tp):
return True
else:
#printf("[%s] %s.%s @%X type is %d\n",
# "O" if nm == tp else "X",
# struc.name, comp.fieldName, offset, dt.length)
if nm == tp:
return True
#comp.dataType.name, numElements, elementLength, length, dataType
#comp.fieldName, comment, endOffset, bitFieldComponent, dataType, length, offset, ordinal
return False
def evaluateParam(param):
param = param.split('=')
offset = int(param[0], 16)
if len(param) < 2:
# no type given - find any struct which has a field
# beginning at this offset.
typ = None
else:
# user specified a type for the field
typ = param[1]
#printf("Evaluate '%s', #res=%d\n", param, len(candidates))
remove = []
for struc in candidates:
monitor.checkCanceled()
#monitor.incrementProgress(1)
#monitor.setMessage("Checking %s" % struc.displayName)
#print("check", struc.displayName)
match = False
for comp in struc.components:
if checkComponent(struc, comp, offset, typ):
match = True
break
if not match: remove.append(struc)
for struc in remove: removeResult(struc)
#printf("Evaluated '%s', #res=%d\n", param, len(candidates))
for param in params:
monitor.checkCanceled()
monitor.incrementProgress(1)
monitor.setMessage("Checking %s" % param)
evaluateParam(param)
if len(candidates) == 0: break
#popup("Found %d matches (see console)" % len(candidates))
showResults()
run()
|
string_column_display = ghidra.app.tablechooser.StringColumnDisplay
addressable_row_object = ghidra.app.tablechooser.AddressableRowObject
table_chooser_executor = ghidra.app.tablechooser.TableChooserExecutor
dtm = state.tool.getService(ghidra.app.services.DataTypeManagerService)
af = currentProgram.getAddressFactory()
dt = currentProgram.getDataTypeManager()
listing = currentProgram.getListing()
mem = currentProgram.getMemory()
def addr_to_int(addr):
return int(str(addr), 16)
def int_to_addr(addr):
return AF.getAddress('0x%08X' % addr)
class Executor(TableChooserExecutor):
def get_button_name(self):
return 'Edit Structure'
def execute(self, row):
DTM.edit(row.struc)
return False
class Structnamecolumn(StringColumnDisplay):
def get_column_name(self):
return 'Struct Name'
def get_column_value(self, row):
return row.struc.displayName
class Structlengthcolumn(StringColumnDisplay):
def get_column_name(self):
return 'Struct Size'
def get_column_value(self, row):
return row.struc.length
class Structlistresult(AddressableRowObject):
def __init__(self, struc):
self.struc = struc
def get_address(self):
return int_to_addr(self.struc.length)
def run():
params = ask_string('Find Struct', 'Enter search criteria')
params = params.split(';')
monitor.initialize(len(params))
candidates = list(DT.allStructures)
def show_results():
executor = executor()
tbl = create_table_chooser_dialog('Matching Structs', executor)
tbl.addCustomColumn(struct_name_column())
tbl.addCustomColumn(struct_length_column())
for res in candidates:
tbl.add(struct_list_result(res))
tbl.show()
tbl.setMessage('%d results' % len(candidates))
def remove_result(struc):
candidates.remove(struc)
def check_component(struc, comp, offset, typ):
if comp.offset != offset:
return False
if typ is None:
return True
tp = typ
dt = comp.dataType
while tp.startswith('*'):
if not hasattr(dt, 'dataType') or dt.dataType is None:
return False
dt = dt.dataType
tp = tp[1:]
tp = tp.replace(' ', '')
nm = dt.name.replace(' ', '')
if tp.isnumeric():
if dt.length == int(tp):
return True
elif nm == tp:
return True
return False
def evaluate_param(param):
param = param.split('=')
offset = int(param[0], 16)
if len(param) < 2:
typ = None
else:
typ = param[1]
remove = []
for struc in candidates:
monitor.checkCanceled()
match = False
for comp in struc.components:
if check_component(struc, comp, offset, typ):
match = True
break
if not match:
remove.append(struc)
for struc in remove:
remove_result(struc)
for param in params:
monitor.checkCanceled()
monitor.incrementProgress(1)
monitor.setMessage('Checking %s' % param)
evaluate_param(param)
if len(candidates) == 0:
break
show_results()
run()
|
expected_output = {
"interface": {
"GigabitEthernet1/0/1": {
"out": {
"mcast_pkts": 188396,
"bcast_pkts": 0,
"ucast_pkts": 124435064,
"name": "GigabitEthernet1/0/1",
"octets": 24884341205,
},
"in": {
"mcast_pkts": 214513,
"bcast_pkts": 0,
"ucast_pkts": 15716712,
"name": "GigabitEthernet1/0/1",
"octets": 3161931167,
},
}
}
}
|
expected_output = {'interface': {'GigabitEthernet1/0/1': {'out': {'mcast_pkts': 188396, 'bcast_pkts': 0, 'ucast_pkts': 124435064, 'name': 'GigabitEthernet1/0/1', 'octets': 24884341205}, 'in': {'mcast_pkts': 214513, 'bcast_pkts': 0, 'ucast_pkts': 15716712, 'name': 'GigabitEthernet1/0/1', 'octets': 3161931167}}}}
|
DOMAIN = "echonet_lite"
MANUFACTURER = {
0x0B: "Panasonic",
0x69: "Toshiba",
0x2f: "AIPHONE",
}
CONF_STATE_CLASS = "state_class"
|
domain = 'echonet_lite'
manufacturer = {11: 'Panasonic', 105: 'Toshiba', 47: 'AIPHONE'}
conf_state_class = 'state_class'
|
"""
Container for Configuration related errors.
"""
class ConfigError(Exception):
""" Generic exception raised by
configuration errors.
"""
def __init__(self, expr, msg):
self.expression = expr
self.message = msg
def __str__(self):
return self.message
|
"""
Container for Configuration related errors.
"""
class Configerror(Exception):
""" Generic exception raised by
configuration errors.
"""
def __init__(self, expr, msg):
self.expression = expr
self.message = msg
def __str__(self):
return self.message
|
files = ['avalon_mm_bfm_pkg.vhd',
'avalon_st_bfm_pkg.vhd',
'axilite_bfm_pkg.vhd',
'axistream_bfm_pkg.vhd',
'gmii_bfm_pkg.vhd',
'gpio_bfm_pkg.vhd',
'i2c_bfm_pkg.vhd',
'rgmii_bfm_pkg.vhd',
'sbi_bfm_pkg.vhd',
'spi_bfm_pkg.vhd',
'uart_bfm_pkg.vhd',
]
|
files = ['avalon_mm_bfm_pkg.vhd', 'avalon_st_bfm_pkg.vhd', 'axilite_bfm_pkg.vhd', 'axistream_bfm_pkg.vhd', 'gmii_bfm_pkg.vhd', 'gpio_bfm_pkg.vhd', 'i2c_bfm_pkg.vhd', 'rgmii_bfm_pkg.vhd', 'sbi_bfm_pkg.vhd', 'spi_bfm_pkg.vhd', 'uart_bfm_pkg.vhd']
|
#pragma repy restrictions.loose
# create a junk.py file
myfo = open("junk.py","w")
print >> myfo, "print 'Hello world'"
myfo.close()
removefile("junk.py") # should be removed...
|
myfo = open('junk.py', 'w')
(print >> myfo, "print 'Hello world'")
myfo.close()
removefile('junk.py')
|
"""
How to find GCD (Greater Common Divisor) of two numbers using recursion?
Based on Euclidean Algorithm
"""
def GCD(n1, n2):
assert n1 != 0 and n2 != 0 and int(n1) == n1 and int(n2) == n2, "error"
if n1 < 0:
n1 *= -1
if n2 < 0:
n2 *= -1
if n1 % n2 == 0:
return n2
return GCD(n2, n1 % n2)
def GCD2(n1, n2):
if n1 == n2:
return n1
elif n1 > n2:
return GCD2(n1 - n2, n2)
else:
return GCD2(n1, n2 - n1)
print(GCD(48, 18))
print(GCD2(48, 18))
|
"""
How to find GCD (Greater Common Divisor) of two numbers using recursion?
Based on Euclidean Algorithm
"""
def gcd(n1, n2):
assert n1 != 0 and n2 != 0 and (int(n1) == n1) and (int(n2) == n2), 'error'
if n1 < 0:
n1 *= -1
if n2 < 0:
n2 *= -1
if n1 % n2 == 0:
return n2
return gcd(n2, n1 % n2)
def gcd2(n1, n2):
if n1 == n2:
return n1
elif n1 > n2:
return gcd2(n1 - n2, n2)
else:
return gcd2(n1, n2 - n1)
print(gcd(48, 18))
print(gcd2(48, 18))
|
a = ['a','b','c']
b = ['1','2','3','4','5','6']
c = list(zip(*b))
print(a)
print(c)
for d,e in zip(c,a):
print(d)
print(e)
|
a = ['a', 'b', 'c']
b = ['1', '2', '3', '4', '5', '6']
c = list(zip(*b))
print(a)
print(c)
for (d, e) in zip(c, a):
print(d)
print(e)
|
#!/usr/bin/env python
# coding: utf-8
# # Mendel's First Law
# ## Problem
#
# Probability is the mathematical study of randomly occurring phenomena. We will model such a phenomenon with a random variable, which is simply a variable that can take a number of different distinct outcomes depending on the result of an underlying random process.
#
# For example, say that we have a bag containing 3 red balls and 2 blue balls. If we let **X** represent the random variable corresponding to the color of a drawn ball, then the probability of each of the two outcomes is given by **Pr(X = red) = 35** and **Pr(X = blue) = 25**.
#
# Random variables can be combined to yield new random variables. Returning to the ball example, let Y model the color of a second ball drawn from the bag (without replacing the first ball). The probability of Y being red depends on whether the first ball was red or blue. To represent all outcomes of X and Y, we therefore use a probability tree diagram. This branching diagram represents all possible individual probabilities for X and Y, with outcomes at the endpoints ("leaves") of the tree. The probability of any outcome is given by the product of probabilities along the path from the beginning of the tree; see Figure 2 for an illustrative example.
#
# An event is simply a collection of outcomes. Because outcomes are distinct, the probability of an event can be written as the sum of the probabilities of its constituent outcomes. For our colored ball example, let **A** be the event **"Y is blue."** **Pr(A)** is equal to the sum of the probabilities of two different outcomes:
# >**Pr(X = blue and Y = blue) + Pr(X = red and Y = blue)**, or **310 + 110 = 25**.
#
# > **Given:** Three positive integers **k**, **m**, and **n**, representing a population containing **k + m + n** organisms: **k** individuals are homozygous dominant for a factor, **m** are heterozygous, and **n** are homozygous recessive.
#
# > **Return:** The probability that two randomly selected mating organisms will produce an individual possessing a dominant allele (and thus displaying the dominant phenotype). Assume that any two organisms can mate.
# In[ ]:
def mendel(x, y, z):
#calculate the probability of recessive traits only
total = x + y + z
twoRecess = (z/total)*((z-1)/(total-1))
twoHetero = (y/total)*((y-1)/(total-1))
heteroRecess = (z/total)*(y/(total-1)) + (y/total)*(z/(total-1))
recessProb = twoRecess + twoHetero*1/4 + heteroRecess*1/2
print(1-recessProb) # take the complement
# In[ ]:
with open ("rosalind_iprb.txt", "r") as file: #replace filename with your filename
line = file.readline().split()
x, y, z = [int(n) for n in line]
print(x, y, z)
file.close()
print(mendel(x, y, z))
|
def mendel(x, y, z):
total = x + y + z
two_recess = z / total * ((z - 1) / (total - 1))
two_hetero = y / total * ((y - 1) / (total - 1))
hetero_recess = z / total * (y / (total - 1)) + y / total * (z / (total - 1))
recess_prob = twoRecess + twoHetero * 1 / 4 + heteroRecess * 1 / 2
print(1 - recessProb)
with open('rosalind_iprb.txt', 'r') as file:
line = file.readline().split()
(x, y, z) = [int(n) for n in line]
print(x, y, z)
file.close()
print(mendel(x, y, z))
|
# examples on set and dict comprehensions
# EXAMPLES OF SET COMPREHENSION
# making a set comprehension is actually really easy
# instead of a list, we'll just use a set notation as follows:
my_list = [char for char in 'hello']
my_set = {char for char in 'hello'}
print(my_list)
print(my_set)
my_list1 = [num for num in range(10)]
my_set1 = {num for num in range(10)}
print(my_list1)
print(my_set1)
my_list2 = [num ** 2 for num in range(50) if num % 2 == 0]
my_set2 = {num ** 2 for num in range(50) if num % 2 == 0}
print(my_list2)
print(my_set2)
# EXAMPLE OF DICT COMPREHENSIONS
# Example 1:
simple_dict = {'a': 1, 'b': 2}
my_dict = {k: v ** 2 for k, v in simple_dict.items()}
# for each of the key:value pair in the simple_dict, we raise the value by the power of 2 and add it to my_dict
print(my_dict)
# Example 2: if we only want the even values from simple_dict to be in my_dict, then, we have the following dict comprehension
my_dict2 = {k: v ** 2 for k, v in simple_dict.items() if v % 2 == 0}
print(my_dict2)
# Example 3: If we want to make a dict from a list where the list item is the key and item*2 is the value in the dict, using dict comprehension:
my_dict3 = {item: item * 2 for item in [1, 2, 3]}
print(my_dict3)
'''
Output:
------
['h', 'e', 'l', 'l', 'o']
{'o', 'h', 'l', 'e'}
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
[0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304]
{0, 256, 1024, 2304, 4, 900, 1156, 16, 144, 400, 784, 1296, 1936, 36, 676, 1444, 64, 576, 1600, 196, 324, 2116, 100, 484, 1764}
{'a': 1, 'b': 4}
{'b': 4}
{1: 2, 2: 4, 3: 6}
'''
|
my_list = [char for char in 'hello']
my_set = {char for char in 'hello'}
print(my_list)
print(my_set)
my_list1 = [num for num in range(10)]
my_set1 = {num for num in range(10)}
print(my_list1)
print(my_set1)
my_list2 = [num ** 2 for num in range(50) if num % 2 == 0]
my_set2 = {num ** 2 for num in range(50) if num % 2 == 0}
print(my_list2)
print(my_set2)
simple_dict = {'a': 1, 'b': 2}
my_dict = {k: v ** 2 for (k, v) in simple_dict.items()}
print(my_dict)
my_dict2 = {k: v ** 2 for (k, v) in simple_dict.items() if v % 2 == 0}
print(my_dict2)
my_dict3 = {item: item * 2 for item in [1, 2, 3]}
print(my_dict3)
"\nOutput:\n------\n['h', 'e', 'l', 'l', 'o']\n{'o', 'h', 'l', 'e'}\n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}\n[0, 4, 16, 36, 64, 100, 144, 196, 256, 324, 400, 484, 576, 676, 784, 900, 1024, 1156, 1296, 1444, 1600, 1764, 1936, 2116, 2304]\n{0, 256, 1024, 2304, 4, 900, 1156, 16, 144, 400, 784, 1296, 1936, 36, 676, 1444, 64, 576, 1600, 196, 324, 2116, 100, 484, 1764}\n{'a': 1, 'b': 4}\n{'b': 4}\n{1: 2, 2: 4, 3: 6}\n"
|
class binding_(object):
"""Register key bindings with the object binding."""
def __init__(self):
self.bindings = {}
def __call__(self, key):
def register(func):
def decorator(model, nav, io, *args, **kwargs):
res = func(model, nav, io, *args, **kwargs)
return res
self.bindings[key] = decorator
return decorator
return register
# this object works as a decorator for registering key bindings
binding = binding_()
|
class Binding_(object):
"""Register key bindings with the object binding."""
def __init__(self):
self.bindings = {}
def __call__(self, key):
def register(func):
def decorator(model, nav, io, *args, **kwargs):
res = func(model, nav, io, *args, **kwargs)
return res
self.bindings[key] = decorator
return decorator
return register
binding = binding_()
|
class HtmlReportException(Exception):
pass
class HtmlReport:
def __init__(self):
self.path = None
self.file = None
self.header = None
self.start_time = None
self.is_initialized = False
def __del__(self):
if self.is_initialized and self.file:
self.write('</body></html>\n')
self.file.close()
def set_path(self, path):
self.path = path
def initialize_file(self, path):
if self.is_initialized:
self.file = open(path, 'w', encoding='utf-8', buffering=1)
def write(self, string):
if self.is_initialized:
if not self.file:
raise HtmlReportException('HTML report is not initialized')
self.file.write(string.encode('utf-8').decode('utf-8', errors='ignore'))
|
class Htmlreportexception(Exception):
pass
class Htmlreport:
def __init__(self):
self.path = None
self.file = None
self.header = None
self.start_time = None
self.is_initialized = False
def __del__(self):
if self.is_initialized and self.file:
self.write('</body></html>\n')
self.file.close()
def set_path(self, path):
self.path = path
def initialize_file(self, path):
if self.is_initialized:
self.file = open(path, 'w', encoding='utf-8', buffering=1)
def write(self, string):
if self.is_initialized:
if not self.file:
raise html_report_exception('HTML report is not initialized')
self.file.write(string.encode('utf-8').decode('utf-8', errors='ignore'))
|
SIZE = 9
INPUT_LEVEL_DIR = "File.txt"
INPUT_CONSTRAINTS_DIR = "Constraints.txt"
OUTPUT_SOLUTION_DIR = "Solution.txt"
ASSIGNED_VALUE_NUM = 0
|
size = 9
input_level_dir = 'File.txt'
input_constraints_dir = 'Constraints.txt'
output_solution_dir = 'Solution.txt'
assigned_value_num = 0
|
class Mother:
@staticmethod
def take_screenshot():
print('I can make a screenshot')
@staticmethod
def receive_email():
print('I can receive email')
class Father:
@staticmethod
def drive_car():
print('I can drive a car ')
@staticmethod
def play_music():
print(f'Play music while driving')
class Grandfather:
@staticmethod
def smoke():
print('I can drive a car ')
@staticmethod
def sing():
print(f'Play music while driving')
class Kid(Mother, Father, Grandfather):
def behave(self):
self.take_screenshot()
self.drive_car()
self.smoke()
kid = Kid()
kid.behave()
kid.drive_car()
print(Kid.mro())
|
class Mother:
@staticmethod
def take_screenshot():
print('I can make a screenshot')
@staticmethod
def receive_email():
print('I can receive email')
class Father:
@staticmethod
def drive_car():
print('I can drive a car ')
@staticmethod
def play_music():
print(f'Play music while driving')
class Grandfather:
@staticmethod
def smoke():
print('I can drive a car ')
@staticmethod
def sing():
print(f'Play music while driving')
class Kid(Mother, Father, Grandfather):
def behave(self):
self.take_screenshot()
self.drive_car()
self.smoke()
kid = kid()
kid.behave()
kid.drive_car()
print(Kid.mro())
|
class NewsModule:
def __init__(self):
pass
def update(self):
pass
|
class Newsmodule:
def __init__(self):
pass
def update(self):
pass
|
# AUTOGENERATED! DO NOT EDIT! File to edit: 01_Virtual_data_setup.ipynb (unless otherwise specified).
__all__ = ['Get_sub_watersheds']
# Cell
def Get_sub_watersheds(watershed, order_max, order_min = 4):
'''Obtains the sub-watersheds a different orders starting from the order_max and
ending on the order_min, there is no return, it only updates the watershed.Table'''
orders = np.arange(order_max, order_min, -1).tolist()
for Prun in orders:
#Finds the connections points
Ho = Prun
watershed.Table['prun_'+str(Ho)] = 0
idx = watershed.Table.loc[watershed.Table['h_order']>=Ho].index
for i in idx:
size = watershed.Table.loc[(watershed.Table['dest'] == i) & (watershed.Table['h_order'] >= Ho-1)]
if size.shape[0] >= 2:
watershed.Table.loc[size.index, 'prun_'+str(Ho)] = 1
#Finds all the links that belong to a pruning level
idx = watershed.Table.loc[watershed.Table['prun_'+str(Ho)] == 1].sort_values(by = ['Acum'], ascending = False).index
cont = 2
for i in idx:
#Finds the watershed upstream
t = am.hlmModel(linkid=i)
idx_t = watershed.Table.index.intersection(t.Table.index)
#Assign that pruning level to the sub-watershed
watershed.Table.loc[idx_t, 'prun_'+str(Ho)] = cont
#Go to next pruning level
cont += 1
print('Prun %d done' % Prun)
|
__all__ = ['Get_sub_watersheds']
def get_sub_watersheds(watershed, order_max, order_min=4):
"""Obtains the sub-watersheds a different orders starting from the order_max and
ending on the order_min, there is no return, it only updates the watershed.Table"""
orders = np.arange(order_max, order_min, -1).tolist()
for prun in orders:
ho = Prun
watershed.Table['prun_' + str(Ho)] = 0
idx = watershed.Table.loc[watershed.Table['h_order'] >= Ho].index
for i in idx:
size = watershed.Table.loc[(watershed.Table['dest'] == i) & (watershed.Table['h_order'] >= Ho - 1)]
if size.shape[0] >= 2:
watershed.Table.loc[size.index, 'prun_' + str(Ho)] = 1
idx = watershed.Table.loc[watershed.Table['prun_' + str(Ho)] == 1].sort_values(by=['Acum'], ascending=False).index
cont = 2
for i in idx:
t = am.hlmModel(linkid=i)
idx_t = watershed.Table.index.intersection(t.Table.index)
watershed.Table.loc[idx_t, 'prun_' + str(Ho)] = cont
cont += 1
print('Prun %d done' % Prun)
|
class Slot:
def __init__(self, name="", description = ""):
self.type = type # categorical, verbatim
self.name = name
self.description = description
self.values = ["not-present"]
self.values_descriptions = ["Ignore me, I'm used for programming."]
def len (self):
return len(self.values)
def add_value (self, value, value_description=""):
if value not in self.values:
self.values.append(value)
self.values_descriptions.append(value_description)
def __repr__(self):
str = "Slot [{}]:\n".format(self.name)
str+= "\tDescription: {}\n".format(self.description)
if self.type is not "verbatim":
str+= "\tValues: CATEGORICAL, {} values\n".format(len(self.values_descriptions))
for i in range (len(self.values)):
str+= "\t\t{}\t{}\n".format(self.values[i], self.values_descriptions[i])
else:
str+= "\tValues: VERBATIM\n"
return str
class Slots: # this is for one MEI only
def __init__(self):
self.slots = []
def add_slot_value_pair(self, slot_name, slot_value, slot_description = ""):
found = False
for slot in self.slots:
if slot.name == slot_name:
found = True
break
if not found:
self.slots.append(Slot(slot_name, slot_description))
for slot in self.slots:
if slot.name == slot_name:
slot.add_value(slot_value)
def get_slot_object(self, slot_name):
for slot in self.slots:
if slot.name == slot_name:
return slot
raise Exception("Slot not found: "+slot_name)
def __repr__(self):
str = "Slots object contains {} slots:\n".format(len(self.slots))
str+= "_"*60+"\n"
for slot in self.slots:
str+=slot.__repr__()
return str
|
class Slot:
def __init__(self, name='', description=''):
self.type = type
self.name = name
self.description = description
self.values = ['not-present']
self.values_descriptions = ["Ignore me, I'm used for programming."]
def len(self):
return len(self.values)
def add_value(self, value, value_description=''):
if value not in self.values:
self.values.append(value)
self.values_descriptions.append(value_description)
def __repr__(self):
str = 'Slot [{}]:\n'.format(self.name)
str += '\tDescription: {}\n'.format(self.description)
if self.type is not 'verbatim':
str += '\tValues: CATEGORICAL, {} values\n'.format(len(self.values_descriptions))
for i in range(len(self.values)):
str += '\t\t{}\t{}\n'.format(self.values[i], self.values_descriptions[i])
else:
str += '\tValues: VERBATIM\n'
return str
class Slots:
def __init__(self):
self.slots = []
def add_slot_value_pair(self, slot_name, slot_value, slot_description=''):
found = False
for slot in self.slots:
if slot.name == slot_name:
found = True
break
if not found:
self.slots.append(slot(slot_name, slot_description))
for slot in self.slots:
if slot.name == slot_name:
slot.add_value(slot_value)
def get_slot_object(self, slot_name):
for slot in self.slots:
if slot.name == slot_name:
return slot
raise exception('Slot not found: ' + slot_name)
def __repr__(self):
str = 'Slots object contains {} slots:\n'.format(len(self.slots))
str += '_' * 60 + '\n'
for slot in self.slots:
str += slot.__repr__()
return str
|
# Check if removing an edge of a binary tree can divide
# the tree in two equal halves
# Count the number of nodes, say n. Then traverse the tree
# in bottom up manner and check if n - s = s
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count(root):
if not root:
return 0
return count(root.left) + count(root.right) + 1
def check_util(root, n):
if root == None:
return False
# Check for root
if count(root) == n - count(root):
return True
# Check for all the other nodes
return check_util(root.left, n) or check_util(root.right, n)
def check(root):
n = count(rot)
return check_util(root, n)
|
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def count(root):
if not root:
return 0
return count(root.left) + count(root.right) + 1
def check_util(root, n):
if root == None:
return False
if count(root) == n - count(root):
return True
return check_util(root.left, n) or check_util(root.right, n)
def check(root):
n = count(rot)
return check_util(root, n)
|
class Cipher:
def __init__(self, codestring):
# Hints:
# Does the capitalization of the words or letter matter here?
# Is hello the same as Hello or even hElLo in terms of definition? Yes
# Maybe we should convert everything to uppercase
# Add your code here
self.alphabet = None # Add alphabet here by replacing None with the answer
self.codestring = ""
for letter in 'ZYXWVUTSRQPONMLKJIHGFEDCBA':
if None not in codestring: # Replace None with answer
self.codestring += None # Replace None with answer
self.codestring = codestring + self.codestring
self.code = {}
for (a,b) in zip(self.codestring.upper(), None): # Replace None & "None2" with the answers
self.code["None2"] = None
self.inverse = {}
for (a,b) in zip(None, self.alphabet):
self.inverse[None] = "None2" # Replace None & "None2" with the answers
def encode(self, plaintext):
# Add your code here
encoded_string = ""
for c in None: #Replace None with the answer
if c.isalpha():
encoded_string += None #Replace None with the answer
else:
encoded_string += None
return "".join(encoded_string)
def decode(self, ciphertext):
# Add your code here
decoded_string = ""
for c in None: #Replace None with the answer
if None: #Replace None with the answer
decoded_string += self.code[None] #Replace None with the answer
else:
None #Replace None with the answer (it's 1 line of code)
return "".join(decoded_string)
|
class Cipher:
def __init__(self, codestring):
self.alphabet = None
self.codestring = ''
for letter in 'ZYXWVUTSRQPONMLKJIHGFEDCBA':
if None not in codestring:
self.codestring += None
self.codestring = codestring + self.codestring
self.code = {}
for (a, b) in zip(self.codestring.upper(), None):
self.code['None2'] = None
self.inverse = {}
for (a, b) in zip(None, self.alphabet):
self.inverse[None] = 'None2'
def encode(self, plaintext):
encoded_string = ''
for c in None:
if c.isalpha():
encoded_string += None
else:
encoded_string += None
return ''.join(encoded_string)
def decode(self, ciphertext):
decoded_string = ''
for c in None:
if None:
decoded_string += self.code[None]
else:
None
return ''.join(decoded_string)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2006 Zuza Software Foundation
#
# This file is part of translate.
#
# translate is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# translate is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""A wrapper for sys.stdout etc that provides tell() for current position"""
class StdIOWrapper:
def __init__(self, stream):
self.stream = stream
self.pos = 0
self.closed = 0
def __getattr__(self, attrname, default=None):
return getattr(self.stream, attrname, default)
def close(self):
if not self.closed:
self.closed = 1
self.stream.close()
def seek(self, pos, mode=0):
raise ValueError("I/O operation on closed file")
def tell(self):
if self.closed:
raise ValueError("I/O operation on closed file")
return self.pos
def write(self, s):
if self.closed:
raise ValueError("I/O operation on closed file")
self.stream.write(s)
self.pos += len(s)
def writelines(self, lines):
if self.closed:
raise ValueError("I/O operation on closed file")
self.stream.writelines(lines)
self.pos += len("".join(lines))
|
"""A wrapper for sys.stdout etc that provides tell() for current position"""
class Stdiowrapper:
def __init__(self, stream):
self.stream = stream
self.pos = 0
self.closed = 0
def __getattr__(self, attrname, default=None):
return getattr(self.stream, attrname, default)
def close(self):
if not self.closed:
self.closed = 1
self.stream.close()
def seek(self, pos, mode=0):
raise value_error('I/O operation on closed file')
def tell(self):
if self.closed:
raise value_error('I/O operation on closed file')
return self.pos
def write(self, s):
if self.closed:
raise value_error('I/O operation on closed file')
self.stream.write(s)
self.pos += len(s)
def writelines(self, lines):
if self.closed:
raise value_error('I/O operation on closed file')
self.stream.writelines(lines)
self.pos += len(''.join(lines))
|
description = 'FRM II FAK40 information (cooling water system)'
group = 'lowlevel'
tango_base = 'tango://ictrlfs.ictrl.frm2:10000/frm2/'
devices = dict(
FAK40_Cap = device('nicos.devices.entangle.AnalogInput',
tangodevice = tango_base +'fak40/CF001',
description = 'The capacity of the cooling water system',
pollinterval = 60,
maxage = 120,
),
FAK40_Press = device('nicos.devices.entangle.AnalogInput',
tangodevice = tango_base +'fak40/CP001',
description = 'The pressure inside the cooling water system',
pollinterval = 60,
maxage = 120,
),
)
|
description = 'FRM II FAK40 information (cooling water system)'
group = 'lowlevel'
tango_base = 'tango://ictrlfs.ictrl.frm2:10000/frm2/'
devices = dict(FAK40_Cap=device('nicos.devices.entangle.AnalogInput', tangodevice=tango_base + 'fak40/CF001', description='The capacity of the cooling water system', pollinterval=60, maxage=120), FAK40_Press=device('nicos.devices.entangle.AnalogInput', tangodevice=tango_base + 'fak40/CP001', description='The pressure inside the cooling water system', pollinterval=60, maxage=120))
|
#
# PySNMP MIB module DHCP-SERVER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/DHCP-SERVER-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:33:35 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:34:52)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
Integer32, Counter64, iso, Bits, Unsigned32, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, Counter32, Gauge32, MibIdentifier, TimeTicks, enterprises, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "Counter64", "iso", "Bits", "Unsigned32", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "Counter32", "Gauge32", "MibIdentifier", "TimeTicks", "enterprises", "ModuleIdentity")
RowStatus, TruthValue, TextualConvention, DisplayString, DateAndTime = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TruthValue", "TextualConvention", "DisplayString", "DateAndTime")
lucent = MibIdentifier((1, 3, 6, 1, 4, 1, 1751))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1))
mibs = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 2))
ipspg = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48))
ipspgServices = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1))
ipspgDHCP = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1))
ipspgDNS = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 2))
ipspgTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2))
dhcpServMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1))
if mibBuilder.loadTexts: dhcpServMib.setLastUpdated('0606220830Z')
if mibBuilder.loadTexts: dhcpServMib.setOrganization('Lucent Technologies')
if mibBuilder.loadTexts: dhcpServMib.setContactInfo(' James Offutt Postal: Lucent Technologies 400 Lapp Road Malvern, PA 19355 USA Tel: +1 610-722-7900 Fax: +1 610-725-8559')
if mibBuilder.loadTexts: dhcpServMib.setDescription('The Vendor Specific MIB module for entities implementing the server side of the Bootstrap Protocol (BOOTP) and the Dynamic Host Configuration protocol (DHCP) for Internet Protocol version 4 (IPv4).')
dhcpServMibTraps = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0))
if mibBuilder.loadTexts: dhcpServMibTraps.setStatus('current')
if mibBuilder.loadTexts: dhcpServMibTraps.setDescription('DHCP Server MIB traps.')
dhcpServMibObjects = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1))
if mibBuilder.loadTexts: dhcpServMibObjects.setStatus('current')
if mibBuilder.loadTexts: dhcpServMibObjects.setDescription('DHCP Server MIB objects are all defined in this branch.')
dhcpServSystem = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1))
if mibBuilder.loadTexts: dhcpServSystem.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystem.setDescription('Group of objects that are related to the overall system.')
dhcpServSubnetCounters = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2))
if mibBuilder.loadTexts: dhcpServSubnetCounters.setStatus('current')
if mibBuilder.loadTexts: dhcpServSubnetCounters.setDescription('Group of objects that count various subnet data values')
dhcpServBootpCounters = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3))
if mibBuilder.loadTexts: dhcpServBootpCounters.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCounters.setDescription('Group of objects that count various BOOTP events.')
dhcpServDhcpCounters = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4))
if mibBuilder.loadTexts: dhcpServDhcpCounters.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCounters.setDescription('Group of objects that count various DHCP Statistics.')
dhcpServBootpStatistics = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5))
if mibBuilder.loadTexts: dhcpServBootpStatistics.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatistics.setDescription('Group of objects that measure various BOOTP statistics.')
dhcpServDhcpStatistics = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6))
if mibBuilder.loadTexts: dhcpServDhcpStatistics.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatistics.setDescription('Group of objects that measure various DHCP statistics.')
dhcpServConfiguration = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7))
if mibBuilder.loadTexts: dhcpServConfiguration.setStatus('current')
if mibBuilder.loadTexts: dhcpServConfiguration.setDescription('Objects that contain pre-configured and Dynamic Config. Info.')
dhcpServFailover = ObjectIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8))
if mibBuilder.loadTexts: dhcpServFailover.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailover.setDescription('Objects that contain partner server info.')
class DhcpServTimeInterval(TextualConvention, Gauge32):
description = 'The number of milli-seconds that has elapsed since some epoch. Systems that cannot measure events to the milli-second resolution SHOULD round this value to the next available resolution that the system supports.'
status = 'current'
dhcpServSystemDescr = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemDescr.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemDescr.setDescription('A textual description of the server. This value should include the full name and version identification of the server. This string MUST contain only printable NVT ASCII characters.')
dhcpServSystemStatus = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("starting", 0), ("running", 1), ("stopping", 2), ("stopped", 3), ("reload", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemStatus.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemStatus.setDescription(' Dhcp System Server Status ')
dhcpServSystemUpTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemUpTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemUpTime.setDescription('If the server has a persistent state (e.g., a process), this value will be the seconds elapsed since it started. For software without persistant state, this value will be zero.')
dhcpServSystemResetTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServSystemResetTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServSystemResetTime.setDescription("If the server has a persistent state (e.g., a process) and supports a `reset' operation (e.g., can be told to re-read configuration files), this value will be the seconds elapsed since the last time the name server was `reset.' For software that does not have persistence or does not support a `reset' operation, this value will be zero.")
dhcpServCountUsedSubnets = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServCountUsedSubnets.setStatus('current')
if mibBuilder.loadTexts: dhcpServCountUsedSubnets.setDescription('The number subnets managed by the server (i.e. configured), from which the server has issued at least one lease.')
dhcpServCountUnusedSubnets = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServCountUnusedSubnets.setStatus('current')
if mibBuilder.loadTexts: dhcpServCountUnusedSubnets.setDescription('The number subnets managed by the server (i.e. configured), from which the server has issued no leases.')
dhcpServCountFullSubnets = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServCountFullSubnets.setStatus('current')
if mibBuilder.loadTexts: dhcpServCountFullSubnets.setDescription('The number subnets managed by the server (i.e. configured), in which the address pools have been exhausted.')
dhcpServBootpCountRequests = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountRequests.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountRequests.setDescription('The number of packets received that contain a Message Type of 1 (BOOTREQUEST) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
dhcpServBootpCountInvalids = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountInvalids.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountInvalids.setDescription('The number of packets received that do not contain a Message Type of 1 (BOOTREQUEST) in the first octet or are not valid BOOTP packets (e.g.: too short, invalid field in packet header).')
dhcpServBootpCountReplies = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountReplies.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountReplies.setDescription('The number of packets sent that contain a Message Type of 1 (BOOTREQUEST) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
dhcpServBootpCountDroppedUnknownClients = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountDroppedUnknownClients.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountDroppedUnknownClients.setDescription('The number of BOOTP packets dropped due to the server not recognizing or not providing service to the hardware address received in the incoming packet.')
dhcpServBootpCountDroppedNotServingSubnet = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpCountDroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpCountDroppedNotServingSubnet.setDescription('The number of BOOTP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
dhcpServDhcpCountDiscovers = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDiscovers.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDiscovers.setDescription('The number of DHCPDISCOVER (option 53 with value 1) packets received.')
dhcpServDhcpCountRequests = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountRequests.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountRequests.setDescription('The number of DHCPREQUEST (option 53 with value 3) packets received.')
dhcpServDhcpCountReleases = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountReleases.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountReleases.setDescription('The number of DHCPRELEASE (option 53 with value 7) packets received.')
dhcpServDhcpCountDeclines = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDeclines.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDeclines.setDescription('The number of DHCPDECLINE (option 53 with value 4) packets received.')
dhcpServDhcpCountInforms = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountInforms.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountInforms.setDescription('The number of DHCPINFORM (option 53 with value 8) packets received.')
dhcpServDhcpCountInvalids = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountInvalids.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountInvalids.setDescription('The number of DHCP packets received whose DHCP message type (i.e.: option number 53) is not understood or handled by the server.')
dhcpServDhcpCountOffers = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountOffers.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountOffers.setDescription('The number of DHCPOFFER (option 53 with value 2) packets sent.')
dhcpServDhcpCountAcks = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountAcks.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountAcks.setDescription('The number of DHCPACK (option 53 with value 5) packets sent.')
dhcpServDhcpCountNacks = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountNacks.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountNacks.setDescription('The number of DHCPNACK (option 53 with value 6) packets sent.')
dhcpServDhcpCountDroppedUnknownClient = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedUnknownClient.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedUnknownClient.setDescription('The number of DHCP packets dropped due to the server not recognizing or not providing service to the client-id and/or hardware address received in the incoming packet.')
dhcpServDhcpCountDroppedNotServingSubnet = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpCountDroppedNotServingSubnet.setDescription('The number of DHCP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
dhcpServBootpStatMinArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 1), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMinArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMinArrivalInterval.setDescription('The minimum amount of time between receiving two BOOTP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServBootpStatMaxArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 2), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMaxArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMaxArrivalInterval.setDescription('The maximum amount of time between receiving two BOOTP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServBootpStatLastArrivalTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatLastArrivalTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatLastArrivalTime.setDescription('The number of seconds since the last valid BOOTP message was received by the server. Invalid messages do not cause this value to change. If valid no messages have been received, then this object contains a zero value.')
dhcpServBootpStatMinResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 4), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMinResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMinResponseTime.setDescription('The smallest time interval measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServBootpStatMaxResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 5), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatMaxResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatMaxResponseTime.setDescription('The largest time interval measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServBootpStatSumResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 6), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServBootpStatSumResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServBootpStatSumResponseTime.setDescription('The sum of the response time intervals in milli-seconds where a response time interval is measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMinArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 1), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMinArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMinArrivalInterval.setDescription('The minimum amount of time between receiving two DHCP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMaxArrivalInterval = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 2), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMaxArrivalInterval.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMaxArrivalInterval.setDescription('The maximum amount of time between receiving two DHCP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcpServDhcpStatLastArrivalTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatLastArrivalTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatLastArrivalTime.setDescription('The number of seconds since the last valid DHCP message was received by the server. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMinResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 4), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMinResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMinResponseTime.setDescription('The smallest time interval measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatMaxResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 5), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatMaxResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatMaxResponseTime.setDescription('The largest time interval measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServDhcpStatSumResponseTime = MibScalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 6), DhcpServTimeInterval()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServDhcpStatSumResponseTime.setStatus('current')
if mibBuilder.loadTexts: dhcpServDhcpStatSumResponseTime.setDescription('The sum of the response time intervals in milli-seconds where a response time interval is measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcpServRangeTable = MibTable((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2), )
if mibBuilder.loadTexts: dhcpServRangeTable.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeTable.setDescription('A list of ranges that are configured on this server.')
dhcpServRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1), ).setIndexNames((0, "DHCP-SERVER-MIB", "dhcpServRangeSubnetAddr"), (0, "DHCP-SERVER-MIB", "dhcpServRangeStart"))
if mibBuilder.loadTexts: dhcpServRangeEntry.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeEntry.setDescription('A logical row in the serverRangeTable.')
dhcpServRangeSubnetAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeSubnetAddr.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeSubnetAddr.setDescription('The IP address defining a subnet')
dhcpServRangeSubnetMask = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeSubnetMask.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeSubnetMask.setDescription('The subnet mask (DHCP option 1) provided to any client offered an address from this range.')
dhcpServRangeStart = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeStart.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeStart.setDescription('Start of Subnet Address, Index for Conceptual Tabl, Type IP address ')
dhcpServRangeEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 4), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeEnd.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeEnd.setDescription('The IP address of the last address in the range. The value of range end must be greater than or equal to the value of range start.')
dhcpServRangeInUse = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 5), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeInUse.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeInUse.setDescription('The number of addresses in this range that are currently in use. This number includes those addresses whose lease has not expired and addresses which have been reserved (either by the server or through configuration).')
dhcpServRangeOutstandingOffers = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 6), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeOutstandingOffers.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeOutstandingOffers.setDescription('The number of outstanding DHCPOFFER messages for this range is reported with this value. An offer is outstanding if the server has sent a DHCPOFFER message to a client, but has not yet received a DHCPREQUEST message from the client nor has the server-specific timeout (limiting the time in which a client can respond to the offer message) for the offer message expired.')
dhcpServRangeUnavailable = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 7), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeUnavailable.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeUnavailable.setDescription(' Dhcp Server IP Addresses unavailable in a Subnet ')
dhcpServRangeType = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("manBootp", 1), ("autoBootp", 2), ("manDhcp", 3), ("autoDhcp", 4), ("dynamicDhcp", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeType.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeType.setDescription('Dhcp Server Client Lease Type ')
dhcpServRangeUnused = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 9), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServRangeUnused.setStatus('current')
if mibBuilder.loadTexts: dhcpServRangeUnused.setDescription('The number of addresses in this range that are currently unused. This number includes those addresses whose lease has not expired and addresses which have been reserved (either by the server or through configuration).')
dhcpServFailoverTable = MibTable((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1), )
if mibBuilder.loadTexts: dhcpServFailoverTable.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverTable.setDescription('A list of partner server.')
dhcpServFailoverEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1), ).setIndexNames((0, "DHCP-SERVER-MIB", "dhcpServFailoverPartnerAddr"))
if mibBuilder.loadTexts: dhcpServFailoverEntry.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverEntry.setDescription('A logical row in the serverFailoverTable.')
dhcpServFailoverPartnerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 1), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerAddr.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerAddr.setDescription('The IP address defining a partner server')
dhcpServFailoverPartnerType = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("failover", 2), ("unconfigured", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerType.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerType.setDescription('Dhcp Server Failover server type ')
dhcpServFailoverPartnerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("unknown", 0), ("syncing", 1), ("active", 2), ("inactive", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerStatus.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerStatus.setDescription('Dhcp Server Partner status ')
dhcpServFailoverPartnerPolltime = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dhcpServFailoverPartnerPolltime.setStatus('current')
if mibBuilder.loadTexts: dhcpServFailoverPartnerPolltime.setDescription('The last time there was a successfull communication with the partner server. This value is local time in seconds since some epoch.')
ipspgDhcpTrapTable = MibTable((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1), )
if mibBuilder.loadTexts: ipspgDhcpTrapTable.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrapTable.setDescription("The agent's table of IPSPG alarm information.")
ipspgDhcpTrapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1), ).setIndexNames((0, "DHCP-SERVER-MIB", "ipspgDhcpTrIndex"))
if mibBuilder.loadTexts: ipspgDhcpTrapEntry.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrapEntry.setDescription('Information about the last alarm trap generated by the agent.')
ipspgDhcpTrIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrIndex.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrIndex.setDescription('Index into the IPSPG Alarm traps')
ipspgDhcpTrSequence = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrSequence.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrSequence.setDescription('Counter of the number of IPSPG alarm traps since the agent was last initialized')
ipspgDhcpTrId = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 3))).clone(namedValues=NamedValues(("monitor", 1), ("analyzer", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrId.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrId.setDescription('The application which generated this IPSPG alarm.')
ipspgDhcpTrText = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrText.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrText.setDescription('An ASCII string describing the IPSPG alarm condition/cause.')
ipspgDhcpTrPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("inform", 1), ("warning", 2), ("minor", 3), ("major", 4), ("critical", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrPriority.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrPriority.setDescription('The priority level as set on the agent for this Calss and Type of trap.')
ipspgDhcpTrClass = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrClass.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrClass.setDescription('The Class number of the described IPSPG alarm.')
ipspgDhcpTrType = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrType.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrType.setDescription('The type number of the described IPSPG alarm.')
ipspgDhcpTrTime = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrTime.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrTime.setDescription('The time that the condition or event occurred which caused generation of this alarm. This value is given in seconds since 00:00:00 Greenwich mean time (GMT) January 1, 1970.')
ipspgDhcpTrSuspect = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrSuspect.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrSuspect.setDescription('An ASCII string describing the host which caused the IPSPG alarm.')
ipspgDhcpTrDiagId = MibTableColumn((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ipspgDhcpTrDiagId.setStatus('current')
if mibBuilder.loadTexts: ipspgDhcpTrDiagId.setDescription('An integer describing the diagnosis which triggered this IPSPG alarm.')
dhcpServerStarted = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 1)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerStarted.setStatus('current')
if mibBuilder.loadTexts: dhcpServerStarted.setDescription('The monitor has determined that the DHCP server has been started.')
dhcpServerStopped = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 2)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerStopped.setStatus('current')
if mibBuilder.loadTexts: dhcpServerStopped.setDescription('The monitor has determined that the DHCP server has been stopped.')
dhcpServerReload = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 3)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerReload.setStatus('current')
if mibBuilder.loadTexts: dhcpServerReload.setDescription('The monitor has determined that the DHCP server has been reloaded.')
dhcpServerSubnetDepleted = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 4)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerSubnetDepleted.setStatus('current')
if mibBuilder.loadTexts: dhcpServerSubnetDepleted.setDescription('The monitor has determined that the DHCP server has run out of addresses in a subnet.')
dhcpServerBadPacket = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 5)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerBadPacket.setStatus('current')
if mibBuilder.loadTexts: dhcpServerBadPacket.setDescription('The monitor has determined that the DHCP server has received a bad DHCP or Bootp packet.')
dhcpServerFailoverActive = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 6)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerFailoverActive.setStatus('current')
if mibBuilder.loadTexts: dhcpServerFailoverActive.setDescription('This trap is issued by the secondary server. It indicates a primary partner server is down and its scopes are now being served by this failover server.')
dhcpServerFailoverReturnedControl = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 7)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerFailoverReturnedControl.setStatus('current')
if mibBuilder.loadTexts: dhcpServerFailoverReturnedControl.setDescription('This trap is issued by the secondary server. It indicates that the failover server has returned control to its primary partner.')
dhcpServerSubnetThresholdExceeded = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 8)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerSubnetThresholdExceeded.setStatus('current')
if mibBuilder.loadTexts: dhcpServerSubnetThresholdExceeded.setDescription('This trap is issued when subnet threshold is exceeded.')
dhcpServerSubnetThresholdDescent = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 9)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerSubnetThresholdDescent.setStatus('current')
if mibBuilder.loadTexts: dhcpServerSubnetThresholdDescent.setDescription('This trap is issued when subnet unavailable lease percentage falls below the descent threshold value.')
dhcpServerDropUnknownClient = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 10)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerDropUnknownClient.setStatus('current')
if mibBuilder.loadTexts: dhcpServerDropUnknownClient.setDescription('This trap is issued when the server drops a client message because the client MAC address is either in a MAC exclusion pool or is not in an inclusion pool.')
dhcpServerPingResponseReceived = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 11)).setObjects(("DHCP-SERVER-MIB", "ipspgDhcpTrSequence"), ("DHCP-SERVER-MIB", "ipspgDhcpTrId"), ("DHCP-SERVER-MIB", "ipspgDhcpTrText"), ("DHCP-SERVER-MIB", "ipspgDhcpTrPriority"), ("DHCP-SERVER-MIB", "ipspgDhcpTrClass"), ("DHCP-SERVER-MIB", "ipspgDhcpTrType"), ("DHCP-SERVER-MIB", "ipspgDhcpTrTime"), ("DHCP-SERVER-MIB", "ipspgDhcpTrSuspect"), ("DHCP-SERVER-MIB", "ipspgDhcpTrDiagId"))
if mibBuilder.loadTexts: dhcpServerPingResponseReceived.setStatus('current')
if mibBuilder.loadTexts: dhcpServerPingResponseReceived.setDescription('This trap is issued when the server receives a ping response.')
mibBuilder.exportSymbols("DHCP-SERVER-MIB", dhcpServDhcpStatMaxArrivalInterval=dhcpServDhcpStatMaxArrivalInterval, dhcpServDhcpStatMinResponseTime=dhcpServDhcpStatMinResponseTime, dhcpServDhcpStatMaxResponseTime=dhcpServDhcpStatMaxResponseTime, dhcpServDhcpStatistics=dhcpServDhcpStatistics, dhcpServDhcpCountDeclines=dhcpServDhcpCountDeclines, dhcpServBootpCounters=dhcpServBootpCounters, dhcpServBootpCountInvalids=dhcpServBootpCountInvalids, dhcpServBootpStatMaxResponseTime=dhcpServBootpStatMaxResponseTime, ipspgDhcpTrText=ipspgDhcpTrText, dhcpServFailover=dhcpServFailover, dhcpServSystem=dhcpServSystem, dhcpServMibTraps=dhcpServMibTraps, DhcpServTimeInterval=DhcpServTimeInterval, PYSNMP_MODULE_ID=dhcpServMib, dhcpServDhcpStatMinArrivalInterval=dhcpServDhcpStatMinArrivalInterval, ipspgDhcpTrClass=ipspgDhcpTrClass, dhcpServMib=dhcpServMib, dhcpServBootpStatMaxArrivalInterval=dhcpServBootpStatMaxArrivalInterval, dhcpServRangeEntry=dhcpServRangeEntry, dhcpServRangeInUse=dhcpServRangeInUse, dhcpServDhcpCountDiscovers=dhcpServDhcpCountDiscovers, dhcpServBootpCountDroppedUnknownClients=dhcpServBootpCountDroppedUnknownClients, dhcpServBootpCountReplies=dhcpServBootpCountReplies, ipspgDhcpTrPriority=ipspgDhcpTrPriority, dhcpServerFailoverReturnedControl=dhcpServerFailoverReturnedControl, dhcpServDhcpCountAcks=dhcpServDhcpCountAcks, ipspgDhcpTrTime=ipspgDhcpTrTime, dhcpServFailoverPartnerType=dhcpServFailoverPartnerType, dhcpServConfiguration=dhcpServConfiguration, dhcpServRangeEnd=dhcpServRangeEnd, dhcpServCountUsedSubnets=dhcpServCountUsedSubnets, dhcpServerStarted=dhcpServerStarted, ipspgDhcpTrSuspect=ipspgDhcpTrSuspect, dhcpServBootpCountDroppedNotServingSubnet=dhcpServBootpCountDroppedNotServingSubnet, dhcpServDhcpCountReleases=dhcpServDhcpCountReleases, ipspgDhcpTrapEntry=ipspgDhcpTrapEntry, dhcpServDhcpCountDroppedUnknownClient=dhcpServDhcpCountDroppedUnknownClient, dhcpServRangeOutstandingOffers=dhcpServRangeOutstandingOffers, dhcpServDhcpCountNacks=dhcpServDhcpCountNacks, dhcpServerDropUnknownClient=dhcpServerDropUnknownClient, lucent=lucent, mibs=mibs, ipspgDhcpTrapTable=ipspgDhcpTrapTable, dhcpServRangeUnavailable=dhcpServRangeUnavailable, dhcpServerReload=dhcpServerReload, dhcpServRangeUnused=dhcpServRangeUnused, dhcpServCountFullSubnets=dhcpServCountFullSubnets, dhcpServRangeSubnetMask=dhcpServRangeSubnetMask, dhcpServDhcpCountDroppedNotServingSubnet=dhcpServDhcpCountDroppedNotServingSubnet, dhcpServRangeType=dhcpServRangeType, dhcpServRangeTable=dhcpServRangeTable, dhcpServSystemDescr=dhcpServSystemDescr, ipspgDhcpTrSequence=ipspgDhcpTrSequence, dhcpServerFailoverActive=dhcpServerFailoverActive, dhcpServerStopped=dhcpServerStopped, ipspgTrap=ipspgTrap, ipspgDhcpTrId=ipspgDhcpTrId, dhcpServerBadPacket=dhcpServerBadPacket, ipspgServices=ipspgServices, ipspgDhcpTrType=ipspgDhcpTrType, dhcpServDhcpCountRequests=dhcpServDhcpCountRequests, dhcpServDhcpCountInforms=dhcpServDhcpCountInforms, dhcpServDhcpCountOffers=dhcpServDhcpCountOffers, products=products, dhcpServerSubnetThresholdExceeded=dhcpServerSubnetThresholdExceeded, ipspgDhcpTrIndex=ipspgDhcpTrIndex, dhcpServerPingResponseReceived=dhcpServerPingResponseReceived, dhcpServRangeStart=dhcpServRangeStart, dhcpServSubnetCounters=dhcpServSubnetCounters, dhcpServFailoverPartnerAddr=dhcpServFailoverPartnerAddr, dhcpServDhcpStatLastArrivalTime=dhcpServDhcpStatLastArrivalTime, ipspgDNS=ipspgDNS, dhcpServerSubnetDepleted=dhcpServerSubnetDepleted, ipspg=ipspg, dhcpServBootpCountRequests=dhcpServBootpCountRequests, dhcpServFailoverPartnerPolltime=dhcpServFailoverPartnerPolltime, dhcpServDhcpStatSumResponseTime=dhcpServDhcpStatSumResponseTime, dhcpServSystemUpTime=dhcpServSystemUpTime, dhcpServBootpStatMinResponseTime=dhcpServBootpStatMinResponseTime, dhcpServBootpStatSumResponseTime=dhcpServBootpStatSumResponseTime, dhcpServFailoverEntry=dhcpServFailoverEntry, ipspgDhcpTrDiagId=ipspgDhcpTrDiagId, ipspgDHCP=ipspgDHCP, dhcpServCountUnusedSubnets=dhcpServCountUnusedSubnets, dhcpServFailoverPartnerStatus=dhcpServFailoverPartnerStatus, dhcpServMibObjects=dhcpServMibObjects, dhcpServDhcpCounters=dhcpServDhcpCounters, dhcpServerSubnetThresholdDescent=dhcpServerSubnetThresholdDescent, dhcpServBootpStatMinArrivalInterval=dhcpServBootpStatMinArrivalInterval, dhcpServSystemResetTime=dhcpServSystemResetTime, dhcpServFailoverTable=dhcpServFailoverTable, dhcpServBootpStatistics=dhcpServBootpStatistics, dhcpServDhcpCountInvalids=dhcpServDhcpCountInvalids, dhcpServSystemStatus=dhcpServSystemStatus, dhcpServBootpStatLastArrivalTime=dhcpServBootpStatLastArrivalTime, dhcpServRangeSubnetAddr=dhcpServRangeSubnetAddr)
|
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_union, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(integer32, counter64, iso, bits, unsigned32, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, object_identity, counter32, gauge32, mib_identifier, time_ticks, enterprises, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'Counter64', 'iso', 'Bits', 'Unsigned32', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ObjectIdentity', 'Counter32', 'Gauge32', 'MibIdentifier', 'TimeTicks', 'enterprises', 'ModuleIdentity')
(row_status, truth_value, textual_convention, display_string, date_and_time) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TruthValue', 'TextualConvention', 'DisplayString', 'DateAndTime')
lucent = mib_identifier((1, 3, 6, 1, 4, 1, 1751))
products = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1))
mibs = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 2))
ipspg = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1, 48))
ipspg_services = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1))
ipspg_dhcp = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1))
ipspg_dns = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 2))
ipspg_trap = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2))
dhcp_serv_mib = module_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1))
if mibBuilder.loadTexts:
dhcpServMib.setLastUpdated('0606220830Z')
if mibBuilder.loadTexts:
dhcpServMib.setOrganization('Lucent Technologies')
if mibBuilder.loadTexts:
dhcpServMib.setContactInfo(' James Offutt Postal: Lucent Technologies 400 Lapp Road Malvern, PA 19355 USA Tel: +1 610-722-7900 Fax: +1 610-725-8559')
if mibBuilder.loadTexts:
dhcpServMib.setDescription('The Vendor Specific MIB module for entities implementing the server side of the Bootstrap Protocol (BOOTP) and the Dynamic Host Configuration protocol (DHCP) for Internet Protocol version 4 (IPv4).')
dhcp_serv_mib_traps = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0))
if mibBuilder.loadTexts:
dhcpServMibTraps.setStatus('current')
if mibBuilder.loadTexts:
dhcpServMibTraps.setDescription('DHCP Server MIB traps.')
dhcp_serv_mib_objects = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1))
if mibBuilder.loadTexts:
dhcpServMibObjects.setStatus('current')
if mibBuilder.loadTexts:
dhcpServMibObjects.setDescription('DHCP Server MIB objects are all defined in this branch.')
dhcp_serv_system = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1))
if mibBuilder.loadTexts:
dhcpServSystem.setStatus('current')
if mibBuilder.loadTexts:
dhcpServSystem.setDescription('Group of objects that are related to the overall system.')
dhcp_serv_subnet_counters = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2))
if mibBuilder.loadTexts:
dhcpServSubnetCounters.setStatus('current')
if mibBuilder.loadTexts:
dhcpServSubnetCounters.setDescription('Group of objects that count various subnet data values')
dhcp_serv_bootp_counters = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3))
if mibBuilder.loadTexts:
dhcpServBootpCounters.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpCounters.setDescription('Group of objects that count various BOOTP events.')
dhcp_serv_dhcp_counters = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4))
if mibBuilder.loadTexts:
dhcpServDhcpCounters.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCounters.setDescription('Group of objects that count various DHCP Statistics.')
dhcp_serv_bootp_statistics = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5))
if mibBuilder.loadTexts:
dhcpServBootpStatistics.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpStatistics.setDescription('Group of objects that measure various BOOTP statistics.')
dhcp_serv_dhcp_statistics = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6))
if mibBuilder.loadTexts:
dhcpServDhcpStatistics.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpStatistics.setDescription('Group of objects that measure various DHCP statistics.')
dhcp_serv_configuration = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7))
if mibBuilder.loadTexts:
dhcpServConfiguration.setStatus('current')
if mibBuilder.loadTexts:
dhcpServConfiguration.setDescription('Objects that contain pre-configured and Dynamic Config. Info.')
dhcp_serv_failover = object_identity((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8))
if mibBuilder.loadTexts:
dhcpServFailover.setStatus('current')
if mibBuilder.loadTexts:
dhcpServFailover.setDescription('Objects that contain partner server info.')
class Dhcpservtimeinterval(TextualConvention, Gauge32):
description = 'The number of milli-seconds that has elapsed since some epoch. Systems that cannot measure events to the milli-second resolution SHOULD round this value to the next available resolution that the system supports.'
status = 'current'
dhcp_serv_system_descr = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServSystemDescr.setStatus('current')
if mibBuilder.loadTexts:
dhcpServSystemDescr.setDescription('A textual description of the server. This value should include the full name and version identification of the server. This string MUST contain only printable NVT ASCII characters.')
dhcp_serv_system_status = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4))).clone(namedValues=named_values(('starting', 0), ('running', 1), ('stopping', 2), ('stopped', 3), ('reload', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServSystemStatus.setStatus('current')
if mibBuilder.loadTexts:
dhcpServSystemStatus.setDescription(' Dhcp System Server Status ')
dhcp_serv_system_up_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 3), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServSystemUpTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServSystemUpTime.setDescription('If the server has a persistent state (e.g., a process), this value will be the seconds elapsed since it started. For software without persistant state, this value will be zero.')
dhcp_serv_system_reset_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 1, 4), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServSystemResetTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServSystemResetTime.setDescription("If the server has a persistent state (e.g., a process) and supports a `reset' operation (e.g., can be told to re-read configuration files), this value will be the seconds elapsed since the last time the name server was `reset.' For software that does not have persistence or does not support a `reset' operation, this value will be zero.")
dhcp_serv_count_used_subnets = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServCountUsedSubnets.setStatus('current')
if mibBuilder.loadTexts:
dhcpServCountUsedSubnets.setDescription('The number subnets managed by the server (i.e. configured), from which the server has issued at least one lease.')
dhcp_serv_count_unused_subnets = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServCountUnusedSubnets.setStatus('current')
if mibBuilder.loadTexts:
dhcpServCountUnusedSubnets.setDescription('The number subnets managed by the server (i.e. configured), from which the server has issued no leases.')
dhcp_serv_count_full_subnets = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 2, 3), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServCountFullSubnets.setStatus('current')
if mibBuilder.loadTexts:
dhcpServCountFullSubnets.setDescription('The number subnets managed by the server (i.e. configured), in which the address pools have been exhausted.')
dhcp_serv_bootp_count_requests = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpCountRequests.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpCountRequests.setDescription('The number of packets received that contain a Message Type of 1 (BOOTREQUEST) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
dhcp_serv_bootp_count_invalids = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpCountInvalids.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpCountInvalids.setDescription('The number of packets received that do not contain a Message Type of 1 (BOOTREQUEST) in the first octet or are not valid BOOTP packets (e.g.: too short, invalid field in packet header).')
dhcp_serv_bootp_count_replies = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpCountReplies.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpCountReplies.setDescription('The number of packets sent that contain a Message Type of 1 (BOOTREQUEST) in the first octet and do not contain option number 53 (DHCP Message Type) in the options.')
dhcp_serv_bootp_count_dropped_unknown_clients = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpCountDroppedUnknownClients.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpCountDroppedUnknownClients.setDescription('The number of BOOTP packets dropped due to the server not recognizing or not providing service to the hardware address received in the incoming packet.')
dhcp_serv_bootp_count_dropped_not_serving_subnet = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 3, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpCountDroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpCountDroppedNotServingSubnet.setDescription('The number of BOOTP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
dhcp_serv_dhcp_count_discovers = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountDiscovers.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountDiscovers.setDescription('The number of DHCPDISCOVER (option 53 with value 1) packets received.')
dhcp_serv_dhcp_count_requests = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountRequests.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountRequests.setDescription('The number of DHCPREQUEST (option 53 with value 3) packets received.')
dhcp_serv_dhcp_count_releases = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountReleases.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountReleases.setDescription('The number of DHCPRELEASE (option 53 with value 7) packets received.')
dhcp_serv_dhcp_count_declines = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountDeclines.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountDeclines.setDescription('The number of DHCPDECLINE (option 53 with value 4) packets received.')
dhcp_serv_dhcp_count_informs = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountInforms.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountInforms.setDescription('The number of DHCPINFORM (option 53 with value 8) packets received.')
dhcp_serv_dhcp_count_invalids = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountInvalids.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountInvalids.setDescription('The number of DHCP packets received whose DHCP message type (i.e.: option number 53) is not understood or handled by the server.')
dhcp_serv_dhcp_count_offers = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountOffers.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountOffers.setDescription('The number of DHCPOFFER (option 53 with value 2) packets sent.')
dhcp_serv_dhcp_count_acks = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountAcks.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountAcks.setDescription('The number of DHCPACK (option 53 with value 5) packets sent.')
dhcp_serv_dhcp_count_nacks = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountNacks.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountNacks.setDescription('The number of DHCPNACK (option 53 with value 6) packets sent.')
dhcp_serv_dhcp_count_dropped_unknown_client = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountDroppedUnknownClient.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountDroppedUnknownClient.setDescription('The number of DHCP packets dropped due to the server not recognizing or not providing service to the client-id and/or hardware address received in the incoming packet.')
dhcp_serv_dhcp_count_dropped_not_serving_subnet = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 4, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpCountDroppedNotServingSubnet.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpCountDroppedNotServingSubnet.setDescription('The number of DHCP packets dropped due to the server not being configured or not otherwise able to serve addresses on the subnet from which this message was received.')
dhcp_serv_bootp_stat_min_arrival_interval = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 1), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpStatMinArrivalInterval.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpStatMinArrivalInterval.setDescription('The minimum amount of time between receiving two BOOTP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcp_serv_bootp_stat_max_arrival_interval = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 2), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpStatMaxArrivalInterval.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpStatMaxArrivalInterval.setDescription('The maximum amount of time between receiving two BOOTP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcp_serv_bootp_stat_last_arrival_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 3), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpStatLastArrivalTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpStatLastArrivalTime.setDescription('The number of seconds since the last valid BOOTP message was received by the server. Invalid messages do not cause this value to change. If valid no messages have been received, then this object contains a zero value.')
dhcp_serv_bootp_stat_min_response_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 4), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpStatMinResponseTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpStatMinResponseTime.setDescription('The smallest time interval measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcp_serv_bootp_stat_max_response_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 5), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpStatMaxResponseTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpStatMaxResponseTime.setDescription('The largest time interval measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcp_serv_bootp_stat_sum_response_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 5, 6), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServBootpStatSumResponseTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServBootpStatSumResponseTime.setDescription('The sum of the response time intervals in milli-seconds where a response time interval is measured as the difference between the arrival of a BOOTP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcp_serv_dhcp_stat_min_arrival_interval = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 1), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpStatMinArrivalInterval.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpStatMinArrivalInterval.setDescription('The minimum amount of time between receiving two DHCP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcp_serv_dhcp_stat_max_arrival_interval = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 2), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpStatMaxArrivalInterval.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpStatMaxArrivalInterval.setDescription('The maximum amount of time between receiving two DHCP messages. A message is received at the server when the server is able to begin processing the message. This typically occurs immediately after the message is read into server memory. If no messages have been received, then this object contains a zero value.')
dhcp_serv_dhcp_stat_last_arrival_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 3), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpStatLastArrivalTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpStatLastArrivalTime.setDescription('The number of seconds since the last valid DHCP message was received by the server. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcp_serv_dhcp_stat_min_response_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 4), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpStatMinResponseTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpStatMinResponseTime.setDescription('The smallest time interval measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcp_serv_dhcp_stat_max_response_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 5), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpStatMaxResponseTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpStatMaxResponseTime.setDescription('The largest time interval measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcp_serv_dhcp_stat_sum_response_time = mib_scalar((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 6, 6), dhcp_serv_time_interval()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServDhcpStatSumResponseTime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServDhcpStatSumResponseTime.setDescription('The sum of the response time intervals in milli-seconds where a response time interval is measured as the difference between the arrival of a DHCP message at the server and the successful transmission of the response to that message. A message is received at the server when the server is able to begin processing the message. A message is transmitted after the server has no further use for the message. Note that the operating system may still have the message queued internally. The operating system queue time is not to be considered as part of the response time. Invalid messages do not cause this value to change. If no valid messages have been received, then this object contains a zero value.')
dhcp_serv_range_table = mib_table((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2))
if mibBuilder.loadTexts:
dhcpServRangeTable.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeTable.setDescription('A list of ranges that are configured on this server.')
dhcp_serv_range_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1)).setIndexNames((0, 'DHCP-SERVER-MIB', 'dhcpServRangeSubnetAddr'), (0, 'DHCP-SERVER-MIB', 'dhcpServRangeStart'))
if mibBuilder.loadTexts:
dhcpServRangeEntry.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeEntry.setDescription('A logical row in the serverRangeTable.')
dhcp_serv_range_subnet_addr = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 1), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeSubnetAddr.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeSubnetAddr.setDescription('The IP address defining a subnet')
dhcp_serv_range_subnet_mask = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 2), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeSubnetMask.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeSubnetMask.setDescription('The subnet mask (DHCP option 1) provided to any client offered an address from this range.')
dhcp_serv_range_start = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 3), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeStart.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeStart.setDescription('Start of Subnet Address, Index for Conceptual Tabl, Type IP address ')
dhcp_serv_range_end = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 4), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeEnd.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeEnd.setDescription('The IP address of the last address in the range. The value of range end must be greater than or equal to the value of range start.')
dhcp_serv_range_in_use = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 5), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeInUse.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeInUse.setDescription('The number of addresses in this range that are currently in use. This number includes those addresses whose lease has not expired and addresses which have been reserved (either by the server or through configuration).')
dhcp_serv_range_outstanding_offers = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 6), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeOutstandingOffers.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeOutstandingOffers.setDescription('The number of outstanding DHCPOFFER messages for this range is reported with this value. An offer is outstanding if the server has sent a DHCPOFFER message to a client, but has not yet received a DHCPREQUEST message from the client nor has the server-specific timeout (limiting the time in which a client can respond to the offer message) for the offer message expired.')
dhcp_serv_range_unavailable = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 7), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeUnavailable.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeUnavailable.setDescription(' Dhcp Server IP Addresses unavailable in a Subnet ')
dhcp_serv_range_type = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('manBootp', 1), ('autoBootp', 2), ('manDhcp', 3), ('autoDhcp', 4), ('dynamicDhcp', 5)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeType.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeType.setDescription('Dhcp Server Client Lease Type ')
dhcp_serv_range_unused = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 7, 2, 1, 9), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServRangeUnused.setStatus('current')
if mibBuilder.loadTexts:
dhcpServRangeUnused.setDescription('The number of addresses in this range that are currently unused. This number includes those addresses whose lease has not expired and addresses which have been reserved (either by the server or through configuration).')
dhcp_serv_failover_table = mib_table((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1))
if mibBuilder.loadTexts:
dhcpServFailoverTable.setStatus('current')
if mibBuilder.loadTexts:
dhcpServFailoverTable.setDescription('A list of partner server.')
dhcp_serv_failover_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1)).setIndexNames((0, 'DHCP-SERVER-MIB', 'dhcpServFailoverPartnerAddr'))
if mibBuilder.loadTexts:
dhcpServFailoverEntry.setStatus('current')
if mibBuilder.loadTexts:
dhcpServFailoverEntry.setDescription('A logical row in the serverFailoverTable.')
dhcp_serv_failover_partner_addr = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 1), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerAddr.setStatus('current')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerAddr.setDescription('The IP address defining a partner server')
dhcp_serv_failover_partner_type = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('primary', 1), ('failover', 2), ('unconfigured', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerType.setStatus('current')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerType.setDescription('Dhcp Server Failover server type ')
dhcp_serv_failover_partner_status = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('unknown', 0), ('syncing', 1), ('active', 2), ('inactive', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerStatus.setStatus('current')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerStatus.setDescription('Dhcp Server Partner status ')
dhcp_serv_failover_partner_polltime = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 1, 8, 1, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerPolltime.setStatus('current')
if mibBuilder.loadTexts:
dhcpServFailoverPartnerPolltime.setDescription('The last time there was a successfull communication with the partner server. This value is local time in seconds since some epoch.')
ipspg_dhcp_trap_table = mib_table((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1))
if mibBuilder.loadTexts:
ipspgDhcpTrapTable.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrapTable.setDescription("The agent's table of IPSPG alarm information.")
ipspg_dhcp_trap_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1)).setIndexNames((0, 'DHCP-SERVER-MIB', 'ipspgDhcpTrIndex'))
if mibBuilder.loadTexts:
ipspgDhcpTrapEntry.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrapEntry.setDescription('Information about the last alarm trap generated by the agent.')
ipspg_dhcp_tr_index = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 31))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrIndex.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrIndex.setDescription('Index into the IPSPG Alarm traps')
ipspg_dhcp_tr_sequence = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrSequence.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrSequence.setDescription('Counter of the number of IPSPG alarm traps since the agent was last initialized')
ipspg_dhcp_tr_id = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 3))).clone(namedValues=named_values(('monitor', 1), ('analyzer', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrId.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrId.setDescription('The application which generated this IPSPG alarm.')
ipspg_dhcp_tr_text = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrText.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrText.setDescription('An ASCII string describing the IPSPG alarm condition/cause.')
ipspg_dhcp_tr_priority = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('inform', 1), ('warning', 2), ('minor', 3), ('major', 4), ('critical', 5)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrPriority.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrPriority.setDescription('The priority level as set on the agent for this Calss and Type of trap.')
ipspg_dhcp_tr_class = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrClass.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrClass.setDescription('The Class number of the described IPSPG alarm.')
ipspg_dhcp_tr_type = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrType.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrType.setDescription('The type number of the described IPSPG alarm.')
ipspg_dhcp_tr_time = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrTime.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrTime.setDescription('The time that the condition or event occurred which caused generation of this alarm. This value is given in seconds since 00:00:00 Greenwich mean time (GMT) January 1, 1970.')
ipspg_dhcp_tr_suspect = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 9), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrSuspect.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrSuspect.setDescription('An ASCII string describing the host which caused the IPSPG alarm.')
ipspg_dhcp_tr_diag_id = mib_table_column((1, 3, 6, 1, 4, 1, 1751, 1, 48, 2, 1, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ipspgDhcpTrDiagId.setStatus('current')
if mibBuilder.loadTexts:
ipspgDhcpTrDiagId.setDescription('An integer describing the diagnosis which triggered this IPSPG alarm.')
dhcp_server_started = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 1)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerStarted.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerStarted.setDescription('The monitor has determined that the DHCP server has been started.')
dhcp_server_stopped = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 2)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerStopped.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerStopped.setDescription('The monitor has determined that the DHCP server has been stopped.')
dhcp_server_reload = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 3)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerReload.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerReload.setDescription('The monitor has determined that the DHCP server has been reloaded.')
dhcp_server_subnet_depleted = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 4)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerSubnetDepleted.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerSubnetDepleted.setDescription('The monitor has determined that the DHCP server has run out of addresses in a subnet.')
dhcp_server_bad_packet = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 5)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerBadPacket.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerBadPacket.setDescription('The monitor has determined that the DHCP server has received a bad DHCP or Bootp packet.')
dhcp_server_failover_active = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 6)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerFailoverActive.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerFailoverActive.setDescription('This trap is issued by the secondary server. It indicates a primary partner server is down and its scopes are now being served by this failover server.')
dhcp_server_failover_returned_control = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 7)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerFailoverReturnedControl.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerFailoverReturnedControl.setDescription('This trap is issued by the secondary server. It indicates that the failover server has returned control to its primary partner.')
dhcp_server_subnet_threshold_exceeded = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 8)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerSubnetThresholdExceeded.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerSubnetThresholdExceeded.setDescription('This trap is issued when subnet threshold is exceeded.')
dhcp_server_subnet_threshold_descent = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 9)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerSubnetThresholdDescent.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerSubnetThresholdDescent.setDescription('This trap is issued when subnet unavailable lease percentage falls below the descent threshold value.')
dhcp_server_drop_unknown_client = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 10)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerDropUnknownClient.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerDropUnknownClient.setDescription('This trap is issued when the server drops a client message because the client MAC address is either in a MAC exclusion pool or is not in an inclusion pool.')
dhcp_server_ping_response_received = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 48, 1, 1, 1, 0, 11)).setObjects(('DHCP-SERVER-MIB', 'ipspgDhcpTrSequence'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrId'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrText'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrPriority'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrClass'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrType'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrTime'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrSuspect'), ('DHCP-SERVER-MIB', 'ipspgDhcpTrDiagId'))
if mibBuilder.loadTexts:
dhcpServerPingResponseReceived.setStatus('current')
if mibBuilder.loadTexts:
dhcpServerPingResponseReceived.setDescription('This trap is issued when the server receives a ping response.')
mibBuilder.exportSymbols('DHCP-SERVER-MIB', dhcpServDhcpStatMaxArrivalInterval=dhcpServDhcpStatMaxArrivalInterval, dhcpServDhcpStatMinResponseTime=dhcpServDhcpStatMinResponseTime, dhcpServDhcpStatMaxResponseTime=dhcpServDhcpStatMaxResponseTime, dhcpServDhcpStatistics=dhcpServDhcpStatistics, dhcpServDhcpCountDeclines=dhcpServDhcpCountDeclines, dhcpServBootpCounters=dhcpServBootpCounters, dhcpServBootpCountInvalids=dhcpServBootpCountInvalids, dhcpServBootpStatMaxResponseTime=dhcpServBootpStatMaxResponseTime, ipspgDhcpTrText=ipspgDhcpTrText, dhcpServFailover=dhcpServFailover, dhcpServSystem=dhcpServSystem, dhcpServMibTraps=dhcpServMibTraps, DhcpServTimeInterval=DhcpServTimeInterval, PYSNMP_MODULE_ID=dhcpServMib, dhcpServDhcpStatMinArrivalInterval=dhcpServDhcpStatMinArrivalInterval, ipspgDhcpTrClass=ipspgDhcpTrClass, dhcpServMib=dhcpServMib, dhcpServBootpStatMaxArrivalInterval=dhcpServBootpStatMaxArrivalInterval, dhcpServRangeEntry=dhcpServRangeEntry, dhcpServRangeInUse=dhcpServRangeInUse, dhcpServDhcpCountDiscovers=dhcpServDhcpCountDiscovers, dhcpServBootpCountDroppedUnknownClients=dhcpServBootpCountDroppedUnknownClients, dhcpServBootpCountReplies=dhcpServBootpCountReplies, ipspgDhcpTrPriority=ipspgDhcpTrPriority, dhcpServerFailoverReturnedControl=dhcpServerFailoverReturnedControl, dhcpServDhcpCountAcks=dhcpServDhcpCountAcks, ipspgDhcpTrTime=ipspgDhcpTrTime, dhcpServFailoverPartnerType=dhcpServFailoverPartnerType, dhcpServConfiguration=dhcpServConfiguration, dhcpServRangeEnd=dhcpServRangeEnd, dhcpServCountUsedSubnets=dhcpServCountUsedSubnets, dhcpServerStarted=dhcpServerStarted, ipspgDhcpTrSuspect=ipspgDhcpTrSuspect, dhcpServBootpCountDroppedNotServingSubnet=dhcpServBootpCountDroppedNotServingSubnet, dhcpServDhcpCountReleases=dhcpServDhcpCountReleases, ipspgDhcpTrapEntry=ipspgDhcpTrapEntry, dhcpServDhcpCountDroppedUnknownClient=dhcpServDhcpCountDroppedUnknownClient, dhcpServRangeOutstandingOffers=dhcpServRangeOutstandingOffers, dhcpServDhcpCountNacks=dhcpServDhcpCountNacks, dhcpServerDropUnknownClient=dhcpServerDropUnknownClient, lucent=lucent, mibs=mibs, ipspgDhcpTrapTable=ipspgDhcpTrapTable, dhcpServRangeUnavailable=dhcpServRangeUnavailable, dhcpServerReload=dhcpServerReload, dhcpServRangeUnused=dhcpServRangeUnused, dhcpServCountFullSubnets=dhcpServCountFullSubnets, dhcpServRangeSubnetMask=dhcpServRangeSubnetMask, dhcpServDhcpCountDroppedNotServingSubnet=dhcpServDhcpCountDroppedNotServingSubnet, dhcpServRangeType=dhcpServRangeType, dhcpServRangeTable=dhcpServRangeTable, dhcpServSystemDescr=dhcpServSystemDescr, ipspgDhcpTrSequence=ipspgDhcpTrSequence, dhcpServerFailoverActive=dhcpServerFailoverActive, dhcpServerStopped=dhcpServerStopped, ipspgTrap=ipspgTrap, ipspgDhcpTrId=ipspgDhcpTrId, dhcpServerBadPacket=dhcpServerBadPacket, ipspgServices=ipspgServices, ipspgDhcpTrType=ipspgDhcpTrType, dhcpServDhcpCountRequests=dhcpServDhcpCountRequests, dhcpServDhcpCountInforms=dhcpServDhcpCountInforms, dhcpServDhcpCountOffers=dhcpServDhcpCountOffers, products=products, dhcpServerSubnetThresholdExceeded=dhcpServerSubnetThresholdExceeded, ipspgDhcpTrIndex=ipspgDhcpTrIndex, dhcpServerPingResponseReceived=dhcpServerPingResponseReceived, dhcpServRangeStart=dhcpServRangeStart, dhcpServSubnetCounters=dhcpServSubnetCounters, dhcpServFailoverPartnerAddr=dhcpServFailoverPartnerAddr, dhcpServDhcpStatLastArrivalTime=dhcpServDhcpStatLastArrivalTime, ipspgDNS=ipspgDNS, dhcpServerSubnetDepleted=dhcpServerSubnetDepleted, ipspg=ipspg, dhcpServBootpCountRequests=dhcpServBootpCountRequests, dhcpServFailoverPartnerPolltime=dhcpServFailoverPartnerPolltime, dhcpServDhcpStatSumResponseTime=dhcpServDhcpStatSumResponseTime, dhcpServSystemUpTime=dhcpServSystemUpTime, dhcpServBootpStatMinResponseTime=dhcpServBootpStatMinResponseTime, dhcpServBootpStatSumResponseTime=dhcpServBootpStatSumResponseTime, dhcpServFailoverEntry=dhcpServFailoverEntry, ipspgDhcpTrDiagId=ipspgDhcpTrDiagId, ipspgDHCP=ipspgDHCP, dhcpServCountUnusedSubnets=dhcpServCountUnusedSubnets, dhcpServFailoverPartnerStatus=dhcpServFailoverPartnerStatus, dhcpServMibObjects=dhcpServMibObjects, dhcpServDhcpCounters=dhcpServDhcpCounters, dhcpServerSubnetThresholdDescent=dhcpServerSubnetThresholdDescent, dhcpServBootpStatMinArrivalInterval=dhcpServBootpStatMinArrivalInterval, dhcpServSystemResetTime=dhcpServSystemResetTime, dhcpServFailoverTable=dhcpServFailoverTable, dhcpServBootpStatistics=dhcpServBootpStatistics, dhcpServDhcpCountInvalids=dhcpServDhcpCountInvalids, dhcpServSystemStatus=dhcpServSystemStatus, dhcpServBootpStatLastArrivalTime=dhcpServBootpStatLastArrivalTime, dhcpServRangeSubnetAddr=dhcpServRangeSubnetAddr)
|
def residual(s:dict, y, x):
""" Return residuals
:param s: state - supply empty dict on first call
:param y: incoming observation
:param x: term structure of predictions out k steps ahead, made after y received
:returns k-vector of residuals
"""
k = len(x)
if not s:
s = {'predictions': [[] for _ in range(k)]} # Holds the cavalcade
else:
assert len(x) == len(s['predictions']) # 'k' is immutable
assessable = s['predictions'].pop(0)
z = [0 for _ in range(k)]
if assessable:
for j, xi in assessable:
z[j] = y - xi
s['predictions'].append(list())
for j, xj in enumerate(x):
s['predictions'][j].append((j, xj))
return z, s
|
def residual(s: dict, y, x):
""" Return residuals
:param s: state - supply empty dict on first call
:param y: incoming observation
:param x: term structure of predictions out k steps ahead, made after y received
:returns k-vector of residuals
"""
k = len(x)
if not s:
s = {'predictions': [[] for _ in range(k)]}
else:
assert len(x) == len(s['predictions'])
assessable = s['predictions'].pop(0)
z = [0 for _ in range(k)]
if assessable:
for (j, xi) in assessable:
z[j] = y - xi
s['predictions'].append(list())
for (j, xj) in enumerate(x):
s['predictions'][j].append((j, xj))
return (z, s)
|
html_head = r"""<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" />
<title></title>
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>
<script type="text/javascript">
var subjs = []
function updateCounts(){
var counts = {report:{"-1":0, "1":0, "0":0}}
subjs.forEach(function(val, idx, arr){
counts.report[val.report] += 1;
})
$("#nrpass").text(counts.report["1"])
$("#nrfail").text(counts.report["0"])
$("#nrtodo").text(counts.report["-1"])
}
function qc_update(run_id, stage, value) {
if (stage == 'report') {
subjs[run_id][stage] = parseInt(value)
updateCounts();
}
else {
subjs[run_id][stage] = value
}
}
function update_all(stage, value) {
subjs.forEach( subj => {subj[stage]=value})
}
function get_csv(items) {
// https://stackoverflow.com/questions/44396943/generate-a-csv-file-from-a-javascript-array-of-objects
let csv = ''
// Loop the array of objects
for(let row = 0; row < items.length; row++){
let keysAmount = Object.keys(items[row]).length
let keysCounter = 0
// If this is the first row, generate the headings
if(row === 0){
// Loop each property of the object
for(let key in items[row]){
// This is to not add a comma at the last cell
// The '\r\n' adds a new line
csv += key + (keysCounter+1 < keysAmount ? '\t' : '\r\n' )
keysCounter++
}
let keysCounterb = 0
for(let key in items[row]){
csv += items[row][key] + (keysCounterb+1 < keysAmount ? '\t' : '\r\n' )
keysCounterb++
}
}else{
for(let key in items[row]){
csv += items[row][key] + (keysCounter+1 < keysAmount ? '\t' : '\r\n' )
keysCounter++
}
}
keysCounter = 0
}
// Once we are done looping, download the .csv by creating a link
// if a link has already been created, update it
if (document.querySelector('#download-csv') == null){
let link = document.createElement('a')
link.id = 'download-csv'
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', 'thistextissolongitmustabsolutelybeuniqueright');
document.body.appendChild(link)
} else {
let link = document.querySelector('#download-csv')
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(csv));
link.setAttribute('download', 'thistextissolongitmustabsolutelybeuniqueright');
}
document.querySelector('#download-csv').click()
}
function parse_id(idstr) {
return idstr.split('_')[0].split('-')[1]
}
var observer = new IntersectionObserver(function(entries, observer) {
entries.forEach(entry => {
eid = parse_id(entry.target.id)
if (entry['intersectionRatio'] == 1 && subjs[eid]['been_on_screen'] == false) {
subjs[eid]['been_on_screen'] = true
}
else if (entry['intersectionRatio'] == 0 && subjs[eid]['been_on_screen'] == true && subjs[eid]['report'] == -1) {
subjs[eid]['report'] = 1
observer.unobserve(entry.target)
updateCounts();
radioid = 'inlineRadio' + eid
document.querySelectorAll('[name=' + radioid + ']')[0].checked = true
}
/* Here's where we deal with every intersection */
});
}
, {root:document.querySelector('#scrollArea'), threshold:[0,1]});
</script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<style type="text/css">
.sub-report-title {}
.run-title {}
h1 { padding-top: 35px; }
h2 { padding-top: 20px; }
h3 { padding-top: 15px; }
.elem-desc {}
.elem-caption {
margin-top: 15px
margin-bottom: 0;
}
.elem-filename {}
div.elem-image {
width: 100%;
page-break-before:always;
}
.elem-image object.svg-reportlet {
width: 100%;
padding-bottom: 5px;
}
body {
padding: 65px 10px 10px;
}
.boiler-html {
font-family: "Bitstream Charter", "Georgia", Times;
margin: 20px 25px;
padding: 10px;
background-color: #F8F9FA;
}
div#boilerplate pre {
margin: 20px 25px;
padding: 10px;
background-color: #F8F9FA;
}
</style>
</head>
<body>"""
html_foot = """<script type="text/javascript">
function toggle(id) {
var element = document.getElementById(id);
if(element.style.display == 'block')
element.style.display = 'none';
else
element.style.display = 'block';
}
</script>
<script>
updateCounts();
document.querySelectorAll('[id^="id"]').forEach(img => {observer.observe(img)})
</script>
</body>
</html>"""
reviewer_initials = """
<p> Initials: <input type="text" id="initials_box" oninput="update_all('rater', this.value)"></p>
"""
nav= """<nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light">
<div class="navbar-header">
Ratings: <span id="nrpass" class="badge badge-success">0</span> <span id="nrfail" class="badge badge-danger">0</span> <span id="nrtodo" class="badge badge-warning">0</span>
</div>
<div class="navbar-text">
<button type="button" class="btn btn-info btn-sm" id="csv_download" onclick="get_csv(subjs)">Download TSV</button>
</div>
</div>
</nav>"""
def _generate_html_head(dl_file_name):
"""
generate an html head block where the name of the downloaded file is set appropriately.
Parameters
----------
dl_file_name : str
Returns
-------
str
"""
return html_head.replace('thistextissolongitmustabsolutelybeuniqueright', dl_file_name)
|
html_head = '<?xml version="1.0" encoding="utf-8" ?>\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">\n<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">\n<head>\n<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n<meta name="generator" content="Docutils 0.12: http://docutils.sourceforge.net/" />\n<title></title>\n<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>\n<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>\n<script type="text/javascript">\n var subjs = []\n function updateCounts(){\n var counts = {report:{"-1":0, "1":0, "0":0}}\n\n subjs.forEach(function(val, idx, arr){\n counts.report[val.report] += 1;\n })\n\n $("#nrpass").text(counts.report["1"])\n $("#nrfail").text(counts.report["0"])\n $("#nrtodo").text(counts.report["-1"])\n }\n\n function qc_update(run_id, stage, value) {\n if (stage == \'report\') {\n subjs[run_id][stage] = parseInt(value)\n updateCounts();\n }\n else {\n subjs[run_id][stage] = value\n }\n }\n\n function update_all(stage, value) {\n subjs.forEach( subj => {subj[stage]=value})\n }\n\n function get_csv(items) {\n // https://stackoverflow.com/questions/44396943/generate-a-csv-file-from-a-javascript-array-of-objects\n let csv = \'\'\n\n // Loop the array of objects\n for(let row = 0; row < items.length; row++){\n let keysAmount = Object.keys(items[row]).length\n let keysCounter = 0\n\n // If this is the first row, generate the headings\n if(row === 0){\n\n // Loop each property of the object\n for(let key in items[row]){\n\n // This is to not add a comma at the last cell\n // The \'\\r\\n\' adds a new line\n csv += key + (keysCounter+1 < keysAmount ? \'\\t\' : \'\\r\\n\' )\n keysCounter++\n }\n let keysCounterb = 0\n for(let key in items[row]){\n csv += items[row][key] + (keysCounterb+1 < keysAmount ? \'\\t\' : \'\\r\\n\' )\n keysCounterb++\n }\n }else{\n for(let key in items[row]){\n csv += items[row][key] + (keysCounter+1 < keysAmount ? \'\\t\' : \'\\r\\n\' )\n keysCounter++\n }\n }\n\n keysCounter = 0\n }\n\n // Once we are done looping, download the .csv by creating a link\n // if a link has already been created, update it\n if (document.querySelector(\'#download-csv\') == null){\n let link = document.createElement(\'a\')\n link.id = \'download-csv\'\n link.setAttribute(\'href\', \'data:text/plain;charset=utf-8,\' + encodeURIComponent(csv));\n link.setAttribute(\'download\', \'thistextissolongitmustabsolutelybeuniqueright\');\n document.body.appendChild(link)\n } else {\n let link = document.querySelector(\'#download-csv\')\n link.setAttribute(\'href\', \'data:text/plain;charset=utf-8,\' + encodeURIComponent(csv));\n link.setAttribute(\'download\', \'thistextissolongitmustabsolutelybeuniqueright\');\n }\n document.querySelector(\'#download-csv\').click()\n }\n\n function parse_id(idstr) {\n return idstr.split(\'_\')[0].split(\'-\')[1]\n }\n\n var observer = new IntersectionObserver(function(entries, observer) {\n entries.forEach(entry => {\n eid = parse_id(entry.target.id)\n if (entry[\'intersectionRatio\'] == 1 && subjs[eid][\'been_on_screen\'] == false) {\n subjs[eid][\'been_on_screen\'] = true\n }\n else if (entry[\'intersectionRatio\'] == 0 && subjs[eid][\'been_on_screen\'] == true && subjs[eid][\'report\'] == -1) {\n subjs[eid][\'report\'] = 1\n observer.unobserve(entry.target)\n updateCounts();\n radioid = \'inlineRadio\' + eid\n document.querySelectorAll(\'[name=\' + radioid + \']\')[0].checked = true\n }\n /* Here\'s where we deal with every intersection */\n });\n }\n , {root:document.querySelector(\'#scrollArea\'), threshold:[0,1]});\n\n </script>\n<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">\n<style type="text/css">\n.sub-report-title {}\n.run-title {}\n\nh1 { padding-top: 35px; }\nh2 { padding-top: 20px; }\nh3 { padding-top: 15px; }\n\n.elem-desc {}\n.elem-caption {\n margin-top: 15px\n margin-bottom: 0;\n}\n.elem-filename {}\n\ndiv.elem-image {\n width: 100%;\n page-break-before:always;\n}\n\n.elem-image object.svg-reportlet {\n width: 100%;\n padding-bottom: 5px;\n}\nbody {\n padding: 65px 10px 10px;\n}\n\n.boiler-html {\n font-family: "Bitstream Charter", "Georgia", Times;\n margin: 20px 25px;\n padding: 10px;\n background-color: #F8F9FA;\n}\n\ndiv#boilerplate pre {\n margin: 20px 25px;\n padding: 10px;\n background-color: #F8F9FA;\n}\n\n</style>\n</head>\n<body>'
html_foot = '<script type="text/javascript">\n function toggle(id) {\n var element = document.getElementById(id);\n if(element.style.display == \'block\')\n element.style.display = \'none\';\n else\n element.style.display = \'block\';\n }\n\n</script>\n<script>\n\nupdateCounts();\ndocument.querySelectorAll(\'[id^="id"]\').forEach(img => {observer.observe(img)})\n\n</script>\n</body>\n</html>'
reviewer_initials = '\n <p> Initials: <input type="text" id="initials_box" oninput="update_all(\'rater\', this.value)"></p>\n'
nav = '<nav class="navbar fixed-top navbar-expand-lg navbar-light bg-light">\n <div class="navbar-header">\n Ratings: <span id="nrpass" class="badge badge-success">0</span> <span id="nrfail" class="badge badge-danger">0</span> <span id="nrtodo" class="badge badge-warning">0</span>\n </div>\n <div class="navbar-text">\n <button type="button" class="btn btn-info btn-sm" id="csv_download" onclick="get_csv(subjs)">Download TSV</button>\n\n </div>\n</div>\n</nav>'
def _generate_html_head(dl_file_name):
"""
generate an html head block where the name of the downloaded file is set appropriately.
Parameters
----------
dl_file_name : str
Returns
-------
str
"""
return html_head.replace('thistextissolongitmustabsolutelybeuniqueright', dl_file_name)
|
"""Dot notation for dictionary."""
class Map(dict):
"""dot.notation access to dictionary attributes.
Args:
dict (dict): dictionary to map.
"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
|
"""Dot notation for dictionary."""
class Map(dict):
"""dot.notation access to dictionary attributes.
Args:
dict (dict): dictionary to map.
"""
__getattr__ = dict.get
__setattr__ = dict.__setitem__
__delattr__ = dict.__delitem__
|
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/max-level-sum-in-binary-tree/1
def maxLevelSum(root):
# Code here
h = {}
level = 0
getLevelSum(root, level, h)
return max(h.values())
def getLevelSum(root, level, h):
if root == None:
return
if level not in h:
h[level] = 0
h[level] += root.data
getLevelSum(root.left, level+1, h)
getLevelSum(root.right, level+1, h)
|
def max_level_sum(root):
h = {}
level = 0
get_level_sum(root, level, h)
return max(h.values())
def get_level_sum(root, level, h):
if root == None:
return
if level not in h:
h[level] = 0
h[level] += root.data
get_level_sum(root.left, level + 1, h)
get_level_sum(root.right, level + 1, h)
|
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
class BigQueryObject(object):
"""A BigQueryObject holds data that will be read from/written to BigQuery."""
def __eq__(self, other):
return self.__dict__ == other.__dict__
@staticmethod
def get_bigquery_attributes():
"""Returns a list of attributes that exist in the BigQuery schema.
These attributes should be strings.
"""
raise NotImplementedError()
def as_bigquery_row(self):
"""Returns data in a suitable format for writing to BigQuery.
The default behavior constructs a dictionary from the attributes listed
by get_bigquery_attributes and their values. This behavior can be
overridden.
"""
return {attr: self.__dict__.get(attr)
for attr in self.get_bigquery_attributes()}
@classmethod
def from_bigquery_row(cls, row):
"""Creates an instance of cls from a BigQuery row.
Args:
row: dictionary in the form {field: value} where field is in
get_bigquery_attributes().
"""
obj = cls()
for field, value in row.items():
obj.__dict__[field] = value
return obj
class CQAttempt(BigQueryObject):
"""A CQAttempt represents a single CQ attempt.
It is created by aggregating all CQEvents for a given attempt.
"""
def __init__(self):
# Consistent between events for a given attempt
self.attempt_start_msec = None
self.cq_name = None
self.issue = None
self.patchset = None
self.dry_run = False
# Patch event timestamps
self.first_start_msec = None
self.last_start_msec = None
self.first_stop_msec = None
self.last_stop_msec = None
self.patch_committed_msec = None
self.patch_started_to_commit_msec = None
self.patch_failed_msec = None
self.vcs_commit_latency_sec = None
self.click_to_failure_sec = None
self.click_to_patch_committed_sec = None
self.click_to_result_sec = None
# Patch event bools
self.committed = False
self.was_throttled = False
self.waited_for_tree = False
self.failed = False
# Verifier event timestamps
self.first_verifier_trigger_msec = None
self.patch_verifier_pass_msec = None
self.cq_launch_latency_sec = None
self.verifier_pass_latency_sec = None
self.tree_check_and_throttle_latency_sec = None
# Verifier event bools
self.no_tryjobs_launched = False
self.custom_trybots = False
self.failure_reason = None
self.max_failure_msec = None
self.fail_type = None
self.infra_failures = 0
self.compile_failures = 0
self.test_failures = 0
self.invalid_test_results_failures = 0
self.patch_failures = 0
self.total_failures = 0
self.contributing_bbucket_ids = None
self.earliest_equivalent_patchset = None
self.attempt_key = None
@staticmethod
def get_bigquery_attributes():
return [
'attempt_start_msec',
'first_start_msec',
'last_start_msec',
'cq_name',
'first_stop_msec',
'last_stop_msec',
'committed',
'was_throttled',
'waited_for_tree',
'issue',
'patchset',
'dry_run',
'cq_launch_latency_sec',
'verifier_pass_latency_sec',
'tree_check_and_throttle_latency_sec',
'no_tryjobs_launched',
'custom_trybots',
'failed',
'infra_failures',
'compile_failures',
'test_failures',
'invalid_test_results_failures',
'patch_failures',
'total_failures',
'fail_type',
'contributing_bbucket_ids',
'vcs_commit_latency_sec',
'click_to_patch_committed_sec',
'click_to_failure_sec',
'click_to_result_sec',
'earliest_equivalent_patchset',
'attempt_key',
]
class CQEvent(BigQueryObject):
"""A CQEvent represents event data reported to BigQuery from CQ.
CQEvents are aggregated to make CQAttempts.
"""
def __init__(self):
self.timestamp_millis = None
self.action = None
self.attempt_start_usec = None
self.cq_name = None
self.issue = None
self.patchset = None
self.failure_reason = None
self.dry_run = False
self.contributing_buildbucket_ids = None
self.earliest_equivalent_patchset = None
self.attempt_key = None
@staticmethod
def get_bigquery_attributes():
return [
'timestamp_millis',
'action',
'attempt_start_usec',
'cq_name',
'issue',
'patchset',
'dry_run',
'failure_reason',
'contributing_buildbucket_ids',
'earliest_equivalent_patchset',
'attempt_key',
]
|
class Bigqueryobject(object):
"""A BigQueryObject holds data that will be read from/written to BigQuery."""
def __eq__(self, other):
return self.__dict__ == other.__dict__
@staticmethod
def get_bigquery_attributes():
"""Returns a list of attributes that exist in the BigQuery schema.
These attributes should be strings.
"""
raise not_implemented_error()
def as_bigquery_row(self):
"""Returns data in a suitable format for writing to BigQuery.
The default behavior constructs a dictionary from the attributes listed
by get_bigquery_attributes and their values. This behavior can be
overridden.
"""
return {attr: self.__dict__.get(attr) for attr in self.get_bigquery_attributes()}
@classmethod
def from_bigquery_row(cls, row):
"""Creates an instance of cls from a BigQuery row.
Args:
row: dictionary in the form {field: value} where field is in
get_bigquery_attributes().
"""
obj = cls()
for (field, value) in row.items():
obj.__dict__[field] = value
return obj
class Cqattempt(BigQueryObject):
"""A CQAttempt represents a single CQ attempt.
It is created by aggregating all CQEvents for a given attempt.
"""
def __init__(self):
self.attempt_start_msec = None
self.cq_name = None
self.issue = None
self.patchset = None
self.dry_run = False
self.first_start_msec = None
self.last_start_msec = None
self.first_stop_msec = None
self.last_stop_msec = None
self.patch_committed_msec = None
self.patch_started_to_commit_msec = None
self.patch_failed_msec = None
self.vcs_commit_latency_sec = None
self.click_to_failure_sec = None
self.click_to_patch_committed_sec = None
self.click_to_result_sec = None
self.committed = False
self.was_throttled = False
self.waited_for_tree = False
self.failed = False
self.first_verifier_trigger_msec = None
self.patch_verifier_pass_msec = None
self.cq_launch_latency_sec = None
self.verifier_pass_latency_sec = None
self.tree_check_and_throttle_latency_sec = None
self.no_tryjobs_launched = False
self.custom_trybots = False
self.failure_reason = None
self.max_failure_msec = None
self.fail_type = None
self.infra_failures = 0
self.compile_failures = 0
self.test_failures = 0
self.invalid_test_results_failures = 0
self.patch_failures = 0
self.total_failures = 0
self.contributing_bbucket_ids = None
self.earliest_equivalent_patchset = None
self.attempt_key = None
@staticmethod
def get_bigquery_attributes():
return ['attempt_start_msec', 'first_start_msec', 'last_start_msec', 'cq_name', 'first_stop_msec', 'last_stop_msec', 'committed', 'was_throttled', 'waited_for_tree', 'issue', 'patchset', 'dry_run', 'cq_launch_latency_sec', 'verifier_pass_latency_sec', 'tree_check_and_throttle_latency_sec', 'no_tryjobs_launched', 'custom_trybots', 'failed', 'infra_failures', 'compile_failures', 'test_failures', 'invalid_test_results_failures', 'patch_failures', 'total_failures', 'fail_type', 'contributing_bbucket_ids', 'vcs_commit_latency_sec', 'click_to_patch_committed_sec', 'click_to_failure_sec', 'click_to_result_sec', 'earliest_equivalent_patchset', 'attempt_key']
class Cqevent(BigQueryObject):
"""A CQEvent represents event data reported to BigQuery from CQ.
CQEvents are aggregated to make CQAttempts.
"""
def __init__(self):
self.timestamp_millis = None
self.action = None
self.attempt_start_usec = None
self.cq_name = None
self.issue = None
self.patchset = None
self.failure_reason = None
self.dry_run = False
self.contributing_buildbucket_ids = None
self.earliest_equivalent_patchset = None
self.attempt_key = None
@staticmethod
def get_bigquery_attributes():
return ['timestamp_millis', 'action', 'attempt_start_usec', 'cq_name', 'issue', 'patchset', 'dry_run', 'failure_reason', 'contributing_buildbucket_ids', 'earliest_equivalent_patchset', 'attempt_key']
|
A = [10,13,7]
B = [1,2,3,4,5,6]
def sum_all(A, B):
ASum = sum(A)
#print(ASum)
BSum = sum(B)
#print(BSum)
TSum = ASum+BSum
#print(TSum)
return ASum, BSum, TSum
ASum, BSum, TSum = sum_all(A,B)
print('The sum of list 1 is '+str(ASum))
print('The sum of list 2 is '+str(BSum))
print('The sum of both lists is '+str(TSum))
|
a = [10, 13, 7]
b = [1, 2, 3, 4, 5, 6]
def sum_all(A, B):
a_sum = sum(A)
b_sum = sum(B)
t_sum = ASum + BSum
return (ASum, BSum, TSum)
(a_sum, b_sum, t_sum) = sum_all(A, B)
print('The sum of list 1 is ' + str(ASum))
print('The sum of list 2 is ' + str(BSum))
print('The sum of both lists is ' + str(TSum))
|
class ScriptBase(type):
def __init__(cls, name, bases, attrs):
if cls is None:
return
if not hasattr(cls, "plugins"):
cls.plugins = []
else:
cls.plugins.append(cls)
class ServerBase:
__metaclass__ = ScriptBase
def __init__(self):
super(ServerBase, self).__init__()
def setup(self, nysa):
self.n = nysa
|
class Scriptbase(type):
def __init__(cls, name, bases, attrs):
if cls is None:
return
if not hasattr(cls, 'plugins'):
cls.plugins = []
else:
cls.plugins.append(cls)
class Serverbase:
__metaclass__ = ScriptBase
def __init__(self):
super(ServerBase, self).__init__()
def setup(self, nysa):
self.n = nysa
|
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# Find the max and then break the array in two parts.
# Then recursively
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def maxTree(nums, start, end):
if start >= end:
return None
else:
opt = (nums[start], start)
for i in xrange(start+1, end):
if nums[i] > opt[0]:
opt = (nums[i], i)
root = TreeNode(opt[0])
root.left = maxTree(nums, start, opt[1])
root.right = maxTree(nums, opt[1]+1, end)
return root
if nums is None:
return None
else:
return maxTree(nums, 0, len(nums))
|
class Solution(object):
def construct_maximum_binary_tree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
def max_tree(nums, start, end):
if start >= end:
return None
else:
opt = (nums[start], start)
for i in xrange(start + 1, end):
if nums[i] > opt[0]:
opt = (nums[i], i)
root = tree_node(opt[0])
root.left = max_tree(nums, start, opt[1])
root.right = max_tree(nums, opt[1] + 1, end)
return root
if nums is None:
return None
else:
return max_tree(nums, 0, len(nums))
|
class BuildProducts(object):
'''A class to help keep track of build products in the build.
Really this is just a wrapper around a dict stored at the key
'BUILD_TOOL' in an environment. This class doesn't worry about
what stored in that dict, though it's generally things like
SharedLib configurators and such.
'''
def __init__(self, env):
'''This looks up or, if necessary, creates a few keys in the
`env` that are used by this class.
'''
self.env = env
try:
products = env['BUILD_TOOL']
except KeyError:
env['BUILD_TOOL'] = {}
products = env['BUILD_TOOL']
try:
products = products['BUILD_PRODUCTS']
except KeyError:
products['BUILD_PRODUCTS'] = {}
products = products['BUILD_PRODUCTS']
self.products = products
def __getitem__(self, name):
'''Get the build product at `name`.
'''
return self.products[name]
def __setitem__(self, name, product):
'''Set the build product at `name` to `product`.
'''
self.products[name] = product
|
class Buildproducts(object):
"""A class to help keep track of build products in the build.
Really this is just a wrapper around a dict stored at the key
'BUILD_TOOL' in an environment. This class doesn't worry about
what stored in that dict, though it's generally things like
SharedLib configurators and such.
"""
def __init__(self, env):
"""This looks up or, if necessary, creates a few keys in the
`env` that are used by this class.
"""
self.env = env
try:
products = env['BUILD_TOOL']
except KeyError:
env['BUILD_TOOL'] = {}
products = env['BUILD_TOOL']
try:
products = products['BUILD_PRODUCTS']
except KeyError:
products['BUILD_PRODUCTS'] = {}
products = products['BUILD_PRODUCTS']
self.products = products
def __getitem__(self, name):
"""Get the build product at `name`.
"""
return self.products[name]
def __setitem__(self, name, product):
"""Set the build product at `name` to `product`.
"""
self.products[name] = product
|
"""Meta Content presentation"""
amendment_header = [
"Amendment of Directive 85/611/EEC",
"Amendment of Directive 93/6/EEC",
"Amendment of Directive 2000/12/EC"
]
test_presentations = [
"Article 8 is replaced by the following:",
"In Article 7, paragraphs 1 and 2 are "
"replaced by the following:",
"Article 6 is amended as follows:",
"Article 2 is replaced by the following:",
"Article 1 is replaced by the following:",
"In Article 49, the following subparagraph is added "
"at the end of paragraph 2:",
"In Article 37, the following point (c) is added:",
"The following Chapter 5a is inserted after Article 72:",
"Article 73 is amended as follows:",
"(a) the title is replaced by the following:",
"(b) paragraphs 1, 2, 3 and 4 are replaced by the following:",
"In Part Two, Title I, the title of Chapter 6 is replaced by the "
"following:",
"in Article 11(15), point (b) is deleted;",
"in Article 89, the following paragraph is inserted:",
"the following Chapter is added in Title IV:",
"In Article 5 of Directive 85/611/EEC, paragraph 4 shall "
"be replaced by the following:",
"Article 2(2) shall be replaced by the following:"
]
|
"""Meta Content presentation"""
amendment_header = ['Amendment of Directive 85/611/EEC', 'Amendment of Directive 93/6/EEC', 'Amendment of Directive 2000/12/EC']
test_presentations = ['Article 8 is replaced by the following:', 'In Article 7, paragraphs 1 and 2 are replaced by the following:', 'Article 6 is amended as follows:', 'Article 2 is replaced by the following:', 'Article 1 is replaced by the following:', 'In Article 49, the following subparagraph is added at the end of paragraph 2:', 'In Article 37, the following point (c) is added:', 'The following Chapter 5a is inserted after Article 72:', 'Article 73 is amended as follows:', '(a) the title is replaced by the following:', '(b) paragraphs 1, 2, 3 and 4 are replaced by the following:', 'In Part Two, Title I, the title of Chapter 6 is replaced by the following:', 'in Article 11(15), point (b) is deleted;', 'in Article 89, the following paragraph is inserted:', 'the following Chapter is added in Title IV:', 'In Article 5 of Directive 85/611/EEC, paragraph 4 shall be replaced by the following:', 'Article 2(2) shall be replaced by the following:']
|
class ResourceObject:
def __init__(self,
resource_type,
resource_name,
mem_limit_threshold,
mem_request_threshold,
cpu_limit_threshold,
cpu_request_threshold,
max_hit):
self.resource_type = resource_type
self.resource_name = resource_name
self.cpu_limit = 0
self.mem_limit = 0
self.cpu_request = 0
self.mem_request = 0
self.mem_hits = 0
self.cpu_hits = 0
self.mem_limit_threshold = mem_limit_threshold
self.mem_request_threshold = mem_request_threshold
self.cpu_limit_threshold = cpu_limit_threshold
self.cpu_request_threshold = cpu_request_threshold
self.max_hit = max_hit
def __hit_cpu(self):
if self.cpu_limit > self.cpu_limit_threshold or self.cpu_request > self.cpu_request_threshold:
self.cpu_hits += 1
if self.cpu_hits > self.max_hit:
self.cpu_hits = 1
else:
self.cpu_hits = 0
def __hit_mem(self):
if self.mem_limit > self.mem_limit_threshold or self.mem_request > self.mem_request_threshold:
self.mem_hits += 1
if self.mem_hits > self.max_hit:
self.mem_hits = 1
else:
self.mem_hits = 0
def update_memory(self, request, limit):
self.mem_limit = limit
self.mem_request = request
self.__hit_mem()
def update_cpu(self, request, limit):
self.cpu_limit = limit
self.cpu_request = request
self.__hit_cpu()
def get_notification(self, report_type):
message = ''
cpu_message = ''
mem_message = ''
if self.cpu_hits > 0:
cpu_message = f" [cpu request: {self.cpu_request}% , cpu limit: {self.cpu_limit}%]"
if self.mem_hits > 0:
mem_message = f" [memory request: {self.mem_request}% , memory limit: {self.mem_limit}%]"
if report_type == "all" and (self.cpu_hits == 1 or self.mem_hits == 1):
if self.cpu_hits > 0 and self.mem_hits > 0:
message = ' and'
message = f"{cpu_message}{message}{mem_message}"
elif report_type == 'cpu' and self.cpu_hits == 1:
message = cpu_message
elif report_type == 'memory' and self.mem_hits == 1:
message = mem_message
if message != '':
message = f"[{self.resource_type}] {self.resource_name} is under stress:{message}"
return message
|
class Resourceobject:
def __init__(self, resource_type, resource_name, mem_limit_threshold, mem_request_threshold, cpu_limit_threshold, cpu_request_threshold, max_hit):
self.resource_type = resource_type
self.resource_name = resource_name
self.cpu_limit = 0
self.mem_limit = 0
self.cpu_request = 0
self.mem_request = 0
self.mem_hits = 0
self.cpu_hits = 0
self.mem_limit_threshold = mem_limit_threshold
self.mem_request_threshold = mem_request_threshold
self.cpu_limit_threshold = cpu_limit_threshold
self.cpu_request_threshold = cpu_request_threshold
self.max_hit = max_hit
def __hit_cpu(self):
if self.cpu_limit > self.cpu_limit_threshold or self.cpu_request > self.cpu_request_threshold:
self.cpu_hits += 1
if self.cpu_hits > self.max_hit:
self.cpu_hits = 1
else:
self.cpu_hits = 0
def __hit_mem(self):
if self.mem_limit > self.mem_limit_threshold or self.mem_request > self.mem_request_threshold:
self.mem_hits += 1
if self.mem_hits > self.max_hit:
self.mem_hits = 1
else:
self.mem_hits = 0
def update_memory(self, request, limit):
self.mem_limit = limit
self.mem_request = request
self.__hit_mem()
def update_cpu(self, request, limit):
self.cpu_limit = limit
self.cpu_request = request
self.__hit_cpu()
def get_notification(self, report_type):
message = ''
cpu_message = ''
mem_message = ''
if self.cpu_hits > 0:
cpu_message = f' [cpu request: {self.cpu_request}% , cpu limit: {self.cpu_limit}%]'
if self.mem_hits > 0:
mem_message = f' [memory request: {self.mem_request}% , memory limit: {self.mem_limit}%]'
if report_type == 'all' and (self.cpu_hits == 1 or self.mem_hits == 1):
if self.cpu_hits > 0 and self.mem_hits > 0:
message = ' and'
message = f'{cpu_message}{message}{mem_message}'
elif report_type == 'cpu' and self.cpu_hits == 1:
message = cpu_message
elif report_type == 'memory' and self.mem_hits == 1:
message = mem_message
if message != '':
message = f'[{self.resource_type}] {self.resource_name} is under stress:{message}'
return message
|
M = []
size1 = int(input())
for i in range(size1):
row = []
for j in range(size1):
row.append(int(input()))
M.append(row)
M2 = []
for i in range(size1):
row = []
for j in range(size1):
row.append(int(input()))
M2.append(row)
result = [ [ 0 for i in range(size1) ] for j in range(size1) ]
for i in range(size1):
for j in range(size1):
for k in range(size1):
result[i][j] += M[i][k] * M2[k][j]
for i in range(size1):
print(result[i])
|
m = []
size1 = int(input())
for i in range(size1):
row = []
for j in range(size1):
row.append(int(input()))
M.append(row)
m2 = []
for i in range(size1):
row = []
for j in range(size1):
row.append(int(input()))
M2.append(row)
result = [[0 for i in range(size1)] for j in range(size1)]
for i in range(size1):
for j in range(size1):
for k in range(size1):
result[i][j] += M[i][k] * M2[k][j]
for i in range(size1):
print(result[i])
|
def currencyCodes():
"""
This function returns a list of currency codes.
It looks simple, but it can be improved without
affecting other components.
"""
currency_codes = ['USD', 'EUR', 'AUD']
return currency_codes
|
def currency_codes():
"""
This function returns a list of currency codes.
It looks simple, but it can be improved without
affecting other components.
"""
currency_codes = ['USD', 'EUR', 'AUD']
return currency_codes
|
MYSQL_HOST = 'localhost'
MYSQL_DBNAME = 'spider'
MYSQL_USER = 'root'
MYSQL_PASSWD = '123456'
MYSQL_PORT = 3306
MYSQL_CHARSET = 'utf8'
MYSQL_UNICODE = True
|
mysql_host = 'localhost'
mysql_dbname = 'spider'
mysql_user = 'root'
mysql_passwd = '123456'
mysql_port = 3306
mysql_charset = 'utf8'
mysql_unicode = True
|
class Concrete:
x: int
@require(lambda x: x > 0)
def __init__(self, x: int) -> None:
self.x = x
@require(lambda self: self.x > 2)
@require(lambda number: number > 0)
def some_func(self, number: int) -> int:
"""Do something."""
class Reference:
pass
__book_url__ = "dummy"
__book_version__ = "dummy"
associate_ref_with(Reference)
|
class Concrete:
x: int
@require(lambda x: x > 0)
def __init__(self, x: int) -> None:
self.x = x
@require(lambda self: self.x > 2)
@require(lambda number: number > 0)
def some_func(self, number: int) -> int:
"""Do something."""
class Reference:
pass
__book_url__ = 'dummy'
__book_version__ = 'dummy'
associate_ref_with(Reference)
|
squares = [1, 4, 9, 16, 25]
i = 0
while i < len(squares):
print(i, squares[i])
i = i + 1
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
for i in range(len(words)):
print(i, words[i], len(words[i]))
|
squares = [1, 4, 9, 16, 25]
i = 0
while i < len(squares):
print(i, squares[i])
i = i + 1
words = ['cat', 'window', 'defenestrate']
for w in words:
print(w, len(w))
for i in range(len(words)):
print(i, words[i], len(words[i]))
|
def ov_range(a_1,a_2,b_1,b_2):
big_a=a_1
small_a=a_2
big_b=b_1
small_b=b_1
if a_1<a_2:
big_a=a_2
small_a=a_1
elif a_1>a_2:
big_a=a_1
small_a=a_2
if b_1>b_2:
big_b=b_1
small_b=b_2
elif b_1<b_2:
big_b=b_2
small_b=b_1
#print(big_a, '\n', small_a, '\n', big_b, '\n', small_b)
interval_1=big_a - small_a
interval_2=big_b - small_b
# when they dont overlap
if small_a > big_b:
return 0
elif small_b>big_a:
return 0
# When a dips into b
if big_b>big_a and small_a>small_b:
interval_1 = big_a - small_a
return interval_1
#when b completly overlaps a
if big_a>big_b and small_b>small_a:
interval_1 = big_b - small_b
return interval_1
elif big_a>big_b and big_b>small_a:
interval_1= big_b - small_a
return interval_1
#when a overlaps in b
if small_b<big_a:
interval_1=big_a - small_b
return interval_1
if small_b<big_b:
interval_2=big_b - small_a
#when b overlap in a
if big_a>big_b and big_b>small_a:
interval_1= big_b - small_a
return interval_1
#Good job
# Test function
def test(a1, a2, b1, b2, expected):
print(a1, a2, '&', b1, b2, '=>',
ov_range(a1, a2, b1, b2), '\t',
ov_range(a1, a2, b1, b2) == expected)
test(2,5,-1,3, 1)
test(3, 0, 2, 4, 1)
test(0, 5, 0, 1000, 5)
test(0, 1000, 0, 5, 5)
test(1, 4, 0, 5, 3)
test(0, 5, 2, 4, 2)
test(2,4,0,5, 2)
test(1,10,-5,-5,0)
test(10,1,5,15,5)
test(-5, 0, 2, 4, 0)
test(-5, -5, 2, 4, 0)
test(5, 0, 1, 1, 0)
test(7, -2, -1, 4, 5)
|
def ov_range(a_1, a_2, b_1, b_2):
big_a = a_1
small_a = a_2
big_b = b_1
small_b = b_1
if a_1 < a_2:
big_a = a_2
small_a = a_1
elif a_1 > a_2:
big_a = a_1
small_a = a_2
if b_1 > b_2:
big_b = b_1
small_b = b_2
elif b_1 < b_2:
big_b = b_2
small_b = b_1
interval_1 = big_a - small_a
interval_2 = big_b - small_b
if small_a > big_b:
return 0
elif small_b > big_a:
return 0
if big_b > big_a and small_a > small_b:
interval_1 = big_a - small_a
return interval_1
if big_a > big_b and small_b > small_a:
interval_1 = big_b - small_b
return interval_1
elif big_a > big_b and big_b > small_a:
interval_1 = big_b - small_a
return interval_1
if small_b < big_a:
interval_1 = big_a - small_b
return interval_1
if small_b < big_b:
interval_2 = big_b - small_a
if big_a > big_b and big_b > small_a:
interval_1 = big_b - small_a
return interval_1
def test(a1, a2, b1, b2, expected):
print(a1, a2, '&', b1, b2, '=>', ov_range(a1, a2, b1, b2), '\t', ov_range(a1, a2, b1, b2) == expected)
test(2, 5, -1, 3, 1)
test(3, 0, 2, 4, 1)
test(0, 5, 0, 1000, 5)
test(0, 1000, 0, 5, 5)
test(1, 4, 0, 5, 3)
test(0, 5, 2, 4, 2)
test(2, 4, 0, 5, 2)
test(1, 10, -5, -5, 0)
test(10, 1, 5, 15, 5)
test(-5, 0, 2, 4, 0)
test(-5, -5, 2, 4, 0)
test(5, 0, 1, 1, 0)
test(7, -2, -1, 4, 5)
|
#!/usr/bin/env python
"""
_Agent_t_
Agent test methods
"""
__all__ = []
|
"""
_Agent_t_
Agent test methods
"""
__all__ = []
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file")
all_content = """filegroup(name = "all", srcs = glob(["**"]), visibility = ["//visibility:public"])"""
def include_third_party_repositories():
http_archive(
name = "com_github_libevent",
build_file_content = all_content,
strip_prefix = "libevent-2.1.8-stable",
urls = ["https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz"],
)
http_archive(
name = "com_github_libtbb",
build_file = "//bazel:tbb.BUILD",
strip_prefix = "oneTBB-2020.3",
urls = ["https://github.com/oneapi-src/oneTBB/archive/v2020.3.tar.gz"],
sha256 = "ebc4f6aa47972daed1f7bf71d100ae5bf6931c2e3144cf299c8cc7d041dca2f3",
)
http_archive(
name = "com_github_libtbb_osx",
build_file = "//bazel:osx.tbb.BUILD",
strip_prefix = "oneTBB-2020.3",
urls = ["https://github.com/oneapi-src/oneTBB/archive/v2020.3.tar.gz"],
sha256 = "ebc4f6aa47972daed1f7bf71d100ae5bf6931c2e3144cf299c8cc7d041dca2f3",
)
http_archive(
name = "com_github_fmtlib_fmt",
sha256 = "4c0741e10183f75d7d6f730b8708a99b329b2f942dad5a9da3385ab92bb4a15c",
strip_prefix = "fmt-5.3.0",
urls = ["https://github.com/fmtlib/fmt/releases/download/5.3.0/fmt-5.3.0.zip"],
build_file = "//bazel:fmtlib.BUILD",
)
http_archive(
name = "com_github_gabime_spdlog",
build_file = "//bazel:spdlog.BUILD",
sha256 = "160845266e94db1d4922ef755637f6901266731c4cb3b30b45bf41efa0e6ab70",
strip_prefix = "spdlog-1.3.1",
urls = ["https://github.com/gabime/spdlog/archive/v1.3.1.tar.gz"],
)
|
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive', 'http_file')
all_content = 'filegroup(name = "all", srcs = glob(["**"]), visibility = ["//visibility:public"])'
def include_third_party_repositories():
http_archive(name='com_github_libevent', build_file_content=all_content, strip_prefix='libevent-2.1.8-stable', urls=['https://github.com/libevent/libevent/releases/download/release-2.1.8-stable/libevent-2.1.8-stable.tar.gz'])
http_archive(name='com_github_libtbb', build_file='//bazel:tbb.BUILD', strip_prefix='oneTBB-2020.3', urls=['https://github.com/oneapi-src/oneTBB/archive/v2020.3.tar.gz'], sha256='ebc4f6aa47972daed1f7bf71d100ae5bf6931c2e3144cf299c8cc7d041dca2f3')
http_archive(name='com_github_libtbb_osx', build_file='//bazel:osx.tbb.BUILD', strip_prefix='oneTBB-2020.3', urls=['https://github.com/oneapi-src/oneTBB/archive/v2020.3.tar.gz'], sha256='ebc4f6aa47972daed1f7bf71d100ae5bf6931c2e3144cf299c8cc7d041dca2f3')
http_archive(name='com_github_fmtlib_fmt', sha256='4c0741e10183f75d7d6f730b8708a99b329b2f942dad5a9da3385ab92bb4a15c', strip_prefix='fmt-5.3.0', urls=['https://github.com/fmtlib/fmt/releases/download/5.3.0/fmt-5.3.0.zip'], build_file='//bazel:fmtlib.BUILD')
http_archive(name='com_github_gabime_spdlog', build_file='//bazel:spdlog.BUILD', sha256='160845266e94db1d4922ef755637f6901266731c4cb3b30b45bf41efa0e6ab70', strip_prefix='spdlog-1.3.1', urls=['https://github.com/gabime/spdlog/archive/v1.3.1.tar.gz'])
|
class ContactInformation(object):
def __init__(self, name, weight=100, *args, **kwargs):
self.name = name
self.weight = weight
def __str__(self):
return "Unusable Contact: {:s} ({:d})".format(self.name, self.weight)
class EmailAddress(ContactInformation):
def __init__(self, name, email, *args, **kwargs):
super(EmailAddress, self).__init__(name, *args, **kwargs)
self.email = email
def __str__(self):
return "Email: {:s} <{:s}> ({:d})".format(self.name, self.email, self.weight)
class PhoneNumber(ContactInformation):
def __init__(self, name, phone, sms_ok=True, voice_ok=False, *args, **kwargs):
super(PhoneNumber, self).__init__(name, *args, **kwargs)
self.phone = phone
self.sms_ok = sms_ok
self.voice_ok = voice_ok
def __str__(self):
methods = []
if self.sms_ok:
methods.append('sms')
if self.voice_ok:
methods.append('voice')
return "Phone: {:s} <{:s}> [{:s}] ({:d})".format(self.name, self.phone, ', '.join(methods), self.weight)
class HipChat(ContactInformation):
def __init__(self, name, room, username=None, mention=None, notify=None, server=None, *args, **kwargs):
super(HipChat, self).__init__(name, *args, **kwargs)
self.room = room
self.username = username
self.server = server
if mention is None:
self.mention = True if username else False
else:
self.mention = mention
if notify is None:
self.notify = False if username else True
else:
self.notify = notify
def __str__(self):
path = [self.room]
if self.server:
path.insert(0, self.server)
if self.username:
path.append(self.username)
features = []
if self.mention:
features.append('mention')
if self.notify:
features.append('notify')
return "HipChat: {:s} <{:s}> [{:s}] ({:d})".format(self.name, '/'.join(path), ', '.join(features), self.weight)
class Recipient(object):
def __init__(self, name, contacts=None, *args, **kwargs):
self.name = name
self._contacts = contacts or []
def __str__(self):
return "{:s}: {:s}: {:s}".format(self.__class__.__name__, self.name, map(str, self.contacts) or 'No Contact Information')
def contacts(self, of_type=None, include_all=False, **having):
returned_types = []
for contact in sorted(self._contacts, key=lambda v: v.weight):
if of_type and not isinstance(contact, of_type):
continue
for key, value in having.items():
if getattr(contact, key, None) != value:
break
else:
if not include_all and contact.__class__ in returned_types:
continue
returned_types.append(contact.__class__)
yield contact
class Group(object):
def __init__(self, name, groups=None, recipients=None, *args, **kwargs):
self.name = name
self._groups = groups or []
self._recipients = recipients or []
def groups(self, recursive=True):
for group in self._groups:
yield group
if recursive:
for group_ in group.groups(recursive=True):
yield group_
def recipients(self, recursive=True):
for recipient in self._recipients:
yield recipient
if recursive:
for group in self.groups(recursive=False):
for recipient in group.recipients(recursive=True):
yield recipient
def contacts(self, of_type=None, include_all=False, recursive=True, **having):
for recipient in self.recipients(recursive=recursive):
for contact in recipient.contacts(of_type=of_type, include_all=include_all, **having):
yield contact
|
class Contactinformation(object):
def __init__(self, name, weight=100, *args, **kwargs):
self.name = name
self.weight = weight
def __str__(self):
return 'Unusable Contact: {:s} ({:d})'.format(self.name, self.weight)
class Emailaddress(ContactInformation):
def __init__(self, name, email, *args, **kwargs):
super(EmailAddress, self).__init__(name, *args, **kwargs)
self.email = email
def __str__(self):
return 'Email: {:s} <{:s}> ({:d})'.format(self.name, self.email, self.weight)
class Phonenumber(ContactInformation):
def __init__(self, name, phone, sms_ok=True, voice_ok=False, *args, **kwargs):
super(PhoneNumber, self).__init__(name, *args, **kwargs)
self.phone = phone
self.sms_ok = sms_ok
self.voice_ok = voice_ok
def __str__(self):
methods = []
if self.sms_ok:
methods.append('sms')
if self.voice_ok:
methods.append('voice')
return 'Phone: {:s} <{:s}> [{:s}] ({:d})'.format(self.name, self.phone, ', '.join(methods), self.weight)
class Hipchat(ContactInformation):
def __init__(self, name, room, username=None, mention=None, notify=None, server=None, *args, **kwargs):
super(HipChat, self).__init__(name, *args, **kwargs)
self.room = room
self.username = username
self.server = server
if mention is None:
self.mention = True if username else False
else:
self.mention = mention
if notify is None:
self.notify = False if username else True
else:
self.notify = notify
def __str__(self):
path = [self.room]
if self.server:
path.insert(0, self.server)
if self.username:
path.append(self.username)
features = []
if self.mention:
features.append('mention')
if self.notify:
features.append('notify')
return 'HipChat: {:s} <{:s}> [{:s}] ({:d})'.format(self.name, '/'.join(path), ', '.join(features), self.weight)
class Recipient(object):
def __init__(self, name, contacts=None, *args, **kwargs):
self.name = name
self._contacts = contacts or []
def __str__(self):
return '{:s}: {:s}: {:s}'.format(self.__class__.__name__, self.name, map(str, self.contacts) or 'No Contact Information')
def contacts(self, of_type=None, include_all=False, **having):
returned_types = []
for contact in sorted(self._contacts, key=lambda v: v.weight):
if of_type and (not isinstance(contact, of_type)):
continue
for (key, value) in having.items():
if getattr(contact, key, None) != value:
break
else:
if not include_all and contact.__class__ in returned_types:
continue
returned_types.append(contact.__class__)
yield contact
class Group(object):
def __init__(self, name, groups=None, recipients=None, *args, **kwargs):
self.name = name
self._groups = groups or []
self._recipients = recipients or []
def groups(self, recursive=True):
for group in self._groups:
yield group
if recursive:
for group_ in group.groups(recursive=True):
yield group_
def recipients(self, recursive=True):
for recipient in self._recipients:
yield recipient
if recursive:
for group in self.groups(recursive=False):
for recipient in group.recipients(recursive=True):
yield recipient
def contacts(self, of_type=None, include_all=False, recursive=True, **having):
for recipient in self.recipients(recursive=recursive):
for contact in recipient.contacts(of_type=of_type, include_all=include_all, **having):
yield contact
|
#
# Copyright 2019 FMR LLC <opensource@fmr.com>
#
# SPDX-License-Identifier: MIT
#
"""CLI and library to concurrently execute user-defined commands across AWS accounts.
## Overview
`awsrun` is both a CLI and library to execute commands over one or more AWS
accounts concurrently. Commands are user-defined Python modules that implement a
simple interface to abstract away the complications of obtaining credentials for
Boto3 sessions - especially when using SAML authentication and/or cross-account
access.
### CLI Usage
The awsrun CLI command is documented extensively on the `awsrun.cli` page. It
includes both a user guide as well as a reference guide on the use of the CLI
command, its command line options, use of the account loader and credential
plug-ins, as well as the syntax of the configuration file.
### Library Usage
Not only is awsrun a CLI, but it is, first and foremost, a Python package that
can be used in other Python libraries and scripts. The package contains
extensive documentation on its use. Each submodule contains an overview of the
module and how to use it, which is then followed by standard module docs for
classes and methods. The available [submodules](#header-submodules) can be found
at the bottom of this page. Of particular interest to library users will be the
following submodules:
`awsrun.runner`
: The core module to execute a command across one or more accounts. You will
find the `awsrun.runner.AccountRunner` and `awsrun.runner.Command` classes
defined in this module. Build your own commands by subclassing the base class.
See the [User-Defined Commmands](#user-defined-commands) next for more
information.
`awsrun.session`
: Contains the definition of the `awsrun.session.SessionProvider`, which is used
to provide Boto3 sessions pre-loaded with credentials. Included are several
built-in implementations such as `awsrun.session.aws.CredsViaProfile`,
`awsrun.session.aws.CredsViaSAML`, and `awsrun.session.aws.CredsViaCrossAccount`.
This module can be used outside of awsurn in other scripts. The module
documentation includes a user guide on how to do so.
### User-Defined Commands
To get the most benefit from awsrun, one typically writes their own used-defined
commands. Please refer to the `awsrun.commands` page for an extensive user guide
on building commands. In summary, a command is nothing more than a single Python
file that contains a subclass of `awsrun.runner.Command`. After the command has
been written, it must be added to the awsrun command path using the `--cmd-path`
[CLI flag](cli.html#options) or `cmd-path` option in the awsrun [configuration
file](cli.html#configuration_1).
### User-Defined Plug-ins
In addition to writing your own user-defined commands, you can write your own
account loader plug-ins as well as credential loader plug-ins. The following are
the high-level steps involved in writing your own plug-ins:
1. Subclass `awsrun.plugmgr.Plugin`. Be sure to read the class and module
documentation for details on how the CLI loads your plug-in.
2. Add an `__init__` method to register command line flags and configuration
options you want to make available to the end user. Be sure to call the
superclass's `__init__` method as well.
3. Provide an implementation for `awsrun.plugmgr.Plugin.instantiate`, which must
return an instance of either `awsrun.acctload.AccountLoader` or
`awsrun.session.SessionProvider` depending on whether you are writing an
account loader or a credential loader.
4. Provide an implementation for your account loader or credential loader
returned in step 3. Refer to the `awsrun.acctload.AccountLoader` and
`awsrun.session.SessionProvider` for the methods that must be implemented.
It is recommended that you review the existing plug-ins included in awsrun for
additional guidance on how to build your own.
## Future Plans
Prior to open-sourcing awsrun, the codebase was refactored to support the use of
other cloud service providers. This section includes the implementation details
as well as a high-level roadmap of future enhancements.
### Other CSPs
Other Cloud Service Providers (CSPs) aside from AWS and Azure can be supported.
The name of the installed CLI script is used to determine which CSP is being
used. For example, if the CLI has been installed as `awsrun`, the CSP is `aws`.
If the CLI has been installed as `azurerun`, the CSP is `azure`. The name of the
CSP dictates the following:
- The user configuration file is loaded from `$HOME/.csprun.yaml`, where `csp`
is the name of the CSP. This allows users to have CSP-specific configuration
files.
- The environment variable used to select an alternate path for the
configuration file is `CSPRUN_CONFIG`, where `CSP` is the name of the CSP.
This allows users to have multiple environment variables set for different
CSPs.
- The default command path is set to `awsrun.commands.csp`, where `csp` is the
name of the CSP. All of the included CSP commands are isolated in modules
dedicated to the CSP. This prevents commands for a different CSP from being
displayed on the command line when a user lists the available commands.
- The default credential loader plug-in is `awsrun.plugins.creds.csp.Default`,
where `csp` is the name of the CSP. Providing credentials to commands is done
via a credential loader. When none has been specified in the configuration
file, awsrun must default to a sane choice for a CSP.
### Roadmap
- Add tests for each module (only a handful have been done so far). PyTest is
the framework used in awsrun. See the tests/ directory which contains the
directories for unit and integration tests.
"""
name = "awsrun"
__version__ = "2.3.1"
|
"""CLI and library to concurrently execute user-defined commands across AWS accounts.
## Overview
`awsrun` is both a CLI and library to execute commands over one or more AWS
accounts concurrently. Commands are user-defined Python modules that implement a
simple interface to abstract away the complications of obtaining credentials for
Boto3 sessions - especially when using SAML authentication and/or cross-account
access.
### CLI Usage
The awsrun CLI command is documented extensively on the `awsrun.cli` page. It
includes both a user guide as well as a reference guide on the use of the CLI
command, its command line options, use of the account loader and credential
plug-ins, as well as the syntax of the configuration file.
### Library Usage
Not only is awsrun a CLI, but it is, first and foremost, a Python package that
can be used in other Python libraries and scripts. The package contains
extensive documentation on its use. Each submodule contains an overview of the
module and how to use it, which is then followed by standard module docs for
classes and methods. The available [submodules](#header-submodules) can be found
at the bottom of this page. Of particular interest to library users will be the
following submodules:
`awsrun.runner`
: The core module to execute a command across one or more accounts. You will
find the `awsrun.runner.AccountRunner` and `awsrun.runner.Command` classes
defined in this module. Build your own commands by subclassing the base class.
See the [User-Defined Commmands](#user-defined-commands) next for more
information.
`awsrun.session`
: Contains the definition of the `awsrun.session.SessionProvider`, which is used
to provide Boto3 sessions pre-loaded with credentials. Included are several
built-in implementations such as `awsrun.session.aws.CredsViaProfile`,
`awsrun.session.aws.CredsViaSAML`, and `awsrun.session.aws.CredsViaCrossAccount`.
This module can be used outside of awsurn in other scripts. The module
documentation includes a user guide on how to do so.
### User-Defined Commands
To get the most benefit from awsrun, one typically writes their own used-defined
commands. Please refer to the `awsrun.commands` page for an extensive user guide
on building commands. In summary, a command is nothing more than a single Python
file that contains a subclass of `awsrun.runner.Command`. After the command has
been written, it must be added to the awsrun command path using the `--cmd-path`
[CLI flag](cli.html#options) or `cmd-path` option in the awsrun [configuration
file](cli.html#configuration_1).
### User-Defined Plug-ins
In addition to writing your own user-defined commands, you can write your own
account loader plug-ins as well as credential loader plug-ins. The following are
the high-level steps involved in writing your own plug-ins:
1. Subclass `awsrun.plugmgr.Plugin`. Be sure to read the class and module
documentation for details on how the CLI loads your plug-in.
2. Add an `__init__` method to register command line flags and configuration
options you want to make available to the end user. Be sure to call the
superclass's `__init__` method as well.
3. Provide an implementation for `awsrun.plugmgr.Plugin.instantiate`, which must
return an instance of either `awsrun.acctload.AccountLoader` or
`awsrun.session.SessionProvider` depending on whether you are writing an
account loader or a credential loader.
4. Provide an implementation for your account loader or credential loader
returned in step 3. Refer to the `awsrun.acctload.AccountLoader` and
`awsrun.session.SessionProvider` for the methods that must be implemented.
It is recommended that you review the existing plug-ins included in awsrun for
additional guidance on how to build your own.
## Future Plans
Prior to open-sourcing awsrun, the codebase was refactored to support the use of
other cloud service providers. This section includes the implementation details
as well as a high-level roadmap of future enhancements.
### Other CSPs
Other Cloud Service Providers (CSPs) aside from AWS and Azure can be supported.
The name of the installed CLI script is used to determine which CSP is being
used. For example, if the CLI has been installed as `awsrun`, the CSP is `aws`.
If the CLI has been installed as `azurerun`, the CSP is `azure`. The name of the
CSP dictates the following:
- The user configuration file is loaded from `$HOME/.csprun.yaml`, where `csp`
is the name of the CSP. This allows users to have CSP-specific configuration
files.
- The environment variable used to select an alternate path for the
configuration file is `CSPRUN_CONFIG`, where `CSP` is the name of the CSP.
This allows users to have multiple environment variables set for different
CSPs.
- The default command path is set to `awsrun.commands.csp`, where `csp` is the
name of the CSP. All of the included CSP commands are isolated in modules
dedicated to the CSP. This prevents commands for a different CSP from being
displayed on the command line when a user lists the available commands.
- The default credential loader plug-in is `awsrun.plugins.creds.csp.Default`,
where `csp` is the name of the CSP. Providing credentials to commands is done
via a credential loader. When none has been specified in the configuration
file, awsrun must default to a sane choice for a CSP.
### Roadmap
- Add tests for each module (only a handful have been done so far). PyTest is
the framework used in awsrun. See the tests/ directory which contains the
directories for unit and integration tests.
"""
name = 'awsrun'
__version__ = '2.3.1'
|
py_ignore = """
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
target/
# Jupyter Notebook
.ipynb_checkpoints
# pyenv
.python-version
# celery beat schedule file
celerybeat-schedule
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
"""
py_setup_tmp = """
from setuptools import setup, find_packages
setup(name='%s',
version='0.0.0',
description='%s',
url='%s',
author='%s',
author_email='%s',
license='MIT',
include_package_data=True,
zip_safe=False,
packages=find_packages(),
install_requires=[%s],
entry_points={
'console_scripts': ['%s']
},
)
"""
py_cmd_tmp = """
import argparse
parser = argparse.ArgumentParser(usage="Manager project, can create git , sync , encrypt your repo")
parser.add_argument("-i","--init", help="default to initialize a projet in current dir")
def main():
args = parser.parse_args()
if __name__ == "__main__":
main()
"""
read_me_tmp = """
# %s
<code>%s</code>
> %s
%s
"""
|
py_ignore = '\n# Byte-compiled / optimized / DLL files\n__pycache__/\n*.py[cod]\n*$py.class\n\n# C extensions\n*.so\n\n# Distribution / packaging\n.Python\nbuild/\ndevelop-eggs/\ndist/\ndownloads/\neggs/\n.eggs/\nlib/\nlib64/\nparts/\nsdist/\nvar/\nwheels/\n*.egg-info/\n.installed.cfg\n*.egg\nMANIFEST\n\n# PyInstaller\n# Usually these files are written by a python script from a template\n# before PyInstaller builds the exe, so as to inject date/other infos into it.\n*.manifest\n*.spec\n\n# Installer logs\npip-log.txt\npip-delete-this-directory.txt\n\n# Unit test / coverage reports\nhtmlcov/\n.tox/\n.coverage\n.coverage.*\n.cache\nnosetests.xml\ncoverage.xml\n*.cover\n.hypothesis/\n.pytest_cache/\n\n# Translations\n*.mo\n*.pot\n\n# Django stuff:\n*.log\nlocal_settings.py\ndb.sqlite3\n\n# Flask stuff:\ninstance/\n.webassets-cache\n\n# Scrapy stuff:\n.scrapy\n\n# Sphinx documentation\ndocs/_build/\n\n# PyBuilder\ntarget/\n\n# Jupyter Notebook\n.ipynb_checkpoints\n\n# pyenv\n.python-version\n\n# celery beat schedule file\ncelerybeat-schedule\n\n# SageMath parsed files\n*.sage.py\n\n# Environments\n.env\n.venv\nenv/\nvenv/\nENV/\nenv.bak/\nvenv.bak/\n\n# Spyder project settings\n.spyderproject\n.spyproject\n\n# Rope project settings\n.ropeproject\n\n# mkdocs documentation\n/site\n\n# mypy\n.mypy_cache/\n'
py_setup_tmp = "\nfrom setuptools import setup, find_packages\n\n\nsetup(name='%s',\n version='0.0.0',\n description='%s',\n url='%s',\n author='%s',\n author_email='%s',\n license='MIT',\n include_package_data=True,\n zip_safe=False,\n packages=find_packages(),\n install_requires=[%s],\n entry_points={\n 'console_scripts': ['%s']\n },\n\n)\n"
py_cmd_tmp = '\nimport argparse\n\n\nparser = argparse.ArgumentParser(usage="Manager project, can create git , sync , encrypt your repo")\nparser.add_argument("-i","--init", help="default to initialize a projet in current dir")\n\n\ndef main():\n args = parser.parse_args()\n \n\nif __name__ == "__main__":\n main()\n'
read_me_tmp = '\n# %s\n\n<code>%s</code>\n\n> %s\n\n%s\n\n\n'
|
class train_test_setup():
def __init__(self, device, net_type, save_dir, voc, prerocess,
training_epoch=100, latent_k=32, batch_size=40, hidden_size=300, clip=50,
num_of_reviews = 5,
intra_method='dualFC', inter_method='dualFC',
learning_rate=0.00001, dropout=0, setence_max_len=50):
self.device = device
self.net_type = net_type
self.save_dir = save_dir
self.voc = voc
self.prerocess = prerocess # prerocess method
self.training_epoch = training_epoch
self.latent_k = latent_k
self.hidden_size = hidden_size
self.num_of_reviews = num_of_reviews
self.clip = clip
self.intra_method = intra_method
self.inter_method = inter_method
self.learning_rate = learning_rate
self.dropout = dropout
self.batch_size = batch_size
self.setence_max_len = setence_max_len
pass
def _get_asin_reviewer(self, select_table='clothing_'):
"""Get asin and reviewerID from file"""
asin, reviewerID = self.prerocess._read_asin_reviewer(table=select_table)
return asin, reviewerID
def set_training_batches(self, training_batches, external_memorys, candidate_items, candidate_users, training_batch_labels):
self.training_batches = training_batches
self.external_memorys = external_memorys
self.candidate_items = candidate_items
self.candidate_users = candidate_users
self.training_batch_labels = training_batch_labels
pass
def set_asin2title(self, asin2title):
self.asin2title = asin2title
pass
|
class Train_Test_Setup:
def __init__(self, device, net_type, save_dir, voc, prerocess, training_epoch=100, latent_k=32, batch_size=40, hidden_size=300, clip=50, num_of_reviews=5, intra_method='dualFC', inter_method='dualFC', learning_rate=1e-05, dropout=0, setence_max_len=50):
self.device = device
self.net_type = net_type
self.save_dir = save_dir
self.voc = voc
self.prerocess = prerocess
self.training_epoch = training_epoch
self.latent_k = latent_k
self.hidden_size = hidden_size
self.num_of_reviews = num_of_reviews
self.clip = clip
self.intra_method = intra_method
self.inter_method = inter_method
self.learning_rate = learning_rate
self.dropout = dropout
self.batch_size = batch_size
self.setence_max_len = setence_max_len
pass
def _get_asin_reviewer(self, select_table='clothing_'):
"""Get asin and reviewerID from file"""
(asin, reviewer_id) = self.prerocess._read_asin_reviewer(table=select_table)
return (asin, reviewerID)
def set_training_batches(self, training_batches, external_memorys, candidate_items, candidate_users, training_batch_labels):
self.training_batches = training_batches
self.external_memorys = external_memorys
self.candidate_items = candidate_items
self.candidate_users = candidate_users
self.training_batch_labels = training_batch_labels
pass
def set_asin2title(self, asin2title):
self.asin2title = asin2title
pass
|
"""Provides HTML tags wrappers for pretty printing."""
def bold(s):
return '<b>'+s+'</b>'
def italic(s):
return '<i>'+s+'</i>'
def b(s):
return bold(s)
def i(s):
return italic(s)
def red(s):
return '<font color="red">'+s+'</font>'
def green(s):
return '<font color="green">'+s+'</font>'
def blue(s):
return '<font color="blue">'+s+'</font>'
|
"""Provides HTML tags wrappers for pretty printing."""
def bold(s):
return '<b>' + s + '</b>'
def italic(s):
return '<i>' + s + '</i>'
def b(s):
return bold(s)
def i(s):
return italic(s)
def red(s):
return '<font color="red">' + s + '</font>'
def green(s):
return '<font color="green">' + s + '</font>'
def blue(s):
return '<font color="blue">' + s + '</font>'
|
class Solution(object):
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
triplate = []
prevSum = float("-inf")
prevDiff = target - prevSum
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
left, right = i + 1, len(nums) - 1
while left < right:
currentSum = nums[i] + nums[left] + nums[right]
currentDiff = target - currentSum
prevDiff = target - prevSum
if abs(currentDiff) < abs(prevDiff):
triplate = [nums[i], nums[left], nums[right]]
prevDiff = currentDiff
prevSum = currentSum
if currentSum < target:
while left < right and nums[left] == nums[left + 1]:
left += 1
left += 1
elif currentSum > target:
while left < right and nums[right] == nums[right - 1]:
right -= 1
right -= 1
else:
return sum(triplate[:])
return sum(triplate[:])
sol = Solution()
input = [1,1,1,0]
target = -100
tripletsSum = sol.threeSumClosest(input, target)
print("Result: ", tripletsSum)
|
class Solution(object):
def three_sum_closest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
nums.sort()
triplate = []
prev_sum = float('-inf')
prev_diff = target - prevSum
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i - 1]:
continue
(left, right) = (i + 1, len(nums) - 1)
while left < right:
current_sum = nums[i] + nums[left] + nums[right]
current_diff = target - currentSum
prev_diff = target - prevSum
if abs(currentDiff) < abs(prevDiff):
triplate = [nums[i], nums[left], nums[right]]
prev_diff = currentDiff
prev_sum = currentSum
if currentSum < target:
while left < right and nums[left] == nums[left + 1]:
left += 1
left += 1
elif currentSum > target:
while left < right and nums[right] == nums[right - 1]:
right -= 1
right -= 1
else:
return sum(triplate[:])
return sum(triplate[:])
sol = solution()
input = [1, 1, 1, 0]
target = -100
triplets_sum = sol.threeSumClosest(input, target)
print('Result: ', tripletsSum)
|
MODELS = {
"pwc": (
'configs/pwcnet/pwcnet_ft_4x1_300k_sintel_final_384x768.py',
'checkpoints/pwcnet_ft_4x1_300k_sintel_final_384x768.pth'
),
"flownetc": (
'configs/flownet/flownetc_8x1_sfine_sintel_384x448.py',
'checkpoints/flownetc_8x1_sfine_sintel_384x448.pth'
),
"raft": (
"configs/raft/raft_8x2_100k_mixed_368x768.py",
"checkpoints/raft_8x2_100k_mixed_368x768.pth"
)
}
|
models = {'pwc': ('configs/pwcnet/pwcnet_ft_4x1_300k_sintel_final_384x768.py', 'checkpoints/pwcnet_ft_4x1_300k_sintel_final_384x768.pth'), 'flownetc': ('configs/flownet/flownetc_8x1_sfine_sintel_384x448.py', 'checkpoints/flownetc_8x1_sfine_sintel_384x448.pth'), 'raft': ('configs/raft/raft_8x2_100k_mixed_368x768.py', 'checkpoints/raft_8x2_100k_mixed_368x768.pth')}
|
'''
Implementation of exponential search
Time Complexity: O(logn)
Space Complexity: Depends on implementation of binary_search {O(logn): recursive, O(1):iterative}
Used for unbounded search, when the length of array is infinite or not known
'''
#iterative implementation of binary search
def binary_search(arr, s, e, x):
'''
#arr: the array in which we need to find an element (sorted, increasing order)
#s: start index
#e: end index
#x: element we are looking for
'''
#search until arr becomes empty []
while (e>=s):
m = s + int((e-s)/2) #middle index
if x==arr[m]: #if found at mid return index
return m
elif x>arr[m]: #if x>arr[m] search only in the right array
s = m+1
elif x<arr[m]: #if x<arr[m] search only in the left array
e = m-1
return -1
def exponential_search(arr, n, x):
if x==arr[0]:
return 0;
i=1 #index
#keep increasing index until the indexed element is smaller and then do binary search
while i<n and x>arr[i]:
i = i*2
return binary_search(arr, int(i/2), min(i, n), x)
arr = [2,3,4,10,40]
x = 10
index = exponential_search(arr, len(arr), x)
if index==-1:
print("Element not present in list")
else:
print("Element",x,"is present at",index)
|
"""
Implementation of exponential search
Time Complexity: O(logn)
Space Complexity: Depends on implementation of binary_search {O(logn): recursive, O(1):iterative}
Used for unbounded search, when the length of array is infinite or not known
"""
def binary_search(arr, s, e, x):
"""
#arr: the array in which we need to find an element (sorted, increasing order)
#s: start index
#e: end index
#x: element we are looking for
"""
while e >= s:
m = s + int((e - s) / 2)
if x == arr[m]:
return m
elif x > arr[m]:
s = m + 1
elif x < arr[m]:
e = m - 1
return -1
def exponential_search(arr, n, x):
if x == arr[0]:
return 0
i = 1
while i < n and x > arr[i]:
i = i * 2
return binary_search(arr, int(i / 2), min(i, n), x)
arr = [2, 3, 4, 10, 40]
x = 10
index = exponential_search(arr, len(arr), x)
if index == -1:
print('Element not present in list')
else:
print('Element', x, 'is present at', index)
|
# Copyright (c) 2016, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory (subject to receipt
# of any required approvals from the U.S. Dept. of Energy).
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""
Custom exception and warning classes.
"""
class EventException(Exception):
"""Custom Event exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class EventWarning(Warning):
"""Custom Event warning"""
pass
class TimeRangeException(Exception):
"""Custom TimeRange exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class TimeRangeWarning(Warning):
"""Custom TimeRange warning"""
pass
class IndexException(Exception):
"""Custom Index exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class IndexWarning(Warning):
"""Custom Index warning"""
pass
class UtilityException(Exception):
"""Custom Utility exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class UtilityWarning(Warning):
"""Custom Utility warning"""
pass
class PipelineException(Exception):
"""Custom Pipeline exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class PipelineWarning(Warning):
"""Custom Pipeline warning"""
pass
class PipelineIOException(Exception):
"""Custom PipelineIO exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class PipelineIOWarning(Warning):
"""Custom PipelineIO warning"""
pass
class CollectionException(Exception):
"""Custom Collection exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class CollectionWarning(Warning):
"""Custom Collection warning"""
pass
class TimeSeriesException(Exception):
"""Custom TimeSeries exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class TimeSeriesWarning(Warning):
"""Custom TimeSeries warning"""
pass
class ProcessorException(Exception):
"""Custom Processor exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class ProcessorWarning(Warning):
"""Custom Processor warning"""
pass
class FilterException(Exception):
"""Custom Filter exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class FilterWarning(Warning):
"""Custom Filter warning"""
pass
class FunctionException(Exception):
"""Custom Function exception"""
def __init__(self, value):
# pylint: disable=super-init-not-called
self.value = value
def __str__(self): # pragma: no cover
return repr(self.value)
class FunctionWarning(Warning):
"""Custom Function warning"""
pass
NAIVE_MESSAGE = 'non-naive (aware) datetime objects required'
|
"""
Custom exception and warning classes.
"""
class Eventexception(Exception):
"""Custom Event exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Eventwarning(Warning):
"""Custom Event warning"""
pass
class Timerangeexception(Exception):
"""Custom TimeRange exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Timerangewarning(Warning):
"""Custom TimeRange warning"""
pass
class Indexexception(Exception):
"""Custom Index exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Indexwarning(Warning):
"""Custom Index warning"""
pass
class Utilityexception(Exception):
"""Custom Utility exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Utilitywarning(Warning):
"""Custom Utility warning"""
pass
class Pipelineexception(Exception):
"""Custom Pipeline exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Pipelinewarning(Warning):
"""Custom Pipeline warning"""
pass
class Pipelineioexception(Exception):
"""Custom PipelineIO exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Pipelineiowarning(Warning):
"""Custom PipelineIO warning"""
pass
class Collectionexception(Exception):
"""Custom Collection exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Collectionwarning(Warning):
"""Custom Collection warning"""
pass
class Timeseriesexception(Exception):
"""Custom TimeSeries exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Timeserieswarning(Warning):
"""Custom TimeSeries warning"""
pass
class Processorexception(Exception):
"""Custom Processor exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Processorwarning(Warning):
"""Custom Processor warning"""
pass
class Filterexception(Exception):
"""Custom Filter exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Filterwarning(Warning):
"""Custom Filter warning"""
pass
class Functionexception(Exception):
"""Custom Function exception"""
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Functionwarning(Warning):
"""Custom Function warning"""
pass
naive_message = 'non-naive (aware) datetime objects required'
|
"""
Searching lists.
"""
toys = ["blocks", "slinky", "fidget spinner", "cards", "doll house", "legos", "blocks", "teddy bear"]
# Finding items in a list
print(toys.index("legos"))
print(toys.index("blocks"))
#print(toys.index("video game"))
print("")
# Checking if items are in a list
print("legos" in toys)
print("blocks" in toys)
print("video game" in toys)
print("teddy bear" not in toys)
print("dice" not in toys)
print("")
# Counting items in list
print(toys.count("slinky"))
print(toys.count("blocks"))
|
"""
Searching lists.
"""
toys = ['blocks', 'slinky', 'fidget spinner', 'cards', 'doll house', 'legos', 'blocks', 'teddy bear']
print(toys.index('legos'))
print(toys.index('blocks'))
print('')
print('legos' in toys)
print('blocks' in toys)
print('video game' in toys)
print('teddy bear' not in toys)
print('dice' not in toys)
print('')
print(toys.count('slinky'))
print(toys.count('blocks'))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.