content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
def insertSort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = i-1
while j >=0 and val < arr[j] :
arr[j+1] = arr[j]
j -= 1
arr[j+1] = val
arr = [67, 12, 1, 6, 9]
insertSort(arr)
print(arr) | def insert_sort(arr):
for i in range(1, len(arr)):
val = arr[i]
j = i - 1
while j >= 0 and val < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = val
arr = [67, 12, 1, 6, 9]
insert_sort(arr)
print(arr) |
# this files contains basic metadata about the project. This data will be used
# (by default) in the base.html and index.html
PROJECT_METADATA = {
'title': 'Thunau',
'author': 'Peter Andorfer',
'subtitle': 'An Exavation Docu',
'description': 'A web application to manage and publish data gathered around the excavations in Thunau',
'github': 'https://github.com/acdh-oeaw/thunau',
'purpose_de': 'Ziel ist die Publikation von Forschungsdaten',
'purpose_en': 'The purpose of this project is the publication of research data',
'version': '0.1'
}
| project_metadata = {'title': 'Thunau', 'author': 'Peter Andorfer', 'subtitle': 'An Exavation Docu', 'description': 'A web application to manage and publish data gathered around the excavations in Thunau', 'github': 'https://github.com/acdh-oeaw/thunau', 'purpose_de': 'Ziel ist die Publikation von Forschungsdaten', 'purpose_en': 'The purpose of this project is the publication of research data', 'version': '0.1'} |
def last_sqrt(x):
n = 1
sqr = 0
while x>=sqr:
sqr = sqr + ((2*n)-1)
n+=1
return n-2
list = []
n = int(input("Enter the Number:"))
for num in range(2,(n+1)):
list.append(num)
for ltsqrt in range(0,(last_sqrt(n)-1)):
if list[ltsqrt]!=0:
for nums in range((ltsqrt+1),len(list)):
if list[nums]!=0:
if list[nums]%list[ltsqrt]==0:
list[nums]=0
for num in range(0,len(list)):
if list[num]!=0:
print(list[num])
# your code goes here | def last_sqrt(x):
n = 1
sqr = 0
while x >= sqr:
sqr = sqr + (2 * n - 1)
n += 1
return n - 2
list = []
n = int(input('Enter the Number:'))
for num in range(2, n + 1):
list.append(num)
for ltsqrt in range(0, last_sqrt(n) - 1):
if list[ltsqrt] != 0:
for nums in range(ltsqrt + 1, len(list)):
if list[nums] != 0:
if list[nums] % list[ltsqrt] == 0:
list[nums] = 0
for num in range(0, len(list)):
if list[num] != 0:
print(list[num]) |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPLUSMINUSleftTIMESDIVIDErightUMINUSDIVIDE EQUALS LPAREN MINUS NAME NUMBER PLUS RPAREN TIMESstatement : expressionexpression : expression PLUS expression\n | expression MINUS expression\n | expression TIMES expression\n | expression DIVIDE expressionexpression : MINUS expression %prec UMINUSexpression : LPAREN expression RPARENexpression : NUMBER'
_lr_action_items = {'MINUS':([0,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,],[3,7,3,3,-8,3,3,3,3,-6,7,-2,-3,-4,-5,-7,]),'LPAREN':([0,3,4,6,7,8,9,],[4,4,4,4,4,4,4,]),'NUMBER':([0,3,4,6,7,8,9,],[5,5,5,5,5,5,5,]),'$end':([1,2,5,10,12,13,14,15,16,],[0,-1,-8,-6,-2,-3,-4,-5,-7,]),'PLUS':([2,5,10,11,12,13,14,15,16,],[6,-8,-6,6,-2,-3,-4,-5,-7,]),'TIMES':([2,5,10,11,12,13,14,15,16,],[8,-8,-6,8,8,8,-4,-5,-7,]),'DIVIDE':([2,5,10,11,12,13,14,15,16,],[9,-8,-6,9,9,9,-4,-5,-7,]),'RPAREN':([5,10,11,12,13,14,15,16,],[-8,-6,16,-2,-3,-4,-5,-7,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'statement':([0,],[1,]),'expression':([0,3,4,6,7,8,9,],[2,10,11,12,13,14,15,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> statement","S'",1,None,None,None),
('statement -> expression','statement',1,'p_statement_expr','22.py',67),
('expression -> expression PLUS expression','expression',3,'p_expression_binop','22.py',71),
('expression -> expression MINUS expression','expression',3,'p_expression_binop','22.py',72),
('expression -> expression TIMES expression','expression',3,'p_expression_binop','22.py',73),
('expression -> expression DIVIDE expression','expression',3,'p_expression_binop','22.py',74),
('expression -> MINUS expression','expression',2,'p_expression_uminus','22.py',89),
('expression -> LPAREN expression RPAREN','expression',3,'p_expression_group','22.py',94),
('expression -> NUMBER','expression',1,'p_expression_number','22.py',98),
]
| _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPLUSMINUSleftTIMESDIVIDErightUMINUSDIVIDE EQUALS LPAREN MINUS NAME NUMBER PLUS RPAREN TIMESstatement : expressionexpression : expression PLUS expression\n | expression MINUS expression\n | expression TIMES expression\n | expression DIVIDE expressionexpression : MINUS expression %prec UMINUSexpression : LPAREN expression RPARENexpression : NUMBER'
_lr_action_items = {'MINUS': ([0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], [3, 7, 3, 3, -8, 3, 3, 3, 3, -6, 7, -2, -3, -4, -5, -7]), 'LPAREN': ([0, 3, 4, 6, 7, 8, 9], [4, 4, 4, 4, 4, 4, 4]), 'NUMBER': ([0, 3, 4, 6, 7, 8, 9], [5, 5, 5, 5, 5, 5, 5]), '$end': ([1, 2, 5, 10, 12, 13, 14, 15, 16], [0, -1, -8, -6, -2, -3, -4, -5, -7]), 'PLUS': ([2, 5, 10, 11, 12, 13, 14, 15, 16], [6, -8, -6, 6, -2, -3, -4, -5, -7]), 'TIMES': ([2, 5, 10, 11, 12, 13, 14, 15, 16], [8, -8, -6, 8, 8, 8, -4, -5, -7]), 'DIVIDE': ([2, 5, 10, 11, 12, 13, 14, 15, 16], [9, -8, -6, 9, 9, 9, -4, -5, -7]), 'RPAREN': ([5, 10, 11, 12, 13, 14, 15, 16], [-8, -6, 16, -2, -3, -4, -5, -7])}
_lr_action = {}
for (_k, _v) in _lr_action_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_action:
_lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'statement': ([0], [1]), 'expression': ([0, 3, 4, 6, 7, 8, 9], [2, 10, 11, 12, 13, 14, 15])}
_lr_goto = {}
for (_k, _v) in _lr_goto_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_goto:
_lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [("S' -> statement", "S'", 1, None, None, None), ('statement -> expression', 'statement', 1, 'p_statement_expr', '22.py', 67), ('expression -> expression PLUS expression', 'expression', 3, 'p_expression_binop', '22.py', 71), ('expression -> expression MINUS expression', 'expression', 3, 'p_expression_binop', '22.py', 72), ('expression -> expression TIMES expression', 'expression', 3, 'p_expression_binop', '22.py', 73), ('expression -> expression DIVIDE expression', 'expression', 3, 'p_expression_binop', '22.py', 74), ('expression -> MINUS expression', 'expression', 2, 'p_expression_uminus', '22.py', 89), ('expression -> LPAREN expression RPAREN', 'expression', 3, 'p_expression_group', '22.py', 94), ('expression -> NUMBER', 'expression', 1, 'p_expression_number', '22.py', 98)] |
## Aim :
## You are given two strings, A and B.
## Find if there is a substring that appears in both A and B.
# Input:
# The first line of the input will contain a single integer , tthe number of test cases.
# Then there will be t descriptions of the test cases. Each description contains two lines.
# The first line contains the string A and the second line contains the string B.
# Output:
# For each test case, display YES (in a newline), if there is a common substring.
# Otherwise, display NO
n = int(input().strip())
a = []
for a_i in range(2*n):
a_t = [a_temp for a_temp in input().strip().split(' ')][0]
a.append(a_t)
for i in range(2*n):
if (i%2==0):
s1=set(a[i])
s2=set(a[i+1])
S=s1.intersection(s2) #intersection of subset -> return the same characters !!
if (len(S)==0):
print("NO")
else:
print("YES")
| n = int(input().strip())
a = []
for a_i in range(2 * n):
a_t = [a_temp for a_temp in input().strip().split(' ')][0]
a.append(a_t)
for i in range(2 * n):
if i % 2 == 0:
s1 = set(a[i])
s2 = set(a[i + 1])
s = s1.intersection(s2)
if len(S) == 0:
print('NO')
else:
print('YES') |
'''
* @File: main.py
* @Author: CSY
* @Date: 2019/7/27 - 9:40
'''
| """
* @File: main.py
* @Author: CSY
* @Date: 2019/7/27 - 9:40
""" |
class LoopDetected(Exception):
"""
A loop has been detected while tracing a cable path.
"""
pass
class CableTraceSplit(Exception):
"""
A cable trace cannot be completed because a RearPort maps to multiple FrontPorts and
we don't know which one to follow.
"""
def __init__(self, termination, *args, **kwargs):
self.termination = termination
| class Loopdetected(Exception):
"""
A loop has been detected while tracing a cable path.
"""
pass
class Cabletracesplit(Exception):
"""
A cable trace cannot be completed because a RearPort maps to multiple FrontPorts and
we don't know which one to follow.
"""
def __init__(self, termination, *args, **kwargs):
self.termination = termination |
def show_free(cal_name, d, m, t1, t2):
"String x Integer x String x String x String ->"
day = new_day(d)
mon = new_month(m)
start = convert_time(t1)
end = convert_time(t2)
cal_day = calendar_day(day, calendar_month(mon, fetch_calendar(cal_name)))
show_time_spans(free_spans(cal_day, start, end))
def spans_copy(spans):
"spans -> spans"
time_spans = get_time_spans(spans)
new_spans = new_time_spans()
for span in time_spans:
new_spans = insert_span(span, new_spans)
return new_spans
def free_spans(cal_day, start1, end1, spans=new_time_spans()):
"calendar_day x time x time (x spans) -> spans"
span1 = new_time_span(start1, end1)
if is_empty_calendar_day(cal_day):
return insert_span(span1, spans_copy(spans))
app = first_appointment(cal_day)
start2 = start_time(get_span(app))
end2 = end_time(get_span(app))
span2 = new_time_span(start2, end2)
if not are_overlapping(span1, span2):
return insert_span(span1, spans_copy(spans))
if earliest_time(start1, start2) == start1 and start1 != start2:
spans = free_spans(rest_calendar_day(cal_day), start1, start2, spans)
if latest_time(end1, end2) == end1 and end2 != end1:
spans = free_spans(rest_calendar_day(cal_day), end2, end1, spans)
return spans
| def show_free(cal_name, d, m, t1, t2):
"""String x Integer x String x String x String ->"""
day = new_day(d)
mon = new_month(m)
start = convert_time(t1)
end = convert_time(t2)
cal_day = calendar_day(day, calendar_month(mon, fetch_calendar(cal_name)))
show_time_spans(free_spans(cal_day, start, end))
def spans_copy(spans):
"""spans -> spans"""
time_spans = get_time_spans(spans)
new_spans = new_time_spans()
for span in time_spans:
new_spans = insert_span(span, new_spans)
return new_spans
def free_spans(cal_day, start1, end1, spans=new_time_spans()):
"""calendar_day x time x time (x spans) -> spans"""
span1 = new_time_span(start1, end1)
if is_empty_calendar_day(cal_day):
return insert_span(span1, spans_copy(spans))
app = first_appointment(cal_day)
start2 = start_time(get_span(app))
end2 = end_time(get_span(app))
span2 = new_time_span(start2, end2)
if not are_overlapping(span1, span2):
return insert_span(span1, spans_copy(spans))
if earliest_time(start1, start2) == start1 and start1 != start2:
spans = free_spans(rest_calendar_day(cal_day), start1, start2, spans)
if latest_time(end1, end2) == end1 and end2 != end1:
spans = free_spans(rest_calendar_day(cal_day), end2, end1, spans)
return spans |
def list_comprehension():
matrix = [
[1 if row == 2 or column == 2 else 0 for column in range(5)] for row in range(5)
]
print(matrix)
# von Jonas(JoBo12) aus dem Discord
def with_for():
matrix_1 = []
for item in range(5):
matrix_1.append([])
for item2 in range(5):
matrix_1[item].append(int(item == 2 or item2 == 2))
print(matrix_1)
list_comprehension() | def list_comprehension():
matrix = [[1 if row == 2 or column == 2 else 0 for column in range(5)] for row in range(5)]
print(matrix)
def with_for():
matrix_1 = []
for item in range(5):
matrix_1.append([])
for item2 in range(5):
matrix_1[item].append(int(item == 2 or item2 == 2))
print(matrix_1)
list_comprehension() |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: Zeyuan Shang
# @Date: 2015-11-19 21:10:01
# @Last Modified by: Zeyuan Shang
# @Last Modified time: 2015-11-19 21:10:09
class NumMatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
return
n, m = len(matrix), len(matrix[0])
self.sums = [[0] * (m + 1)]
for i in xrange(1, n + 1):
self.sums.append([0] * (m + 1))
for j in range(1, m + 1):
self.sums[i][j] = self.sums[i][j - 1] + self.sums[i - 1][j] - self.sums[i - 1][j - 1] + matrix[i - 1][j - 1]
def sumRegion(self, row1, col1, row2, col2):
"""
sum of elements matrix[(row1,col1)..(row2,col2)], inclusive.
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:rtype: int
"""
return self.sums[row2 + 1][col2 + 1] - self.sums[row1][col2 + 1] - self.sums[row2 + 1][col1] + self.sums[row1][col1]
# Your NumMatrix object will be instantiated and called as such:
# numMatrix = NumMatrix(matrix)
# numMatrix.sumRegion(0, 1, 2, 3)
# numMatrix.sumRegion(1, 2, 3, 4) | class Nummatrix(object):
def __init__(self, matrix):
"""
initialize your data structure here.
:type matrix: List[List[int]]
"""
if not matrix:
return
(n, m) = (len(matrix), len(matrix[0]))
self.sums = [[0] * (m + 1)]
for i in xrange(1, n + 1):
self.sums.append([0] * (m + 1))
for j in range(1, m + 1):
self.sums[i][j] = self.sums[i][j - 1] + self.sums[i - 1][j] - self.sums[i - 1][j - 1] + matrix[i - 1][j - 1]
def sum_region(self, row1, col1, row2, col2):
"""
sum of elements matrix[(row1,col1)..(row2,col2)], inclusive.
:type row1: int
:type col1: int
:type row2: int
:type col2: int
:rtype: int
"""
return self.sums[row2 + 1][col2 + 1] - self.sums[row1][col2 + 1] - self.sums[row2 + 1][col1] + self.sums[row1][col1] |
# dataset settings
data_source_cfg = dict(type='CIFAR10', root='data/cifar10/')
dataset_type = 'ExtractDataset'
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_pipeline = [
dict(
type='RandomResizedCrop', size=224, scale=(0.2, 1.0), interpolation=3),
dict(type='RandomHorizontalFlip')
]
# prefetch
prefetch = True
if not prefetch:
train_pipeline.extend([dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg)])
# dataset summary
data = dict(
imgs_per_gpu=64, # V100: 64 x 8gpus x 8 accumulates = bs4096
workers_per_gpu=4,
train=dict(
type=dataset_type,
data_source=dict(split='train', return_label=False, **data_source_cfg),
pipeline=train_pipeline,
prefetch=prefetch))
# checkpoint
checkpoint_config = dict(interval=10, max_keep_ckpts=1)
| data_source_cfg = dict(type='CIFAR10', root='data/cifar10/')
dataset_type = 'ExtractDataset'
img_norm_cfg = dict(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
train_pipeline = [dict(type='RandomResizedCrop', size=224, scale=(0.2, 1.0), interpolation=3), dict(type='RandomHorizontalFlip')]
prefetch = True
if not prefetch:
train_pipeline.extend([dict(type='ToTensor'), dict(type='Normalize', **img_norm_cfg)])
data = dict(imgs_per_gpu=64, workers_per_gpu=4, train=dict(type=dataset_type, data_source=dict(split='train', return_label=False, **data_source_cfg), pipeline=train_pipeline, prefetch=prefetch))
checkpoint_config = dict(interval=10, max_keep_ckpts=1) |
"""
Sandbox for MicroPyDatabase
A low-memory json-based databse for MicroPython.
Data is stored in a folder structure in json for easy inspection.
This file contains sample usage.
"""
#Database examples:
db_object = Database.create("mydb2")
db_object = Database.open("mydb")
#Table examples:
db_table = db_object.create_table("mytable", ["name", "password"])
db_table = db_object.open_table("mytable")
db_table.truncate()
#Insert examples:
db_table.insert({"name": "nate", "password": "coolpassword"})
db_table.insert([{"name": "whothere", "password": "ohyeah"}, {"name": "whothere", "password": "ohyeah"}, {"name": "whothere", "password": "ohyeah"}])
#Low-level operations using internal row_id:
db_table.find_row(5)
db_table.update_row(300, {'name': 'bob'})
db_table.delete_row(445)
db_table.find_by_column_value("name", "bob")
f = db_table.scan()
f.__next__()
#High-level operations using queries:
db_table.find({"name": "blah", "password": "something"})
db_table.query({"name": "blah", "password": "something"})
db_table.update({"name": "blah8", "password": "yeah8"}, {"name": "blah9", "password": "yeah9"})
db_table.delete({"name": "blah9", "password": "yeah9"})
| """
Sandbox for MicroPyDatabase
A low-memory json-based databse for MicroPython.
Data is stored in a folder structure in json for easy inspection.
This file contains sample usage.
"""
db_object = Database.create('mydb2')
db_object = Database.open('mydb')
db_table = db_object.create_table('mytable', ['name', 'password'])
db_table = db_object.open_table('mytable')
db_table.truncate()
db_table.insert({'name': 'nate', 'password': 'coolpassword'})
db_table.insert([{'name': 'whothere', 'password': 'ohyeah'}, {'name': 'whothere', 'password': 'ohyeah'}, {'name': 'whothere', 'password': 'ohyeah'}])
db_table.find_row(5)
db_table.update_row(300, {'name': 'bob'})
db_table.delete_row(445)
db_table.find_by_column_value('name', 'bob')
f = db_table.scan()
f.__next__()
db_table.find({'name': 'blah', 'password': 'something'})
db_table.query({'name': 'blah', 'password': 'something'})
db_table.update({'name': 'blah8', 'password': 'yeah8'}, {'name': 'blah9', 'password': 'yeah9'})
db_table.delete({'name': 'blah9', 'password': 'yeah9'}) |
travel_mode = {"1": "car", "2": "plane"}
items = {
"can opener",
"fuel",
"jumper",
"knife",
"matches",
"razor blades",
"razor",
"scissors",
"shampoo",
"shaving cream",
"shirts (3)",
"shorts",
"sleeping bag(s)",
"soap",
"socks (3 pairs)",
"stove",
"tent",
"mug",
"toothbrush",
"toothpaste",
"towel",
"underwear (3 pairs)",
"water carrier",
}
restricted_items = {
"catapult",
"fuel",
"gun",
"knife",
"razor blades",
"scissors",
"shampoo",
}
print("Please choose your mode of travel:")
for key, value in travel_mode.items():
print(f"{key}: {value}")
# Python 3.5 and earlier
# print("{}: {}".format(key, value))
mode = "-"
while mode not in travel_mode:
mode = input("> ")
if mode == "2":
# travelling by plane, remove restricted items
for item in restricted_items:
items.discard(item)
# print the packing list
print("You need to pack:")
for item in sorted(items):
print(item)
| travel_mode = {'1': 'car', '2': 'plane'}
items = {'can opener', 'fuel', 'jumper', 'knife', 'matches', 'razor blades', 'razor', 'scissors', 'shampoo', 'shaving cream', 'shirts (3)', 'shorts', 'sleeping bag(s)', 'soap', 'socks (3 pairs)', 'stove', 'tent', 'mug', 'toothbrush', 'toothpaste', 'towel', 'underwear (3 pairs)', 'water carrier'}
restricted_items = {'catapult', 'fuel', 'gun', 'knife', 'razor blades', 'scissors', 'shampoo'}
print('Please choose your mode of travel:')
for (key, value) in travel_mode.items():
print(f'{key}: {value}')
mode = '-'
while mode not in travel_mode:
mode = input('> ')
if mode == '2':
for item in restricted_items:
items.discard(item)
print('You need to pack:')
for item in sorted(items):
print(item) |
class Solution:
def removeOuterParentheses(self, S: str) -> str:
primitiveEndIndices = set([0])
count = 0
for i, char in enumerate(S):
if char == '(':
count += 1
elif char == ')':
count -= 1
if count == 0:
primitiveEndIndices.add(i)
primitiveEndIndices.add(i + 1)
result = []
for i in range(len(S)):
if i not in primitiveEndIndices:
result.append(S[i])
return ''.join(result) | class Solution:
def remove_outer_parentheses(self, S: str) -> str:
primitive_end_indices = set([0])
count = 0
for (i, char) in enumerate(S):
if char == '(':
count += 1
elif char == ')':
count -= 1
if count == 0:
primitiveEndIndices.add(i)
primitiveEndIndices.add(i + 1)
result = []
for i in range(len(S)):
if i not in primitiveEndIndices:
result.append(S[i])
return ''.join(result) |
person = {
"name": "Bernardo",
"age": 21
}
print(person)
print(person.items())
print(person["name"])
person["wright"] = "78kg"
print(person) | person = {'name': 'Bernardo', 'age': 21}
print(person)
print(person.items())
print(person['name'])
person['wright'] = '78kg'
print(person) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
BASE_CF_TEMPLATE = '''
AWSTemplateFormatVersion: 2010-09-09
Description: AWS CloudFormation template
Parameters:
EcsAmiId:
Type: String
Description: ECS AMI Id
EcsInstanceType:
Type: String
Description: ECS EC2 instance type
Default: t2.micro
ConstraintDescription: must be a valid EC2 instance type.
KeyName:
Type: String
Description: >-
Optional - Name of an existing EC2 KeyPair to enable SSH access to the ECS
instances
Default: 'ecs-ssh'
AsgMaxSize:
Type: Number
Description: Maximum size and initial Desired Capacity of ECS Auto Scaling Group
Default: '1'
IamRoleInstanceProfile:
Type: String
Description: >-
Name or the Amazon Resource Name (ARN) of the instance profile associated
with the IAM role for the instance
Default: ecsInstanceRole
EcsClusterName:
Type: String
Description: ECS Cluster Name
Default: default
EcsPort:
Type: String
Description: >-
Optional - Security Group port to open on ECS instances - defaults to port 80
Default: '80'
ElbPort:
Type: String
Description: >-
Optional - Security Group port to open on ELB - port 80 will be open by
default
Default: '80'
ElbHealthCheckTarget:
Type: String
Description: 'Optional - Health Check Target for ELB - defaults to HTTP:80/'
Default: 'HTTP:80/'
SourceCidr:
Type: String
Description: Optional - CIDR/IP range for EcsPort and ElbPort - defaults to 0.0.0.0/0
Default: 0.0.0.0/0
EcsEndpoint:
Type: String
Description: 'Optional : ECS Endpoint for the ECS Agent to connect to'
Default: ''
VpcAvailabilityZones:
Type: CommaDelimitedList
Description: >-
Optional : Comma-delimited list of two VPC availability zones in which to create subnets
Default: ''
VpcCidrBlock:
Type: String
Description: Optional - CIDR/IP range for the VPC
Default: 10.0.0.0/16
SubnetCidrBlock1:
Type: String
Description: Optional - CIDR/IP range for the VPC
Default: 10.0.0.0/24
SubnetCidrBlock2:
Type: String
Description: Optional - CIDR/IP range for the VPC
Default: 10.0.1.0/24
Conditions:
SetEndpointToECSAgent: !Not
- !Equals
- !Ref EcsEndpoint
- ''
CreateEC2LCWithKeyPair: !Not
- !Equals
- !Ref KeyName
- ''
UseSpecifiedVpcAvailabilityZones: !Not
- !Equals
- !Join
- ''
- !Ref VpcAvailabilityZones
- ''
Resources:
Vpc:
Type: 'AWS::EC2::VPC'
Properties:
CidrBlock: !Ref VpcCidrBlock
EnableDnsSupport: 'true'
EnableDnsHostnames: 'true'
PubSubnetAz1:
Type: 'AWS::EC2::Subnet'
Properties:
VpcId: !Ref Vpc
CidrBlock: !Ref SubnetCidrBlock1
AvailabilityZone: !If
- UseSpecifiedVpcAvailabilityZones
- !Select
- '0'
- !Ref VpcAvailabilityZones
- !Select
- '0'
- !GetAZs
Ref: 'AWS::Region'
PubSubnetAz2:
Type: 'AWS::EC2::Subnet'
Properties:
VpcId: !Ref Vpc
CidrBlock: !Ref SubnetCidrBlock2
AvailabilityZone: !If
- UseSpecifiedVpcAvailabilityZones
- !Select
- '1'
- !Ref VpcAvailabilityZones
- !Select
- '1'
- !GetAZs
Ref: 'AWS::Region'
InternetGateway:
Type: 'AWS::EC2::InternetGateway'
AttachGateway:
Type: 'AWS::EC2::VPCGatewayAttachment'
Properties:
VpcId: !Ref Vpc
InternetGatewayId: !Ref InternetGateway
RouteViaIgw:
Type: 'AWS::EC2::RouteTable'
Properties:
VpcId: !Ref Vpc
PublicRouteViaIgw:
Type: 'AWS::EC2::Route'
DependsOn: AttachGateway
Properties:
RouteTableId: !Ref RouteViaIgw
DestinationCidrBlock: 0.0.0.0/0
GatewayId: !Ref InternetGateway
PubSubnet1RouteTableAssociation:
Type: 'AWS::EC2::SubnetRouteTableAssociation'
Properties:
SubnetId: !Ref PubSubnetAz1
RouteTableId: !Ref RouteViaIgw
PubSubnet2RouteTableAssociation:
Type: 'AWS::EC2::SubnetRouteTableAssociation'
Properties:
SubnetId: !Ref PubSubnetAz2
RouteTableId: !Ref RouteViaIgw
EcsInternalSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: ECS Allowed Ports
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '1'
ToPort: '65535'
SourceSecurityGroupId: !Ref AlbInternalSecurityGroup
AlbInternalSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: ELB Allowed Ports
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: !Ref ElbPort
ToPort: !Ref ElbPort
CidrIp: !Ref SourceCidr
InternalTargetGroup:
Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
Properties:
Name: !Join
- ''
- - !Ref 'AWS::StackName'
- '-internal-tg'
VpcId: !Ref Vpc
Port: !Ref ElbPort
Protocol: HTTP
EcsInternalElasticLoadBalancer:
Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'
Properties:
Name: !Join
- ''
- - !Ref 'AWS::StackName'
- '-internal-alb'
SecurityGroups:
- !Ref AlbInternalSecurityGroup
Subnets:
- !Ref PubSubnetAz1
- !Ref PubSubnetAz2
Scheme: internal
InternalLoadBalancerListener:
Type: 'AWS::ElasticLoadBalancingV2::Listener'
Properties:
LoadBalancerArn: !Ref EcsInternalElasticLoadBalancer
Port: !Ref ElbPort
Protocol: HTTP
DefaultActions:
- Type: forward
TargetGroupArn: !Ref InternalTargetGroup
EcsInternetFacingSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: ECS Allowed Ports
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '1'
ToPort: '65535'
SourceSecurityGroupId: !Ref AlbInternetFacingSecurityGroup
AlbInternetFacingSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: ELB Allowed Ports
VpcId: !Ref Vpc
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: !Ref ElbPort
ToPort: !Ref ElbPort
CidrIp: !Ref SourceCidr
InternetFacingTargetGroup:
Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
Properties:
Name: !Join
- ''
- - !Ref 'AWS::StackName'
- '-internet-facing-tg'
VpcId: !Ref Vpc
Port: !Ref ElbPort
Protocol: HTTP
EcsInternetFacingElasticLoadBalancer:
Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'
Properties:
Name: !Join
- ''
- - !Ref 'AWS::StackName'
- '-internet-facing-alb'
SecurityGroups:
- !Ref AlbInternetFacingSecurityGroup
Subnets:
- !Ref PubSubnetAz1
- !Ref PubSubnetAz2
Scheme: internet-facing
InternetFacingLoadBalancerListener:
Type: 'AWS::ElasticLoadBalancingV2::Listener'
Properties:
LoadBalancerArn: !Ref EcsInternetFacingElasticLoadBalancer
Port: !Ref ElbPort
Protocol: HTTP
DefaultActions:
- Type: forward
TargetGroupArn: !Ref InternetFacingTargetGroup
EcsInstanceLc:
Type: 'AWS::AutoScaling::LaunchConfiguration'
Properties:
ImageId: !Ref EcsAmiId
InstanceType: !Ref EcsInstanceType
AssociatePublicIpAddress: true
IamInstanceProfile: !Ref IamRoleInstanceProfile
KeyName: !If
- CreateEC2LCWithKeyPair
- !Ref KeyName
- !Ref 'AWS::NoValue'
SecurityGroups:
- !Ref EcsInternalSecurityGroup
- !Ref EcsInternetFacingSecurityGroup
UserData: !If
- SetEndpointToECSAgent
- !Base64
'Fn::Join':
- ''
- - |
#!/bin/bash
- echo ECS_CLUSTER=
- !Ref EcsClusterName
- ' >> /etc/ecs/ecs.config'
- |-
echo ECS_BACKEND_HOST=
- !Ref EcsEndpoint
- ' >> /etc/ecs/ecs.config'
- !Base64
'Fn::Join':
- ''
- - |
#!/bin/bash
- echo ECS_CLUSTER=
- !Ref EcsClusterName
- ' >> /etc/ecs/ecs.config'
EcsInstanceAsg:
Type: 'AWS::AutoScaling::AutoScalingGroup'
Properties:
VPCZoneIdentifier:
- !Join
- ','
- - !Ref PubSubnetAz1
- !Ref PubSubnetAz2
LaunchConfigurationName: !Ref EcsInstanceLc
MinSize: '0'
MaxSize: !Ref AsgMaxSize
DesiredCapacity: !Ref AsgMaxSize
Tags:
- Key: Name
Value: !Join
- ''
- - 'ECS Instance - '
- !Ref 'AWS::StackName'
PropagateAtLaunch: 'true'
Outputs:
EcsInstanceAsgName:
Description: Auto Scaling Group Name for ECS Instances
Value: !Ref EcsInstanceAsg
EcsInternalElbName:
Description: Internal Load Balancer for ECS Service
Value: !Ref EcsInternalElasticLoadBalancer
EcsInternetFacingElbName:
Description: Internet-facing Load Balancer for ECS Service
Value: !Ref EcsInternetFacingElasticLoadBalancer
'''
| base_cf_template = "\nAWSTemplateFormatVersion: 2010-09-09\nDescription: AWS CloudFormation template\nParameters:\n EcsAmiId:\n Type: String\n Description: ECS AMI Id\n EcsInstanceType:\n Type: String\n Description: ECS EC2 instance type\n Default: t2.micro\n ConstraintDescription: must be a valid EC2 instance type.\n KeyName:\n Type: String\n Description: >-\n Optional - Name of an existing EC2 KeyPair to enable SSH access to the ECS\n instances\n Default: 'ecs-ssh'\n AsgMaxSize:\n Type: Number\n Description: Maximum size and initial Desired Capacity of ECS Auto Scaling Group\n Default: '1'\n IamRoleInstanceProfile:\n Type: String\n Description: >-\n Name or the Amazon Resource Name (ARN) of the instance profile associated\n with the IAM role for the instance\n Default: ecsInstanceRole\n EcsClusterName:\n Type: String\n Description: ECS Cluster Name\n Default: default\n EcsPort:\n Type: String\n Description: >-\n Optional - Security Group port to open on ECS instances - defaults to port 80\n Default: '80'\n ElbPort:\n Type: String\n Description: >-\n Optional - Security Group port to open on ELB - port 80 will be open by\n default\n Default: '80'\n ElbHealthCheckTarget:\n Type: String\n Description: 'Optional - Health Check Target for ELB - defaults to HTTP:80/'\n Default: 'HTTP:80/'\n SourceCidr:\n Type: String\n Description: Optional - CIDR/IP range for EcsPort and ElbPort - defaults to 0.0.0.0/0\n Default: 0.0.0.0/0\n EcsEndpoint:\n Type: String\n Description: 'Optional : ECS Endpoint for the ECS Agent to connect to'\n Default: ''\n VpcAvailabilityZones:\n Type: CommaDelimitedList\n Description: >-\n Optional : Comma-delimited list of two VPC availability zones in which to create subnets\n Default: ''\n VpcCidrBlock:\n Type: String\n Description: Optional - CIDR/IP range for the VPC\n Default: 10.0.0.0/16\n SubnetCidrBlock1:\n Type: String\n Description: Optional - CIDR/IP range for the VPC\n Default: 10.0.0.0/24\n SubnetCidrBlock2:\n Type: String\n Description: Optional - CIDR/IP range for the VPC\n Default: 10.0.1.0/24\nConditions:\n SetEndpointToECSAgent: !Not\n - !Equals\n - !Ref EcsEndpoint\n - ''\n CreateEC2LCWithKeyPair: !Not\n - !Equals\n - !Ref KeyName\n - ''\n UseSpecifiedVpcAvailabilityZones: !Not\n - !Equals\n - !Join\n - ''\n - !Ref VpcAvailabilityZones\n - ''\nResources:\n Vpc:\n Type: 'AWS::EC2::VPC'\n Properties:\n CidrBlock: !Ref VpcCidrBlock\n EnableDnsSupport: 'true'\n EnableDnsHostnames: 'true'\n PubSubnetAz1:\n Type: 'AWS::EC2::Subnet'\n Properties:\n VpcId: !Ref Vpc\n CidrBlock: !Ref SubnetCidrBlock1\n AvailabilityZone: !If\n - UseSpecifiedVpcAvailabilityZones\n - !Select\n - '0'\n - !Ref VpcAvailabilityZones\n - !Select\n - '0'\n - !GetAZs\n Ref: 'AWS::Region'\n PubSubnetAz2:\n Type: 'AWS::EC2::Subnet'\n Properties:\n VpcId: !Ref Vpc\n CidrBlock: !Ref SubnetCidrBlock2\n AvailabilityZone: !If\n - UseSpecifiedVpcAvailabilityZones\n - !Select\n - '1'\n - !Ref VpcAvailabilityZones\n - !Select\n - '1'\n - !GetAZs\n Ref: 'AWS::Region'\n InternetGateway:\n Type: 'AWS::EC2::InternetGateway'\n AttachGateway:\n Type: 'AWS::EC2::VPCGatewayAttachment'\n Properties:\n VpcId: !Ref Vpc\n InternetGatewayId: !Ref InternetGateway\n RouteViaIgw:\n Type: 'AWS::EC2::RouteTable'\n Properties:\n VpcId: !Ref Vpc\n PublicRouteViaIgw:\n Type: 'AWS::EC2::Route'\n DependsOn: AttachGateway\n Properties:\n RouteTableId: !Ref RouteViaIgw\n DestinationCidrBlock: 0.0.0.0/0\n GatewayId: !Ref InternetGateway\n PubSubnet1RouteTableAssociation:\n Type: 'AWS::EC2::SubnetRouteTableAssociation'\n Properties:\n SubnetId: !Ref PubSubnetAz1\n RouteTableId: !Ref RouteViaIgw\n PubSubnet2RouteTableAssociation:\n Type: 'AWS::EC2::SubnetRouteTableAssociation'\n Properties:\n SubnetId: !Ref PubSubnetAz2\n RouteTableId: !Ref RouteViaIgw\n EcsInternalSecurityGroup:\n Type: 'AWS::EC2::SecurityGroup'\n Properties:\n GroupDescription: ECS Allowed Ports\n VpcId: !Ref Vpc\n SecurityGroupIngress:\n - IpProtocol: tcp\n FromPort: '1'\n ToPort: '65535'\n SourceSecurityGroupId: !Ref AlbInternalSecurityGroup\n AlbInternalSecurityGroup:\n Type: 'AWS::EC2::SecurityGroup'\n Properties:\n GroupDescription: ELB Allowed Ports\n VpcId: !Ref Vpc\n SecurityGroupIngress:\n - IpProtocol: tcp\n FromPort: !Ref ElbPort\n ToPort: !Ref ElbPort\n CidrIp: !Ref SourceCidr\n InternalTargetGroup:\n Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'\n Properties:\n Name: !Join\n - ''\n - - !Ref 'AWS::StackName'\n - '-internal-tg'\n VpcId: !Ref Vpc\n Port: !Ref ElbPort\n Protocol: HTTP\n EcsInternalElasticLoadBalancer:\n Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'\n Properties:\n Name: !Join\n - ''\n - - !Ref 'AWS::StackName'\n - '-internal-alb'\n SecurityGroups:\n - !Ref AlbInternalSecurityGroup\n Subnets:\n - !Ref PubSubnetAz1\n - !Ref PubSubnetAz2\n Scheme: internal\n InternalLoadBalancerListener:\n Type: 'AWS::ElasticLoadBalancingV2::Listener'\n Properties:\n LoadBalancerArn: !Ref EcsInternalElasticLoadBalancer\n Port: !Ref ElbPort\n Protocol: HTTP\n DefaultActions:\n - Type: forward\n TargetGroupArn: !Ref InternalTargetGroup\n EcsInternetFacingSecurityGroup:\n Type: 'AWS::EC2::SecurityGroup'\n Properties:\n GroupDescription: ECS Allowed Ports\n VpcId: !Ref Vpc\n SecurityGroupIngress:\n - IpProtocol: tcp\n FromPort: '1'\n ToPort: '65535'\n SourceSecurityGroupId: !Ref AlbInternetFacingSecurityGroup\n AlbInternetFacingSecurityGroup:\n Type: 'AWS::EC2::SecurityGroup'\n Properties:\n GroupDescription: ELB Allowed Ports\n VpcId: !Ref Vpc\n SecurityGroupIngress:\n - IpProtocol: tcp\n FromPort: !Ref ElbPort\n ToPort: !Ref ElbPort\n CidrIp: !Ref SourceCidr\n InternetFacingTargetGroup:\n Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'\n Properties:\n Name: !Join\n - ''\n - - !Ref 'AWS::StackName'\n - '-internet-facing-tg'\n VpcId: !Ref Vpc\n Port: !Ref ElbPort\n Protocol: HTTP\n EcsInternetFacingElasticLoadBalancer:\n Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'\n Properties:\n Name: !Join\n - ''\n - - !Ref 'AWS::StackName'\n - '-internet-facing-alb'\n SecurityGroups:\n - !Ref AlbInternetFacingSecurityGroup\n Subnets:\n - !Ref PubSubnetAz1\n - !Ref PubSubnetAz2\n Scheme: internet-facing\n InternetFacingLoadBalancerListener:\n Type: 'AWS::ElasticLoadBalancingV2::Listener'\n Properties:\n LoadBalancerArn: !Ref EcsInternetFacingElasticLoadBalancer\n Port: !Ref ElbPort\n Protocol: HTTP\n DefaultActions:\n - Type: forward\n TargetGroupArn: !Ref InternetFacingTargetGroup\n EcsInstanceLc:\n Type: 'AWS::AutoScaling::LaunchConfiguration'\n Properties:\n ImageId: !Ref EcsAmiId\n InstanceType: !Ref EcsInstanceType\n AssociatePublicIpAddress: true\n IamInstanceProfile: !Ref IamRoleInstanceProfile\n KeyName: !If\n - CreateEC2LCWithKeyPair\n - !Ref KeyName\n - !Ref 'AWS::NoValue'\n SecurityGroups:\n - !Ref EcsInternalSecurityGroup\n - !Ref EcsInternetFacingSecurityGroup\n UserData: !If\n - SetEndpointToECSAgent\n - !Base64\n 'Fn::Join':\n - ''\n - - |\n #!/bin/bash\n - echo ECS_CLUSTER=\n - !Ref EcsClusterName\n - ' >> /etc/ecs/ecs.config'\n - |-\n\n echo ECS_BACKEND_HOST=\n - !Ref EcsEndpoint\n - ' >> /etc/ecs/ecs.config'\n - !Base64\n 'Fn::Join':\n - ''\n - - |\n #!/bin/bash\n - echo ECS_CLUSTER=\n - !Ref EcsClusterName\n - ' >> /etc/ecs/ecs.config'\n EcsInstanceAsg:\n Type: 'AWS::AutoScaling::AutoScalingGroup'\n Properties:\n VPCZoneIdentifier:\n - !Join\n - ','\n - - !Ref PubSubnetAz1\n - !Ref PubSubnetAz2\n LaunchConfigurationName: !Ref EcsInstanceLc\n MinSize: '0'\n MaxSize: !Ref AsgMaxSize\n DesiredCapacity: !Ref AsgMaxSize\n Tags:\n - Key: Name\n Value: !Join\n - ''\n - - 'ECS Instance - '\n - !Ref 'AWS::StackName'\n PropagateAtLaunch: 'true'\nOutputs:\n EcsInstanceAsgName:\n Description: Auto Scaling Group Name for ECS Instances\n Value: !Ref EcsInstanceAsg\n EcsInternalElbName:\n Description: Internal Load Balancer for ECS Service\n Value: !Ref EcsInternalElasticLoadBalancer\n EcsInternetFacingElbName:\n Description: Internet-facing Load Balancer for ECS Service\n Value: !Ref EcsInternetFacingElasticLoadBalancer\n" |
STABLECOIN_SYMBOLS = ['USDC', 'DAI', 'USDT', 'BUSD', 'TUSD', 'PAX', 'VAI']
FREE_RPC_ENDPOINTS = ['https://api.mycryptoapi.com/eth',
'https://nodes.mewapi.io/rpc/eth',
'https://mainnet-nethermind.blockscout.com/',
'https://mainnet.eth.cloud.ava.do/',
'https://cloudflare-eth.com/']
CHAINLINK_ADDRESSES = {'1INCH-ETH': '0x72AFAECF99C9d9C8215fF44C77B94B99C28741e8',
'AAVE-ETH': '0x6Df09E975c830ECae5bd4eD9d90f3A95a4f88012',
'AAVE-USD': '0x547a514d5e3769680Ce22B2361c10Ea13619e8a9',
'ADA-USD': '0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55',
'ADX-USD': '0x231e764B44b2C1b7Ca171fa8021A24ed520Cde10',
'ALPHA-ETH': '0x89c7926c7c15fD5BFDB1edcFf7E7fC8283B578F6',
'AMP-USD': '0x8797ABc4641dE76342b8acE9C63e3301DC35e3d8',
'AMPL-ETH': '0x492575FDD11a0fCf2C6C719867890a7648d526eB',
'AMPL-USD': '0xe20CA8D7546932360e37E9D72c1a47334af57706',
'ANT-ETH': '0x8f83670260F8f7708143b836a2a6F11eF0aBac01',
'APY TVL': '0x889f28E24EA0573db472EedEf7c4137B3357ac2B',
'AUD-USD': '0x77F9710E7d0A19669A13c055F62cd80d313dF022',
'BADGER-ETH': '0x58921Ac140522867bf50b9E009599Da0CA4A2379',
'BAL-ETH': '0xC1438AA3823A6Ba0C159CfA8D98dF5A994bA120b',
'BAND-ETH': '0x0BDb051e10c9718d1C29efbad442E88D38958274',
'BAND-USD': '0x919C77ACc7373D000b329c1276C76586ed2Dd19F',
'BAT-ETH': '0x0d16d4528239e9ee52fa531af613AcdB23D88c94',
'BCH-USD': '0x9F0F69428F923D6c95B781F89E165C9b2df9789D',
'BNB-ETH': '0xc546d2d06144F9DD42815b8bA46Ee7B8FcAFa4a2',
'BNB-USD': '0x14e613AC84a31f709eadbdF89C6CC390fDc9540A',
'BNT-ETH': '0xCf61d1841B178fe82C8895fe60c2EDDa08314416',
'BNT-USD': '0x1E6cF0D433de4FE882A437ABC654F58E1e78548c',
'BTC-ARS': '0xA912dd6b62B1C978e205B86994E057B1b494D73a',
'BTC-ETH': '0xdeb288F737066589598e9214E782fa5A8eD689e8',
'BTC-USD': '0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c',
'BTC-height': '0x4D2574c790d836b8C886615d927e9BA585B10EbA',
'BTC Difficulty': '0xA792Ebd0E4465DB2657c7971519Cfa0f0275F428',
'BUSD-ETH': '0x614715d2Af89E6EC99A233818275142cE88d1Cfd',
'BZRX-ETH': '0x8f7C7181Ed1a2BA41cfC3f5d064eF91b67daef66',
'CAD-USD': '0xa34317DB73e77d453b1B8d04550c44D10e981C8e',
'CEL-ETH': '0x75FbD83b4bd51dEe765b2a01e8D3aa1B020F9d33',
'CHF-USD': '0x449d117117838fFA61263B61dA6301AA2a88B13A',
'CNY-USD': '0xeF8A4aF35cd47424672E3C590aBD37FBB7A7759a',
'COMP-ETH': '0x1B39Ee86Ec5979ba5C322b826B3ECb8C79991699',
'COMP-USD': '0xdbd020CAeF83eFd542f4De03e3cF0C28A4428bd5',
'COVER-ETH': '0x7B6230EF79D5E97C11049ab362c0b685faCBA0C2',
'COVER-USD': '0x0ad50393F11FfAc4dd0fe5F1056448ecb75226Cf',
'CREAM-ETH': '0x82597CFE6af8baad7c0d441AA82cbC3b51759607',
'CRO-ETH': '0xcA696a9Eb93b81ADFE6435759A29aB4cf2991A96',
'CRV-ETH': '0x8a12Be339B0cD1829b91Adc01977caa5E9ac121e',
'CV-Index': '0x1B58B67B2b2Df71b4b0fb6691271E83A0fa36aC5',
'DAI-ETH': '0x773616E4d11A78F511299002da57A0a94577F1f4',
'DAI-USD': '0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9',
'DASH-USD': '0xFb0cADFEa136E9E343cfb55B863a6Df8348ab912',
'DIGG-BTC': '0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685',
'DMG-ETH': '0xD010e899f7ab723AC93f825cDC5Aa057669557c2',
'DOT-USD': '0x1C07AFb8E2B827c5A4739C6d59Ae3A5035f28734',
'DPI-ETH': '0x029849bbc0b1d93b85a8b6190e979fd38F5760E2',
'DPI-USD': '0xD2A593BF7594aCE1faD597adb697b5645d5edDB2',
'ENJ-ETH': '0x24D9aB51950F3d62E9144fdC2f3135DAA6Ce8D1B',
'EOS-USD': '0x10a43289895eAff840E8d45995BBa89f9115ECEe',
'ETC-USD': '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2',
'ETH-USD': '0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419',
'ETH-XDR': '0xb022E2970b3501d8d83eD07912330d178543C1eB',
'EUR-USD': '0xb49f677943BC038e9857d61E7d053CaA2C1734C1',
'EURS RESERVES': '0xbcD05A3E0c11f340cCcD9a4Efe05eEB2b33AB67A',
'FIL-ETH': '0x0606Be69451B1C9861Ac6b3626b99093b713E801',
'FIL-USD': '0x1A31D42149e82Eb99777f903C08A2E41A00085d3',
'FNX-USD': '0x80070f7151BdDbbB1361937ad4839317af99AE6c',
'FTM-ETH': '0x2DE7E4a9488488e0058B95854CC2f7955B35dC9b',
'FTSE-GBP': '0xE23FA0e8dd05D6f66a6e8c98cab2d9AE82A7550c',
'FTT-ETH': '0xF0985f7E2CaBFf22CecC5a71282a89582c382EFE',
'FXS-USD': '0x6Ebc52C8C1089be9eB3945C4350B68B8E4C2233f',
'Fast Gas-Gwei': '0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C',
'GBP-USD': '0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5',
'GRT-ETH': '0x17D054eCac33D91F7340645341eFB5DE9009F1C1',
'HEGIC-ETH': '0xAf5E8D9Cd9fC85725A83BF23C52f1C39A71588a6',
'HEGIC-USD': '0xBFC189aC214E6A4a35EBC281ad15669619b75534',
'INJ-USD': '0xaE2EbE3c4D20cE13cE47cbb49b6d7ee631Cd816e',
'IOST-USD': '0xd0935838935349401c73a06FCde9d63f719e84E5',
'JPY-USD': '0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3',
'KNC-ETH': '0x656c0544eF4C98A6a98491833A89204Abb045d6b',
'KNC-USD': '0xf8fF43E991A81e6eC886a3D281A2C6cC19aE70Fc',
'KP3R-ETH': '0xe7015CCb7E5F788B8c1010FC22343473EaaC3741',
'KRW-USD': '0x01435677FB11763550905594A16B645847C1d0F3',
'LINK-ETH': '0xDC530D9457755926550b59e8ECcdaE7624181557',
'LINK-USD': '0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c',
'LRC-ETH': '0x160AC928A16C93eD4895C2De6f81ECcE9a7eB7b4',
'LRC-USD': '0xFd33ec6ABAa1Bdc3D9C6C85f1D6299e5a1a5511F',
'LTC-USD': '0x6AF09DF7563C363B5763b9102712EbeD3b9e859B',
'MANA-ETH': '0x82A44D92D6c329826dc557c5E1Be6ebeC5D5FeB9',
'MATIC-USD': '0x7bAC85A8a13A4BcD8abb3eB7d6b4d632c5a57676',
'MKR-ETH': '0x24551a8Fb2A7211A25a17B1481f043A8a8adC7f2',
'MLN-ETH': '0xDaeA8386611A157B08829ED4997A8A62B557014C',
'MTA-ETH': '0x98334b85De2A8b998Ba844c5521e73D68AD69C00',
'MTA-USD': '0xc751E86208F0F8aF2d5CD0e29716cA7AD98B5eF5',
'N225-JPY': '0x5c4939a2ab3A2a9f93A518d81d4f8D0Bc6a68980',
'NMR-ETH': '0x9cB2A01A7E64992d32A34db7cEea4c919C391f6A',
'OGN-ETH': '0x2c881B6f3f6B5ff6C975813F87A4dad0b241C15b',
'OMG-ETH': '0x57C9aB3e56EE4a83752c181f241120a3DBba06a1',
'ONT-USD': '0xcDa3708C5c2907FCca52BB3f9d3e4c2028b89319',
'ORN-ETH': '0xbA9B2a360eb8aBdb677d6d7f27E12De11AA052ef',
'OXT-USD': '0xd75AAaE4AF0c398ca13e2667Be57AF2ccA8B5de6',
'Orchid': '0xa175FA75795c6Fb2aFA48B72d22054ee0DeDa4aC',
'PAX-ETH': '0x3a08ebBaB125224b7b6474384Ee39fBb247D2200',
'PAX-RESERVES': '0xf482Ed35406933F321f293aC0e4c6c8f59a22fA5',
'PAXG-ETH': '0x9B97304EA12EFed0FAd976FBeCAad46016bf269e',
'PAXG-RESERVES': '0x716BB8c60D409e54b8Fb5C4f6aBC50E794DA048a',
'PERP-ETH': '0x3b41D5571468904D4e53b6a8d93A6BaC43f02dC9',
'RCN-BTC': '0xEa0b3DCa635f4a4E77D9654C5c18836EE771566e',
'REN-ETH': '0x3147D7203354Dc06D9fd350c7a2437bcA92387a4',
'REN-USD': '0x0f59666EDE214281e956cb3b2D0d69415AfF4A01',
'REP-ETH': '0xD4CE430C3b67b3E2F7026D86E7128588629e2455',
'RLC-ETH': '0x4cba1e1fdc738D0fe8DB3ee07728E2Bc4DA676c6',
'RUNE-ETH': '0x875D60C44cfbC38BaA4Eb2dDB76A767dEB91b97e',
'SGD-USD': '0xe25277fF4bbF9081C75Ab0EB13B4A13a721f3E13',
'SNX-ETH': '0x79291A9d692Df95334B1a0B3B4AE6bC606782f8c',
'SNX-USD': '0xDC3EA94CD0AC27d9A86C180091e7f78C683d3699',
'SRM-ETH': '0x050c048c9a0CD0e76f166E2539F87ef2acCEC58f',
'SUSD-ETH': '0x8e0b7e6062272B5eF4524250bFFF8e5Bd3497757',
'SUSHI-ETH': '0xe572CeF69f43c2E488b33924AF04BDacE19079cf',
'SXP-USD': '0xFb0CfD6c19e25DB4a08D8a204a387cEa48Cc138f',
'TOMO-USD': '0x3d44925a8E9F9DFd90390E58e92Ec16c996A331b',
'TRU-USD': '0x26929b85fE284EeAB939831002e1928183a10fb1',
'TRX-USD': '0xacD0D1A29759CC01E8D925371B72cb2b5610EA25',
'TRY-USD': '0xB09fC5fD3f11Cf9eb5E1C5Dba43114e3C9f477b5',
'TSLA-USD': '0x1ceDaaB50936881B3e449e47e40A2cDAF5576A4a',
'TUSD-ETH': '0x3886BA987236181D98F2401c507Fb8BeA7871dF2',
'TUSD Reserves': '0x478f4c42b877c697C4b19E396865D4D533EcB6ea',
'TUSD Supply': '0x807b029DD462D5d9B9DB45dff90D3414013B969e',
'Total Marketcap-USD': '0xEC8761a0A73c34329CA5B1D3Dc7eD07F30e836e2',
'UMA-ETH': '0xf817B69EA583CAFF291E287CaE00Ea329d22765C',
'UNI-ETH': '0xD6aA3D25116d8dA79Ea0246c4826EB951872e02e',
'UNI-USD': '0x553303d460EE0afB37EdFf9bE42922D8FF63220e',
'USDC-ETH': '0x986b5E1e1755e3C2440e960477f25201B0a8bbD4',
'USDC-USD': '0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6',
'USDK-USD': '0xfAC81Ea9Dd29D8E9b212acd6edBEb6dE38Cb43Af',
'USDT-ETH': '0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46',
'USDT-USD': '0x3E7d1eAB13ad0104d2750B8863b489D65364e32D',
'UST-ETH': '0xa20623070413d42a5C01Db2c8111640DD7A5A03a',
'WAVES-USD': '0x9a79fdCd0E326dF6Fa34EA13c05d3106610798E9',
'WING-USD': '0x134fE0a225Fb8e6683617C13cEB6B3319fB4fb82',
'WNXM-ETH': '0xe5Dc0A609Ab8bCF15d3f35cFaa1Ff40f521173Ea',
'WOM-ETH': '0xcEBD2026d3C99F2a7CE028acf372C154aB4638a9',
'WTI-USD': '0xf3584F4dd3b467e73C2339EfD008665a70A4185c',
'XAG-USD': '0x379589227b15F1a12195D3f2d90bBc9F31f95235',
'XAU-USD': '0x214eD9Da11D2fbe465a6fc601a91E62EbEc1a0D6',
'XHV-USD': '0xeccBeEd9691d8521385259AE596CF00D68429de0',
'XMR-USD': '0xFA66458Cce7Dd15D8650015c4fce4D278271618F',
'XRP-USD': '0xCed2660c6Dd1Ffd856A5A82C67f3482d88C50b12',
'XTZ-USD': '0x5239a625dEb44bF3EeAc2CD5366ba24b8e9DB63F',
'YFI-ETH': '0x7c5d4F8345e66f68099581Db340cd65B078C41f4',
'YFI-USD': '0xA027702dbb89fbd58938e4324ac03B58d812b0E1',
'YFII-ETH': '0xaaB2f6b45B28E962B3aCd1ee4fC88aEdDf557756',
'ZRX-ETH': '0x2Da4983a622a8498bb1a21FaE9D8F6C664939962',
'ZRX-USD': '0x2885d15b8Af22648b98B122b22FDF4D2a56c6023',
'sCEX-USD': '0x283D433435cFCAbf00263beEF6A362b7cc5ed9f2',
'sDEFI-USD': '0xa8E875F94138B0C5b51d1e1d5dE35bbDdd28EA87'}
FIAT_SYMBOLS = ['AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD',
'BIF', 'BMD', 'BND', 'BOB', 'BRL', 'BSD', 'BTN', 'BWP', 'BYR', 'BZD', 'CAD', 'CDF', 'CHF', 'CLP', 'CNY',
'COP', 'CRC', 'CUC', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EEK', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD',
'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GQE', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF',
'IDR', 'ILS', 'INR', 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW',
'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LTL', 'LVL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD',
'MMK', 'MNT', 'MOP', 'MRO', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZM', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR',
'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'SAR', 'SBD',
'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TRY',
'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VEB', 'VND', 'VUV', 'WST', 'XAF', 'XCD', 'XDR',
'XOF', 'XPF', 'YER', 'ZAR', 'ZMK', 'ZWR'] | stablecoin_symbols = ['USDC', 'DAI', 'USDT', 'BUSD', 'TUSD', 'PAX', 'VAI']
free_rpc_endpoints = ['https://api.mycryptoapi.com/eth', 'https://nodes.mewapi.io/rpc/eth', 'https://mainnet-nethermind.blockscout.com/', 'https://mainnet.eth.cloud.ava.do/', 'https://cloudflare-eth.com/']
chainlink_addresses = {'1INCH-ETH': '0x72AFAECF99C9d9C8215fF44C77B94B99C28741e8', 'AAVE-ETH': '0x6Df09E975c830ECae5bd4eD9d90f3A95a4f88012', 'AAVE-USD': '0x547a514d5e3769680Ce22B2361c10Ea13619e8a9', 'ADA-USD': '0xAE48c91dF1fE419994FFDa27da09D5aC69c30f55', 'ADX-USD': '0x231e764B44b2C1b7Ca171fa8021A24ed520Cde10', 'ALPHA-ETH': '0x89c7926c7c15fD5BFDB1edcFf7E7fC8283B578F6', 'AMP-USD': '0x8797ABc4641dE76342b8acE9C63e3301DC35e3d8', 'AMPL-ETH': '0x492575FDD11a0fCf2C6C719867890a7648d526eB', 'AMPL-USD': '0xe20CA8D7546932360e37E9D72c1a47334af57706', 'ANT-ETH': '0x8f83670260F8f7708143b836a2a6F11eF0aBac01', 'APY TVL': '0x889f28E24EA0573db472EedEf7c4137B3357ac2B', 'AUD-USD': '0x77F9710E7d0A19669A13c055F62cd80d313dF022', 'BADGER-ETH': '0x58921Ac140522867bf50b9E009599Da0CA4A2379', 'BAL-ETH': '0xC1438AA3823A6Ba0C159CfA8D98dF5A994bA120b', 'BAND-ETH': '0x0BDb051e10c9718d1C29efbad442E88D38958274', 'BAND-USD': '0x919C77ACc7373D000b329c1276C76586ed2Dd19F', 'BAT-ETH': '0x0d16d4528239e9ee52fa531af613AcdB23D88c94', 'BCH-USD': '0x9F0F69428F923D6c95B781F89E165C9b2df9789D', 'BNB-ETH': '0xc546d2d06144F9DD42815b8bA46Ee7B8FcAFa4a2', 'BNB-USD': '0x14e613AC84a31f709eadbdF89C6CC390fDc9540A', 'BNT-ETH': '0xCf61d1841B178fe82C8895fe60c2EDDa08314416', 'BNT-USD': '0x1E6cF0D433de4FE882A437ABC654F58E1e78548c', 'BTC-ARS': '0xA912dd6b62B1C978e205B86994E057B1b494D73a', 'BTC-ETH': '0xdeb288F737066589598e9214E782fa5A8eD689e8', 'BTC-USD': '0xF4030086522a5bEEa4988F8cA5B36dbC97BeE88c', 'BTC-height': '0x4D2574c790d836b8C886615d927e9BA585B10EbA', 'BTC Difficulty': '0xA792Ebd0E4465DB2657c7971519Cfa0f0275F428', 'BUSD-ETH': '0x614715d2Af89E6EC99A233818275142cE88d1Cfd', 'BZRX-ETH': '0x8f7C7181Ed1a2BA41cfC3f5d064eF91b67daef66', 'CAD-USD': '0xa34317DB73e77d453b1B8d04550c44D10e981C8e', 'CEL-ETH': '0x75FbD83b4bd51dEe765b2a01e8D3aa1B020F9d33', 'CHF-USD': '0x449d117117838fFA61263B61dA6301AA2a88B13A', 'CNY-USD': '0xeF8A4aF35cd47424672E3C590aBD37FBB7A7759a', 'COMP-ETH': '0x1B39Ee86Ec5979ba5C322b826B3ECb8C79991699', 'COMP-USD': '0xdbd020CAeF83eFd542f4De03e3cF0C28A4428bd5', 'COVER-ETH': '0x7B6230EF79D5E97C11049ab362c0b685faCBA0C2', 'COVER-USD': '0x0ad50393F11FfAc4dd0fe5F1056448ecb75226Cf', 'CREAM-ETH': '0x82597CFE6af8baad7c0d441AA82cbC3b51759607', 'CRO-ETH': '0xcA696a9Eb93b81ADFE6435759A29aB4cf2991A96', 'CRV-ETH': '0x8a12Be339B0cD1829b91Adc01977caa5E9ac121e', 'CV-Index': '0x1B58B67B2b2Df71b4b0fb6691271E83A0fa36aC5', 'DAI-ETH': '0x773616E4d11A78F511299002da57A0a94577F1f4', 'DAI-USD': '0xAed0c38402a5d19df6E4c03F4E2DceD6e29c1ee9', 'DASH-USD': '0xFb0cADFEa136E9E343cfb55B863a6Df8348ab912', 'DIGG-BTC': '0x418a6C98CD5B8275955f08F0b8C1c6838c8b1685', 'DMG-ETH': '0xD010e899f7ab723AC93f825cDC5Aa057669557c2', 'DOT-USD': '0x1C07AFb8E2B827c5A4739C6d59Ae3A5035f28734', 'DPI-ETH': '0x029849bbc0b1d93b85a8b6190e979fd38F5760E2', 'DPI-USD': '0xD2A593BF7594aCE1faD597adb697b5645d5edDB2', 'ENJ-ETH': '0x24D9aB51950F3d62E9144fdC2f3135DAA6Ce8D1B', 'EOS-USD': '0x10a43289895eAff840E8d45995BBa89f9115ECEe', 'ETC-USD': '0xaEA2808407B7319A31A383B6F8B60f04BCa23cE2', 'ETH-USD': '0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419', 'ETH-XDR': '0xb022E2970b3501d8d83eD07912330d178543C1eB', 'EUR-USD': '0xb49f677943BC038e9857d61E7d053CaA2C1734C1', 'EURS RESERVES': '0xbcD05A3E0c11f340cCcD9a4Efe05eEB2b33AB67A', 'FIL-ETH': '0x0606Be69451B1C9861Ac6b3626b99093b713E801', 'FIL-USD': '0x1A31D42149e82Eb99777f903C08A2E41A00085d3', 'FNX-USD': '0x80070f7151BdDbbB1361937ad4839317af99AE6c', 'FTM-ETH': '0x2DE7E4a9488488e0058B95854CC2f7955B35dC9b', 'FTSE-GBP': '0xE23FA0e8dd05D6f66a6e8c98cab2d9AE82A7550c', 'FTT-ETH': '0xF0985f7E2CaBFf22CecC5a71282a89582c382EFE', 'FXS-USD': '0x6Ebc52C8C1089be9eB3945C4350B68B8E4C2233f', 'Fast Gas-Gwei': '0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C', 'GBP-USD': '0x5c0Ab2d9b5a7ed9f470386e82BB36A3613cDd4b5', 'GRT-ETH': '0x17D054eCac33D91F7340645341eFB5DE9009F1C1', 'HEGIC-ETH': '0xAf5E8D9Cd9fC85725A83BF23C52f1C39A71588a6', 'HEGIC-USD': '0xBFC189aC214E6A4a35EBC281ad15669619b75534', 'INJ-USD': '0xaE2EbE3c4D20cE13cE47cbb49b6d7ee631Cd816e', 'IOST-USD': '0xd0935838935349401c73a06FCde9d63f719e84E5', 'JPY-USD': '0xBcE206caE7f0ec07b545EddE332A47C2F75bbeb3', 'KNC-ETH': '0x656c0544eF4C98A6a98491833A89204Abb045d6b', 'KNC-USD': '0xf8fF43E991A81e6eC886a3D281A2C6cC19aE70Fc', 'KP3R-ETH': '0xe7015CCb7E5F788B8c1010FC22343473EaaC3741', 'KRW-USD': '0x01435677FB11763550905594A16B645847C1d0F3', 'LINK-ETH': '0xDC530D9457755926550b59e8ECcdaE7624181557', 'LINK-USD': '0x2c1d072e956AFFC0D435Cb7AC38EF18d24d9127c', 'LRC-ETH': '0x160AC928A16C93eD4895C2De6f81ECcE9a7eB7b4', 'LRC-USD': '0xFd33ec6ABAa1Bdc3D9C6C85f1D6299e5a1a5511F', 'LTC-USD': '0x6AF09DF7563C363B5763b9102712EbeD3b9e859B', 'MANA-ETH': '0x82A44D92D6c329826dc557c5E1Be6ebeC5D5FeB9', 'MATIC-USD': '0x7bAC85A8a13A4BcD8abb3eB7d6b4d632c5a57676', 'MKR-ETH': '0x24551a8Fb2A7211A25a17B1481f043A8a8adC7f2', 'MLN-ETH': '0xDaeA8386611A157B08829ED4997A8A62B557014C', 'MTA-ETH': '0x98334b85De2A8b998Ba844c5521e73D68AD69C00', 'MTA-USD': '0xc751E86208F0F8aF2d5CD0e29716cA7AD98B5eF5', 'N225-JPY': '0x5c4939a2ab3A2a9f93A518d81d4f8D0Bc6a68980', 'NMR-ETH': '0x9cB2A01A7E64992d32A34db7cEea4c919C391f6A', 'OGN-ETH': '0x2c881B6f3f6B5ff6C975813F87A4dad0b241C15b', 'OMG-ETH': '0x57C9aB3e56EE4a83752c181f241120a3DBba06a1', 'ONT-USD': '0xcDa3708C5c2907FCca52BB3f9d3e4c2028b89319', 'ORN-ETH': '0xbA9B2a360eb8aBdb677d6d7f27E12De11AA052ef', 'OXT-USD': '0xd75AAaE4AF0c398ca13e2667Be57AF2ccA8B5de6', 'Orchid': '0xa175FA75795c6Fb2aFA48B72d22054ee0DeDa4aC', 'PAX-ETH': '0x3a08ebBaB125224b7b6474384Ee39fBb247D2200', 'PAX-RESERVES': '0xf482Ed35406933F321f293aC0e4c6c8f59a22fA5', 'PAXG-ETH': '0x9B97304EA12EFed0FAd976FBeCAad46016bf269e', 'PAXG-RESERVES': '0x716BB8c60D409e54b8Fb5C4f6aBC50E794DA048a', 'PERP-ETH': '0x3b41D5571468904D4e53b6a8d93A6BaC43f02dC9', 'RCN-BTC': '0xEa0b3DCa635f4a4E77D9654C5c18836EE771566e', 'REN-ETH': '0x3147D7203354Dc06D9fd350c7a2437bcA92387a4', 'REN-USD': '0x0f59666EDE214281e956cb3b2D0d69415AfF4A01', 'REP-ETH': '0xD4CE430C3b67b3E2F7026D86E7128588629e2455', 'RLC-ETH': '0x4cba1e1fdc738D0fe8DB3ee07728E2Bc4DA676c6', 'RUNE-ETH': '0x875D60C44cfbC38BaA4Eb2dDB76A767dEB91b97e', 'SGD-USD': '0xe25277fF4bbF9081C75Ab0EB13B4A13a721f3E13', 'SNX-ETH': '0x79291A9d692Df95334B1a0B3B4AE6bC606782f8c', 'SNX-USD': '0xDC3EA94CD0AC27d9A86C180091e7f78C683d3699', 'SRM-ETH': '0x050c048c9a0CD0e76f166E2539F87ef2acCEC58f', 'SUSD-ETH': '0x8e0b7e6062272B5eF4524250bFFF8e5Bd3497757', 'SUSHI-ETH': '0xe572CeF69f43c2E488b33924AF04BDacE19079cf', 'SXP-USD': '0xFb0CfD6c19e25DB4a08D8a204a387cEa48Cc138f', 'TOMO-USD': '0x3d44925a8E9F9DFd90390E58e92Ec16c996A331b', 'TRU-USD': '0x26929b85fE284EeAB939831002e1928183a10fb1', 'TRX-USD': '0xacD0D1A29759CC01E8D925371B72cb2b5610EA25', 'TRY-USD': '0xB09fC5fD3f11Cf9eb5E1C5Dba43114e3C9f477b5', 'TSLA-USD': '0x1ceDaaB50936881B3e449e47e40A2cDAF5576A4a', 'TUSD-ETH': '0x3886BA987236181D98F2401c507Fb8BeA7871dF2', 'TUSD Reserves': '0x478f4c42b877c697C4b19E396865D4D533EcB6ea', 'TUSD Supply': '0x807b029DD462D5d9B9DB45dff90D3414013B969e', 'Total Marketcap-USD': '0xEC8761a0A73c34329CA5B1D3Dc7eD07F30e836e2', 'UMA-ETH': '0xf817B69EA583CAFF291E287CaE00Ea329d22765C', 'UNI-ETH': '0xD6aA3D25116d8dA79Ea0246c4826EB951872e02e', 'UNI-USD': '0x553303d460EE0afB37EdFf9bE42922D8FF63220e', 'USDC-ETH': '0x986b5E1e1755e3C2440e960477f25201B0a8bbD4', 'USDC-USD': '0x8fFfFfd4AfB6115b954Bd326cbe7B4BA576818f6', 'USDK-USD': '0xfAC81Ea9Dd29D8E9b212acd6edBEb6dE38Cb43Af', 'USDT-ETH': '0xEe9F2375b4bdF6387aa8265dD4FB8F16512A1d46', 'USDT-USD': '0x3E7d1eAB13ad0104d2750B8863b489D65364e32D', 'UST-ETH': '0xa20623070413d42a5C01Db2c8111640DD7A5A03a', 'WAVES-USD': '0x9a79fdCd0E326dF6Fa34EA13c05d3106610798E9', 'WING-USD': '0x134fE0a225Fb8e6683617C13cEB6B3319fB4fb82', 'WNXM-ETH': '0xe5Dc0A609Ab8bCF15d3f35cFaa1Ff40f521173Ea', 'WOM-ETH': '0xcEBD2026d3C99F2a7CE028acf372C154aB4638a9', 'WTI-USD': '0xf3584F4dd3b467e73C2339EfD008665a70A4185c', 'XAG-USD': '0x379589227b15F1a12195D3f2d90bBc9F31f95235', 'XAU-USD': '0x214eD9Da11D2fbe465a6fc601a91E62EbEc1a0D6', 'XHV-USD': '0xeccBeEd9691d8521385259AE596CF00D68429de0', 'XMR-USD': '0xFA66458Cce7Dd15D8650015c4fce4D278271618F', 'XRP-USD': '0xCed2660c6Dd1Ffd856A5A82C67f3482d88C50b12', 'XTZ-USD': '0x5239a625dEb44bF3EeAc2CD5366ba24b8e9DB63F', 'YFI-ETH': '0x7c5d4F8345e66f68099581Db340cd65B078C41f4', 'YFI-USD': '0xA027702dbb89fbd58938e4324ac03B58d812b0E1', 'YFII-ETH': '0xaaB2f6b45B28E962B3aCd1ee4fC88aEdDf557756', 'ZRX-ETH': '0x2Da4983a622a8498bb1a21FaE9D8F6C664939962', 'ZRX-USD': '0x2885d15b8Af22648b98B122b22FDF4D2a56c6023', 'sCEX-USD': '0x283D433435cFCAbf00263beEF6A362b7cc5ed9f2', 'sDEFI-USD': '0xa8E875F94138B0C5b51d1e1d5dE35bbDdd28EA87'}
fiat_symbols = ['AED', 'AFN', 'ALL', 'AMD', 'ANG', 'AOA', 'ARS', 'AUD', 'AWG', 'AZN', 'BAM', 'BBD', 'BDT', 'BGN', 'BHD', 'BIF', 'BMD', 'BND', 'BOB', 'BRL', 'BSD', 'BTN', 'BWP', 'BYR', 'BZD', 'CAD', 'CDF', 'CHF', 'CLP', 'CNY', 'COP', 'CRC', 'CUC', 'CVE', 'CZK', 'DJF', 'DKK', 'DOP', 'DZD', 'EEK', 'EGP', 'ERN', 'ETB', 'EUR', 'FJD', 'FKP', 'GBP', 'GEL', 'GHS', 'GIP', 'GMD', 'GNF', 'GQE', 'GTQ', 'GYD', 'HKD', 'HNL', 'HRK', 'HTG', 'HUF', 'IDR', 'ILS', 'INR', 'IQD', 'IRR', 'ISK', 'JMD', 'JOD', 'JPY', 'KES', 'KGS', 'KHR', 'KMF', 'KPW', 'KRW', 'KWD', 'KYD', 'KZT', 'LAK', 'LBP', 'LKR', 'LRD', 'LSL', 'LTL', 'LVL', 'LYD', 'MAD', 'MDL', 'MGA', 'MKD', 'MMK', 'MNT', 'MOP', 'MRO', 'MUR', 'MVR', 'MWK', 'MXN', 'MYR', 'MZM', 'NAD', 'NGN', 'NIO', 'NOK', 'NPR', 'NZD', 'OMR', 'PAB', 'PEN', 'PGK', 'PHP', 'PKR', 'PLN', 'PYG', 'QAR', 'RON', 'RSD', 'RUB', 'SAR', 'SBD', 'SCR', 'SDG', 'SEK', 'SGD', 'SHP', 'SLL', 'SOS', 'SRD', 'SYP', 'SZL', 'THB', 'TJS', 'TMT', 'TND', 'TRY', 'TTD', 'TWD', 'TZS', 'UAH', 'UGX', 'USD', 'UYU', 'UZS', 'VEB', 'VND', 'VUV', 'WST', 'XAF', 'XCD', 'XDR', 'XOF', 'XPF', 'YER', 'ZAR', 'ZMK', 'ZWR'] |
# -*- coding: utf-8 -*-
class SyncCommand(object):
"""
Helper class to call core sync
"""
def __init__(self, core):
self.core = core
def do(self):
"""
Do core sync
"""
self.core.sync()
| class Synccommand(object):
"""
Helper class to call core sync
"""
def __init__(self, core):
self.core = core
def do(self):
"""
Do core sync
"""
self.core.sync() |
# based on nuts_and_bolts.scad from MCAD library
# https:# github.com/elmom/MCAD/
# Copyright 2010 D1plo1d
# This library is dual licensed under the GPL 3.0 and the GNU Lesser General Public License as per http:# creativecommons.org/licenses/LGPL/2.1/ .
MM = "mm"
INCH = "inch" # Not yet supported
# Based on: http:# www.roymech.co.uk/Useful_Tables/Screws/Hex_Screws.htm
METRIC_NUT_AC_WIDTHS = [
-1, # 0 index is not used but reduces computation
-1,
-1,
6.40, # m3
8.10, # m4
9.20, # m5
11.50, # m6
-1,
15.00, # m8
-1,
19.60, # m10
-1,
22.10, # m12
-1,
-1,
-1,
27.70, # m16
-1,
-1,
-1,
34.60, # m20
-1,
-1,
-1,
41.60, # m24
-1,
-1,
-1,
-1,
-1,
53.1, # m30
-1,
-1,
-1,
-1,
-1,
63.5 # m36
]
METRIC_NUT_THICKNESS = [
-1, # 0 index is not used but reduces computation
-1,
-1,
2.40, # m3
3.20, # m4
4.00, # m5
5.00, # m6
-1,
6.50, # m8
-1,
8.00, # m10
-1,
10.00, # m12
-1,
-1,
-1,
13.00, # m16
-1,
-1,
-1,
16.00 # m20
-1,
-1,
-1,
19.00, # m24
-1,
-1,
-1,
-1,
-1,
24.00, # m30
-1,
-1,
-1,
-1,
-1,
29.00 # m36
]
COURSE_METRIC_BOLT_MAJOR_THREAD_DIAMETERS = [
# based on max values
-1, # 0 index is not used but reduces computation
-1,
-1,
2.98, # m3
3.978, # m4
4.976, # m5
5.974, # m6
-1,
7.972, # m8
-1,
9.968, # m10
-1,
11.966, # m12
-1,
-1,
-1,
15.962, # m16
-1,
-1,
-1,
19.958, # m20
-1,
-1,
-1,
23.952, # m24
-1,
-1,
-1,
-1,
-1,
29.947, # m30
-1,
-1,
-1,
-1,
-1,
35.940 # m36
]
| mm = 'mm'
inch = 'inch'
metric_nut_ac_widths = [-1, -1, -1, 6.4, 8.1, 9.2, 11.5, -1, 15.0, -1, 19.6, -1, 22.1, -1, -1, -1, 27.7, -1, -1, -1, 34.6, -1, -1, -1, 41.6, -1, -1, -1, -1, -1, 53.1, -1, -1, -1, -1, -1, 63.5]
metric_nut_thickness = [-1, -1, -1, 2.4, 3.2, 4.0, 5.0, -1, 6.5, -1, 8.0, -1, 10.0, -1, -1, -1, 13.0, -1, -1, -1, 16.0 - 1, -1, -1, 19.0, -1, -1, -1, -1, -1, 24.0, -1, -1, -1, -1, -1, 29.0]
course_metric_bolt_major_thread_diameters = [-1, -1, -1, 2.98, 3.978, 4.976, 5.974, -1, 7.972, -1, 9.968, -1, 11.966, -1, -1, -1, 15.962, -1, -1, -1, 19.958, -1, -1, -1, 23.952, -1, -1, -1, -1, -1, 29.947, -1, -1, -1, -1, -1, 35.94] |
var = 77
def func():
global var
var = 100
print(locals())
func()
print(var)
| var = 77
def func():
global var
var = 100
print(locals())
func()
print(var) |
def solution(xs):
mn = -1000
count = 0
product = 0
for element in xs:
if element != 0:
if product != 0:
product = product * element
else:
product = element
count += 1
if element < 0 and element > mn:
mn = element
if product > -1:
return str(product)
else:
if count > 1:
product = product / mn
return str(product)
else:
if 0 in xs:
return '0'
else:
return str(product)
print(solution([-1]))
print(solution([0]))
print(solution([1]))
print(solution([-1,1]))
print(solution([-1,0]))
print(solution([1,0]))
print(solution([-99,-99]))
print(solution([-1,1,0]))
print(solution([99, 99, -1, -99]))
print(solution([98, 98, -100]))
| def solution(xs):
mn = -1000
count = 0
product = 0
for element in xs:
if element != 0:
if product != 0:
product = product * element
else:
product = element
count += 1
if element < 0 and element > mn:
mn = element
if product > -1:
return str(product)
elif count > 1:
product = product / mn
return str(product)
elif 0 in xs:
return '0'
else:
return str(product)
print(solution([-1]))
print(solution([0]))
print(solution([1]))
print(solution([-1, 1]))
print(solution([-1, 0]))
print(solution([1, 0]))
print(solution([-99, -99]))
print(solution([-1, 1, 0]))
print(solution([99, 99, -1, -99]))
print(solution([98, 98, -100])) |
first_num = 2
secord_num = 3
sum = first_num + secord_num
print(sum)
| first_num = 2
secord_num = 3
sum = first_num + secord_num
print(sum) |
#
# PySNMP MIB module NOKIA-NTP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NOKIA-NTP-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:13:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint")
ntcNtpMibs, ntcNtpReqs, ntcCommonModules = mibBuilder.importSymbols("NOKIA-COMMON-MIB-OID-REGISTRATION-MIB", "ntcNtpMibs", "ntcNtpReqs", "ntcCommonModules")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
Gauge32, Bits, Integer32, iso, ObjectIdentity, IpAddress, TimeTicks, MibIdentifier, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Counter64, Unsigned32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Bits", "Integer32", "iso", "ObjectIdentity", "IpAddress", "TimeTicks", "MibIdentifier", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Counter64", "Unsigned32", "NotificationType")
RowStatus, DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TruthValue", "TextualConvention")
nokiaNtpMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 94, 1, 16, 5, 2))
nokiaNtpMIB.setRevisions(('1998-10-07 00:00',))
if mibBuilder.loadTexts: nokiaNtpMIB.setLastUpdated('9908050000Z')
if mibBuilder.loadTexts: nokiaNtpMIB.setOrganization('Nokia')
nokiaNtpObjs = MibIdentifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1))
ntcNtpConf = MibIdentifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1))
ntcNtpRtcConf = MibIdentifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 2))
ntcNtpGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 1))
ntcNtpCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 2))
class EnabledDisabled(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("enabled", 1), ("disabled", 2))
class TimeServerStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))
namedValues = NamedValues(("ok", 1), ("notReachable", 2), ("clockNotInSynch", 3), ("diffTooBig", 4), ("otherError", 5))
ntcNtpEnabled = MibScalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 1), EnabledDisabled()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ntcNtpEnabled.setStatus('current')
ntcNtpServerTableNextIndex = MibScalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ntcNtpServerTableNextIndex.setStatus('current')
ntcNtpServerTable = MibTable((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3), )
if mibBuilder.loadTexts: ntcNtpServerTable.setStatus('current')
ntcNtpServerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1), ).setIndexNames((0, "NOKIA-NTP-MIB", "ntcNtpServerIndex"))
if mibBuilder.loadTexts: ntcNtpServerEntry.setStatus('current')
ntcNtpServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647)))
if mibBuilder.loadTexts: ntcNtpServerIndex.setStatus('current')
ntcNtpServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ntcNtpServerAddress.setStatus('current')
ntcNtpServerPort = MibTableColumn((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ntcNtpServerPort.setStatus('current')
ntcNtpServerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 4), TimeServerStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ntcNtpServerStatus.setStatus('current')
ntcNtpServerPreferred = MibTableColumn((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 5), TruthValue()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ntcNtpServerPreferred.setStatus('current')
ntcNtpServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 6), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ntcNtpServerRowStatus.setStatus('current')
ntcNtpRtcCurrentTime = MibScalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 2, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(11, 11)).setFixedLength(11)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ntcNtpRtcCurrentTime.setStatus('current')
ntcNtpRtcTimeZone = MibScalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 2, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ntcNtpRtcTimeZone.setStatus('current')
nokiaNtpCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 2, 1)).setObjects(("NOKIA-NTP-MIB", "ntcNtpMinimumRTCGroup"), ("NOKIA-NTP-MIB", "ntcNtpMandatoryNTPGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
nokiaNtpCompliance = nokiaNtpCompliance.setStatus('current')
ntcNtpMinimumRTCGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 1, 1)).setObjects(("NOKIA-NTP-MIB", "ntcNtpRtcCurrentTime"), ("NOKIA-NTP-MIB", "ntcNtpRtcTimeZone"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ntcNtpMinimumRTCGroup = ntcNtpMinimumRTCGroup.setStatus('current')
ntcNtpMandatoryNTPGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 1, 2)).setObjects(("NOKIA-NTP-MIB", "ntcNtpEnabled"), ("NOKIA-NTP-MIB", "ntcNtpServerTableNextIndex"), ("NOKIA-NTP-MIB", "ntcNtpServerAddress"), ("NOKIA-NTP-MIB", "ntcNtpServerPort"), ("NOKIA-NTP-MIB", "ntcNtpServerStatus"), ("NOKIA-NTP-MIB", "ntcNtpServerPreferred"), ("NOKIA-NTP-MIB", "ntcNtpServerRowStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ntcNtpMandatoryNTPGroup = ntcNtpMandatoryNTPGroup.setStatus('current')
mibBuilder.exportSymbols("NOKIA-NTP-MIB", ntcNtpMandatoryNTPGroup=ntcNtpMandatoryNTPGroup, ntcNtpMinimumRTCGroup=ntcNtpMinimumRTCGroup, ntcNtpServerStatus=ntcNtpServerStatus, ntcNtpServerRowStatus=ntcNtpServerRowStatus, nokiaNtpMIB=nokiaNtpMIB, ntcNtpServerEntry=ntcNtpServerEntry, ntcNtpRtcTimeZone=ntcNtpRtcTimeZone, ntcNtpRtcConf=ntcNtpRtcConf, ntcNtpServerTableNextIndex=ntcNtpServerTableNextIndex, ntcNtpServerTable=ntcNtpServerTable, nokiaNtpCompliance=nokiaNtpCompliance, ntcNtpEnabled=ntcNtpEnabled, ntcNtpRtcCurrentTime=ntcNtpRtcCurrentTime, ntcNtpCompliances=ntcNtpCompliances, EnabledDisabled=EnabledDisabled, ntcNtpServerAddress=ntcNtpServerAddress, nokiaNtpObjs=nokiaNtpObjs, PYSNMP_MODULE_ID=nokiaNtpMIB, TimeServerStatus=TimeServerStatus, ntcNtpServerPreferred=ntcNtpServerPreferred, ntcNtpServerPort=ntcNtpServerPort, ntcNtpServerIndex=ntcNtpServerIndex, ntcNtpGroups=ntcNtpGroups, ntcNtpConf=ntcNtpConf)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_size_constraint, single_value_constraint, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint')
(ntc_ntp_mibs, ntc_ntp_reqs, ntc_common_modules) = mibBuilder.importSymbols('NOKIA-COMMON-MIB-OID-REGISTRATION-MIB', 'ntcNtpMibs', 'ntcNtpReqs', 'ntcCommonModules')
(module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup')
(gauge32, bits, integer32, iso, object_identity, ip_address, time_ticks, mib_identifier, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, counter64, unsigned32, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Bits', 'Integer32', 'iso', 'ObjectIdentity', 'IpAddress', 'TimeTicks', 'MibIdentifier', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'Counter64', 'Unsigned32', 'NotificationType')
(row_status, display_string, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TruthValue', 'TextualConvention')
nokia_ntp_mib = module_identity((1, 3, 6, 1, 4, 1, 94, 1, 16, 5, 2))
nokiaNtpMIB.setRevisions(('1998-10-07 00:00',))
if mibBuilder.loadTexts:
nokiaNtpMIB.setLastUpdated('9908050000Z')
if mibBuilder.loadTexts:
nokiaNtpMIB.setOrganization('Nokia')
nokia_ntp_objs = mib_identifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1))
ntc_ntp_conf = mib_identifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1))
ntc_ntp_rtc_conf = mib_identifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 2))
ntc_ntp_groups = mib_identifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 1))
ntc_ntp_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 2))
class Enableddisabled(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('enabled', 1), ('disabled', 2))
class Timeserverstatus(TextualConvention, Integer32):
status = 'current'
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5))
named_values = named_values(('ok', 1), ('notReachable', 2), ('clockNotInSynch', 3), ('diffTooBig', 4), ('otherError', 5))
ntc_ntp_enabled = mib_scalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 1), enabled_disabled()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ntcNtpEnabled.setStatus('current')
ntc_ntp_server_table_next_index = mib_scalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ntcNtpServerTableNextIndex.setStatus('current')
ntc_ntp_server_table = mib_table((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3))
if mibBuilder.loadTexts:
ntcNtpServerTable.setStatus('current')
ntc_ntp_server_entry = mib_table_row((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1)).setIndexNames((0, 'NOKIA-NTP-MIB', 'ntcNtpServerIndex'))
if mibBuilder.loadTexts:
ntcNtpServerEntry.setStatus('current')
ntc_ntp_server_index = mib_table_column((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647)))
if mibBuilder.loadTexts:
ntcNtpServerIndex.setStatus('current')
ntc_ntp_server_address = mib_table_column((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ntcNtpServerAddress.setStatus('current')
ntc_ntp_server_port = mib_table_column((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ntcNtpServerPort.setStatus('current')
ntc_ntp_server_status = mib_table_column((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 4), time_server_status()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ntcNtpServerStatus.setStatus('current')
ntc_ntp_server_preferred = mib_table_column((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 5), truth_value()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ntcNtpServerPreferred.setStatus('current')
ntc_ntp_server_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 1, 3, 1, 6), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ntcNtpServerRowStatus.setStatus('current')
ntc_ntp_rtc_current_time = mib_scalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 2, 1), octet_string().subtype(subtypeSpec=value_size_constraint(11, 11)).setFixedLength(11)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ntcNtpRtcCurrentTime.setStatus('current')
ntc_ntp_rtc_time_zone = mib_scalar((1, 3, 6, 1, 4, 1, 94, 1, 16, 7, 2, 1, 2, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 128))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ntcNtpRtcTimeZone.setStatus('current')
nokia_ntp_compliance = module_compliance((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 2, 1)).setObjects(('NOKIA-NTP-MIB', 'ntcNtpMinimumRTCGroup'), ('NOKIA-NTP-MIB', 'ntcNtpMandatoryNTPGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
nokia_ntp_compliance = nokiaNtpCompliance.setStatus('current')
ntc_ntp_minimum_rtc_group = object_group((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 1, 1)).setObjects(('NOKIA-NTP-MIB', 'ntcNtpRtcCurrentTime'), ('NOKIA-NTP-MIB', 'ntcNtpRtcTimeZone'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ntc_ntp_minimum_rtc_group = ntcNtpMinimumRTCGroup.setStatus('current')
ntc_ntp_mandatory_ntp_group = object_group((1, 3, 6, 1, 4, 1, 94, 1, 16, 8, 2, 1, 2)).setObjects(('NOKIA-NTP-MIB', 'ntcNtpEnabled'), ('NOKIA-NTP-MIB', 'ntcNtpServerTableNextIndex'), ('NOKIA-NTP-MIB', 'ntcNtpServerAddress'), ('NOKIA-NTP-MIB', 'ntcNtpServerPort'), ('NOKIA-NTP-MIB', 'ntcNtpServerStatus'), ('NOKIA-NTP-MIB', 'ntcNtpServerPreferred'), ('NOKIA-NTP-MIB', 'ntcNtpServerRowStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ntc_ntp_mandatory_ntp_group = ntcNtpMandatoryNTPGroup.setStatus('current')
mibBuilder.exportSymbols('NOKIA-NTP-MIB', ntcNtpMandatoryNTPGroup=ntcNtpMandatoryNTPGroup, ntcNtpMinimumRTCGroup=ntcNtpMinimumRTCGroup, ntcNtpServerStatus=ntcNtpServerStatus, ntcNtpServerRowStatus=ntcNtpServerRowStatus, nokiaNtpMIB=nokiaNtpMIB, ntcNtpServerEntry=ntcNtpServerEntry, ntcNtpRtcTimeZone=ntcNtpRtcTimeZone, ntcNtpRtcConf=ntcNtpRtcConf, ntcNtpServerTableNextIndex=ntcNtpServerTableNextIndex, ntcNtpServerTable=ntcNtpServerTable, nokiaNtpCompliance=nokiaNtpCompliance, ntcNtpEnabled=ntcNtpEnabled, ntcNtpRtcCurrentTime=ntcNtpRtcCurrentTime, ntcNtpCompliances=ntcNtpCompliances, EnabledDisabled=EnabledDisabled, ntcNtpServerAddress=ntcNtpServerAddress, nokiaNtpObjs=nokiaNtpObjs, PYSNMP_MODULE_ID=nokiaNtpMIB, TimeServerStatus=TimeServerStatus, ntcNtpServerPreferred=ntcNtpServerPreferred, ntcNtpServerPort=ntcNtpServerPort, ntcNtpServerIndex=ntcNtpServerIndex, ntcNtpGroups=ntcNtpGroups, ntcNtpConf=ntcNtpConf) |
"""
.. module:: errors
:platform: Unix, Windows
:synopsis: Global error classes for gNMIP-API
.. moduleauthor:: Greg Brown <gsb5067@gmail.com>
"""
class GNMIException(Exception):
""" Exception for GNMI API Errors """
pass
class ElasticSearchUploaderException(Exception):
""" Exception for ElasticSearchUploader Errors """
pass
| """
.. module:: errors
:platform: Unix, Windows
:synopsis: Global error classes for gNMIP-API
.. moduleauthor:: Greg Brown <gsb5067@gmail.com>
"""
class Gnmiexception(Exception):
""" Exception for GNMI API Errors """
pass
class Elasticsearchuploaderexception(Exception):
""" Exception for ElasticSearchUploader Errors """
pass |
#!/usr/bin/python
#300 most common words according to google
#Source: https://github.com/first20hours/google-10000-english
#Some words that might refer to scientific information have been removed
boringWords=set(['the','of','and','to','a','in','for','is','on','that','by','this','with','i','you','it','not','or','be','are','from','at','as','your','all','have','new','more','an','was','we','will','home','can','us','about','if','page','my','has','search','free','but','our','one','other','do','no','information','time','they','site','he','up','may','what','which','their','news','out','use','any','there','see','only','so','his','when','contact','here','business','who','web','also','now','help','get','pm','view','online','c','e','first','am','been','would','how','were','me','s','services','some','these','click','its','like','service','x','than','find','price','date','back','top','people','had','list','name','just','over','state','year','day','into','email','two','health','n','world','re','next','used','go','b','work','last','most','products','music','buy','data','make','them','should','product','system','post','her','city','t','add','policy','number','such','please','available','copyright','support','message','after','best','software','then','jan','good','video','well','d','where','info','rights','public','books','high','school','through','m','each','links','she','review','years','order','very','privacy','book','items','company','r','read','group','sex','need','many','user','said','de','does','set','under','general','research','university','january','mail','full','map','reviews','program','life','know','games','way','days','management','p','part','could','great','united','hotel','real','f','item','international','center','ebay','must','store','travel','comments','made','development','report','off','member','details','line','terms','before','hotels','did','send','right','type','because','those','using','results','office','education','national','car','design','take','posted','internet','address','community','within','states','area','want','phone','dvd','shipping','reserved','subject','between','forum','family','l','long','based','w','code','show','o','even','black','check','special','prices','website','index','being','women','much','sign','file','link','open','today','technology','south','case','project','same','pages','version','section','own','found','sports','house','related','both'])
| boring_words = set(['the', 'of', 'and', 'to', 'a', 'in', 'for', 'is', 'on', 'that', 'by', 'this', 'with', 'i', 'you', 'it', 'not', 'or', 'be', 'are', 'from', 'at', 'as', 'your', 'all', 'have', 'new', 'more', 'an', 'was', 'we', 'will', 'home', 'can', 'us', 'about', 'if', 'page', 'my', 'has', 'search', 'free', 'but', 'our', 'one', 'other', 'do', 'no', 'information', 'time', 'they', 'site', 'he', 'up', 'may', 'what', 'which', 'their', 'news', 'out', 'use', 'any', 'there', 'see', 'only', 'so', 'his', 'when', 'contact', 'here', 'business', 'who', 'web', 'also', 'now', 'help', 'get', 'pm', 'view', 'online', 'c', 'e', 'first', 'am', 'been', 'would', 'how', 'were', 'me', 's', 'services', 'some', 'these', 'click', 'its', 'like', 'service', 'x', 'than', 'find', 'price', 'date', 'back', 'top', 'people', 'had', 'list', 'name', 'just', 'over', 'state', 'year', 'day', 'into', 'email', 'two', 'health', 'n', 'world', 're', 'next', 'used', 'go', 'b', 'work', 'last', 'most', 'products', 'music', 'buy', 'data', 'make', 'them', 'should', 'product', 'system', 'post', 'her', 'city', 't', 'add', 'policy', 'number', 'such', 'please', 'available', 'copyright', 'support', 'message', 'after', 'best', 'software', 'then', 'jan', 'good', 'video', 'well', 'd', 'where', 'info', 'rights', 'public', 'books', 'high', 'school', 'through', 'm', 'each', 'links', 'she', 'review', 'years', 'order', 'very', 'privacy', 'book', 'items', 'company', 'r', 'read', 'group', 'sex', 'need', 'many', 'user', 'said', 'de', 'does', 'set', 'under', 'general', 'research', 'university', 'january', 'mail', 'full', 'map', 'reviews', 'program', 'life', 'know', 'games', 'way', 'days', 'management', 'p', 'part', 'could', 'great', 'united', 'hotel', 'real', 'f', 'item', 'international', 'center', 'ebay', 'must', 'store', 'travel', 'comments', 'made', 'development', 'report', 'off', 'member', 'details', 'line', 'terms', 'before', 'hotels', 'did', 'send', 'right', 'type', 'because', 'those', 'using', 'results', 'office', 'education', 'national', 'car', 'design', 'take', 'posted', 'internet', 'address', 'community', 'within', 'states', 'area', 'want', 'phone', 'dvd', 'shipping', 'reserved', 'subject', 'between', 'forum', 'family', 'l', 'long', 'based', 'w', 'code', 'show', 'o', 'even', 'black', 'check', 'special', 'prices', 'website', 'index', 'being', 'women', 'much', 'sign', 'file', 'link', 'open', 'today', 'technology', 'south', 'case', 'project', 'same', 'pages', 'version', 'section', 'own', 'found', 'sports', 'house', 'related', 'both']) |
{
'targets': [
{
'target_name': 'publish',
'type':'none',
'dependencies': [
'appjs'
],
'copies':[
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/',
'files': [
'<(module_root_dir)/README.md',
'<(module_root_dir)/package.json',
'<(module_root_dir)/lib/',
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/examples/',
'files': [
'<(module_root_dir)/examples/hello-world/',
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/cli/',
'files': [
'<(module_root_dir)/cli/postinstall.js',
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/',
'files': [
'<(module_root_dir)/node_modules/mime/',
]
},
{
'destination': '<(module_root_dir)/app/data/',
'files': [
'<(module_root_dir)/examples/hello-world/content/',
'<(module_root_dir)/examples/hello-world/app.js'
]
}
],
'conditions': [
['OS=="mac"', {
'copies': [
{
'destination': '<(module_root_dir)/build/Release/',
'files': [
'<(module_root_dir)/deps/cef/Release/lib.target/libcef.dylib',
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-darwin/libs/',
'files': [
'<(module_root_dir)/deps/cef/Release/lib.target/libcef.dylib',
'<(module_root_dir)/deps/cef/Release/lib.target/ffmpegsumo.so',
],
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/bindings/darwin/ia32/',
'files': [
'<(PRODUCT_DIR)/appjs.node'
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-darwin/',
'files': [
'<(module_root_dir)/data/mac/package.json',
'<(module_root_dir)/data/mac/index.js',
'<(module_root_dir)/data/mac/README.md'
],
},
{
'destination': '<(module_root_dir)/app/data/bin/Contents/',
'files': [
'<(module_root_dir)/deps/cef/Release/Resources/'
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-darwin/data/',
'files': [
'<(module_root_dir)/deps/cef/Release/Resources/chrome.pak',
]
},
{
'destination': '<(module_root_dir)/data/pak',
'files': [
'<(module_root_dir)/deps/cef/Release/Resources/chrome.pak',
]
},
{
'destination': '<(module_root_dir)/app/',
'files': [
'<(module_root_dir)/data/mac/app.sh',
]
},
{
'destination': '<(module_root_dir)/app/data/bin/',
'files': [
'<(module_root_dir)/data/mac/node-bin/node/',
]
}
]
}],
['OS=="linux"', {
'copies': [
{
'destination': '<(module_root_dir)/build/Release/',
'files': [
'<(module_root_dir)/deps/cef/Release/lib.target/libcef.so',
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/bindings/linux/<(target_arch)/',
'files': [
'<(PRODUCT_DIR)/appjs.node'
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-linux-<(target_arch)/libs/',
'files': [
'<(module_root_dir)/deps/cef/Release/lib.target/libcef.so',
],
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-linux-<(target_arch)/',
'files': [
'<(module_root_dir)/data/linux/<(target_arch)/package.json',
'<(module_root_dir)/data/linux/index.js',
'<(module_root_dir)/data/linux/README.md',
],
},
{
'destination': '<(module_root_dir)/app/',
'files': [
'<(module_root_dir)/data/linux/app.sh',
]
},
{
'destination': '<(module_root_dir)/app/data/bin/',
'files': [
'<(module_root_dir)/data/linux/<(target_arch)/node-bin/node',
'<(module_root_dir)/deps/cef/Release/lib.target/libffmpegsumo.so'
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-linux-<(target_arch)/data/',
'files': [
'<(module_root_dir)/deps/cef/Release/chrome.pak',
'<(module_root_dir)/deps/cef/Release/locales/'
]
},
{
'destination': '<(module_root_dir)/data/pak',
'files': [
'<(module_root_dir)/deps/cef/Release/chrome.pak',
'<(module_root_dir)/deps/cef/Release/locales/'
]
}
]
}],
['OS=="win"', {
'copies': [
{
'destination': '<(module_root_dir)/build/Release/',
'files': [
'<(module_root_dir)/deps/cef/Release/libcef.dll',
'<(module_root_dir)/deps/cef/Release/avcodec-54.dll',
'<(module_root_dir)/deps/cef/Release/avformat-54.dll',
'<(module_root_dir)/deps/cef/Release/avutil-51.dll',
'<(module_root_dir)/deps/cef/Release/d3dcompiler_43.dll',
'<(module_root_dir)/deps/cef/Release/d3dx9_43.dll',
'<(module_root_dir)/deps/cef/Release/icudt.dll',
'<(module_root_dir)/deps/cef/Release/libEGL.dll',
'<(module_root_dir)/deps/cef/Release/libGLESv2.dll'
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs/bindings/win32/ia32/',
'files': [
'<(PRODUCT_DIR)/appjs.node'
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-win32/libs/',
'files': [
'<(module_root_dir)/deps/cef/Release/libcef.dll',
'<(module_root_dir)/deps/cef/Release/avcodec-54.dll',
'<(module_root_dir)/deps/cef/Release/avformat-54.dll',
'<(module_root_dir)/deps/cef/Release/avutil-51.dll',
'<(module_root_dir)/deps/cef/Release/d3dcompiler_43.dll',
'<(module_root_dir)/deps/cef/Release/d3dx9_43.dll',
'<(module_root_dir)/deps/cef/Release/icudt.dll',
'<(module_root_dir)/deps/cef/Release/libEGL.dll',
'<(module_root_dir)/deps/cef/Release/libGLESv2.dll',
],
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-win32/',
'files': [
'<(module_root_dir)/data/win/package.json',
'<(module_root_dir)/data/win/index.js',
'<(module_root_dir)/data/win/README.md'
],
},
{
'destination': '<(module_root_dir)/app/',
'files': [
'<(module_root_dir)/data/win/app.exe',
]
},
{
'destination': '<(module_root_dir)/app/data/bin/',
'files': [
'<(module_root_dir)/data/win/node-bin/node.exe',
]
},
{
'destination': '<(module_root_dir)/app/data/node_modules/appjs-win32/data/',
'files': [
'<(module_root_dir)/deps/cef/Release/chrome.pak',
'<(module_root_dir)/deps/cef/Release/locales/'
]
},
{
'destination': '<(module_root_dir)/data/pak',
'files': [
'<(module_root_dir)/deps/cef/Release/chrome.pak',
'<(module_root_dir)/deps/cef/Release/locales/'
]
}
]
}]
]
},
{
'target_name': 'appjs',
'msvs_guid': 'A9D6DC71-C0DC-4549-AEB1-3B15B44E86A9',
'sources': [
'src/main.cpp',
'src/appjs.cpp',
'src/appjs_app.cpp',
'src/appjs_window.cpp',
'src/appjs_menu.cpp',
'src/appjs_status_icon.cpp',
'src/native_window/native_window.cpp',
'src/native_menu/native_menu.cpp',
'src/native_status_icon/native_status_icon.cpp',
'src/includes/cef_handler.cpp',
'src/includes/cef.cpp',
'src/includes/cef_loop.cpp',
'src/includes/cef_scheme_handler.cpp',
'src/includes/cef_sync_handler.cpp',
'src/includes/util.cpp',
],
'dependencies': [
'<(module_root_dir)/deps/cef/dll_wrapper.gyp:libcef_dll_wrapper'
],
'include_dirs': [
'src/',
'deps/cef/'
],
'cflags': [
'-fPIC',
'-Wall',
'-std=c++0x'
],
'conditions': [
['OS=="mac"', {
'sources': [
'src/native_window/native_window_mac.mm',
'src/native_menu/native_menu_mac.mm',
'src/native_status_icon/native_status_icon_mac.mm'
],
'defines': [
'__MAC__',
],
'cflags': [ '-m32' ],
'ldflags': [ '-m32' ],
'xcode_settings': {
'OTHER_CFLAGS': ['-ObjC++'],
'OTHER_LDFLAGS':['-Xlinker -rpath -Xlinker @loader_path/../../../../appjs-darwin/libs/'],
'ARCHS': [ 'i386' ]
},
'link_settings': {
'libraries': [
'<(module_root_dir)/deps/cef/Release/lib.target/libcef.dylib',
'<(module_root_dir)/build/Release/cef_dll_wrapper.node',
'-lobjc'
]
}
}],
['OS=="linux"', {
'sources': [
'src/native_window/native_window_linux.cpp',
'src/native_menu/native_menu_linux.cpp',
'src/native_status_icon/native_status_icon_linux.cpp'
],
'defines': [
'__LINUX__',
'<!@(uname -a | grep "Ubuntu" > /dev/null && echo "__UBUNTU__" || echo "__NOTUBUNTU__")'
],
'cflags': [
'<!@(pkg-config --cflags gtk+-2.0 gthread-2.0)',
],
'link_settings': {
'ldflags': [
'<!@(pkg-config --libs-only-L --libs-only-other gtk+-2.0 gthread-2.0)',
'-Wl,-R,\'$$ORIGIN/../../../../appjs-linux-<(target_arch)/libs/\'',
],
'libraries': [
'<!@(pkg-config --libs-only-l gtk+-2.0 gthread-2.0)',
'<(module_root_dir)/deps/cef/Release/lib.target/libcef.so',
'<(module_root_dir)/build/Release/obj.target/deps/cef/cef_dll_wrapper.node'
],
}
}],
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': {
'WholeProgramOptimization': 'true', # /GL, whole program optimization, needed for LTCG
'OmitFramePointers': 'true',
'EnableFunctionLevelLinking': 'true',
'EnableIntrinsicFunctions': 'true',
'RuntimeTypeInfo': 'false',
'ExceptionHandling': '1',
'AdditionalOptions': [ '/EHsc' ]
},
'VCLibrarianTool': {
'AdditionalOptions': [
'/LTCG', # link time code generation
],
},
'VCLinkerTool': {
'LinkTimeCodeGeneration': 1, # link-time code generation
'OptimizeReferences': 2, # /OPT:REF
'EnableCOMDATFolding': 2, # /OPT:ICF
'LinkIncremental': 1, # disable incremental linking
},
},
'sources': [
'src/includes/util_win.cpp',
'src/native_window/native_window_win.cpp',
'src/native_menu/native_menu_win.cpp',
'src/native_status_icon/native_status_icon_win.cpp'
],
'defines': [
'__WIN__',
'_WINSOCKAPI_',
'_UNICODE',
'UNICODE'
],
'link_settings': {
'libraries': [
'GdiPlus.lib',
'Shlwapi.lib',
'<(module_root_dir)/deps/cef/lib/Release/libcef.lib',
'<(module_root_dir)/build/Release/lib/libcef_dll_wrapper.lib'
],
},
}]
]
}
]
}
| {'targets': [{'target_name': 'publish', 'type': 'none', 'dependencies': ['appjs'], 'copies': [{'destination': '<(module_root_dir)/app/data/node_modules/appjs/', 'files': ['<(module_root_dir)/README.md', '<(module_root_dir)/package.json', '<(module_root_dir)/lib/']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs/examples/', 'files': ['<(module_root_dir)/examples/hello-world/']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs/cli/', 'files': ['<(module_root_dir)/cli/postinstall.js']}, {'destination': '<(module_root_dir)/app/data/node_modules/', 'files': ['<(module_root_dir)/node_modules/mime/']}, {'destination': '<(module_root_dir)/app/data/', 'files': ['<(module_root_dir)/examples/hello-world/content/', '<(module_root_dir)/examples/hello-world/app.js']}], 'conditions': [['OS=="mac"', {'copies': [{'destination': '<(module_root_dir)/build/Release/', 'files': ['<(module_root_dir)/deps/cef/Release/lib.target/libcef.dylib']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-darwin/libs/', 'files': ['<(module_root_dir)/deps/cef/Release/lib.target/libcef.dylib', '<(module_root_dir)/deps/cef/Release/lib.target/ffmpegsumo.so']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs/bindings/darwin/ia32/', 'files': ['<(PRODUCT_DIR)/appjs.node']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-darwin/', 'files': ['<(module_root_dir)/data/mac/package.json', '<(module_root_dir)/data/mac/index.js', '<(module_root_dir)/data/mac/README.md']}, {'destination': '<(module_root_dir)/app/data/bin/Contents/', 'files': ['<(module_root_dir)/deps/cef/Release/Resources/']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-darwin/data/', 'files': ['<(module_root_dir)/deps/cef/Release/Resources/chrome.pak']}, {'destination': '<(module_root_dir)/data/pak', 'files': ['<(module_root_dir)/deps/cef/Release/Resources/chrome.pak']}, {'destination': '<(module_root_dir)/app/', 'files': ['<(module_root_dir)/data/mac/app.sh']}, {'destination': '<(module_root_dir)/app/data/bin/', 'files': ['<(module_root_dir)/data/mac/node-bin/node/']}]}], ['OS=="linux"', {'copies': [{'destination': '<(module_root_dir)/build/Release/', 'files': ['<(module_root_dir)/deps/cef/Release/lib.target/libcef.so']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs/bindings/linux/<(target_arch)/', 'files': ['<(PRODUCT_DIR)/appjs.node']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-linux-<(target_arch)/libs/', 'files': ['<(module_root_dir)/deps/cef/Release/lib.target/libcef.so']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-linux-<(target_arch)/', 'files': ['<(module_root_dir)/data/linux/<(target_arch)/package.json', '<(module_root_dir)/data/linux/index.js', '<(module_root_dir)/data/linux/README.md']}, {'destination': '<(module_root_dir)/app/', 'files': ['<(module_root_dir)/data/linux/app.sh']}, {'destination': '<(module_root_dir)/app/data/bin/', 'files': ['<(module_root_dir)/data/linux/<(target_arch)/node-bin/node', '<(module_root_dir)/deps/cef/Release/lib.target/libffmpegsumo.so']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-linux-<(target_arch)/data/', 'files': ['<(module_root_dir)/deps/cef/Release/chrome.pak', '<(module_root_dir)/deps/cef/Release/locales/']}, {'destination': '<(module_root_dir)/data/pak', 'files': ['<(module_root_dir)/deps/cef/Release/chrome.pak', '<(module_root_dir)/deps/cef/Release/locales/']}]}], ['OS=="win"', {'copies': [{'destination': '<(module_root_dir)/build/Release/', 'files': ['<(module_root_dir)/deps/cef/Release/libcef.dll', '<(module_root_dir)/deps/cef/Release/avcodec-54.dll', '<(module_root_dir)/deps/cef/Release/avformat-54.dll', '<(module_root_dir)/deps/cef/Release/avutil-51.dll', '<(module_root_dir)/deps/cef/Release/d3dcompiler_43.dll', '<(module_root_dir)/deps/cef/Release/d3dx9_43.dll', '<(module_root_dir)/deps/cef/Release/icudt.dll', '<(module_root_dir)/deps/cef/Release/libEGL.dll', '<(module_root_dir)/deps/cef/Release/libGLESv2.dll']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs/bindings/win32/ia32/', 'files': ['<(PRODUCT_DIR)/appjs.node']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-win32/libs/', 'files': ['<(module_root_dir)/deps/cef/Release/libcef.dll', '<(module_root_dir)/deps/cef/Release/avcodec-54.dll', '<(module_root_dir)/deps/cef/Release/avformat-54.dll', '<(module_root_dir)/deps/cef/Release/avutil-51.dll', '<(module_root_dir)/deps/cef/Release/d3dcompiler_43.dll', '<(module_root_dir)/deps/cef/Release/d3dx9_43.dll', '<(module_root_dir)/deps/cef/Release/icudt.dll', '<(module_root_dir)/deps/cef/Release/libEGL.dll', '<(module_root_dir)/deps/cef/Release/libGLESv2.dll']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-win32/', 'files': ['<(module_root_dir)/data/win/package.json', '<(module_root_dir)/data/win/index.js', '<(module_root_dir)/data/win/README.md']}, {'destination': '<(module_root_dir)/app/', 'files': ['<(module_root_dir)/data/win/app.exe']}, {'destination': '<(module_root_dir)/app/data/bin/', 'files': ['<(module_root_dir)/data/win/node-bin/node.exe']}, {'destination': '<(module_root_dir)/app/data/node_modules/appjs-win32/data/', 'files': ['<(module_root_dir)/deps/cef/Release/chrome.pak', '<(module_root_dir)/deps/cef/Release/locales/']}, {'destination': '<(module_root_dir)/data/pak', 'files': ['<(module_root_dir)/deps/cef/Release/chrome.pak', '<(module_root_dir)/deps/cef/Release/locales/']}]}]]}, {'target_name': 'appjs', 'msvs_guid': 'A9D6DC71-C0DC-4549-AEB1-3B15B44E86A9', 'sources': ['src/main.cpp', 'src/appjs.cpp', 'src/appjs_app.cpp', 'src/appjs_window.cpp', 'src/appjs_menu.cpp', 'src/appjs_status_icon.cpp', 'src/native_window/native_window.cpp', 'src/native_menu/native_menu.cpp', 'src/native_status_icon/native_status_icon.cpp', 'src/includes/cef_handler.cpp', 'src/includes/cef.cpp', 'src/includes/cef_loop.cpp', 'src/includes/cef_scheme_handler.cpp', 'src/includes/cef_sync_handler.cpp', 'src/includes/util.cpp'], 'dependencies': ['<(module_root_dir)/deps/cef/dll_wrapper.gyp:libcef_dll_wrapper'], 'include_dirs': ['src/', 'deps/cef/'], 'cflags': ['-fPIC', '-Wall', '-std=c++0x'], 'conditions': [['OS=="mac"', {'sources': ['src/native_window/native_window_mac.mm', 'src/native_menu/native_menu_mac.mm', 'src/native_status_icon/native_status_icon_mac.mm'], 'defines': ['__MAC__'], 'cflags': ['-m32'], 'ldflags': ['-m32'], 'xcode_settings': {'OTHER_CFLAGS': ['-ObjC++'], 'OTHER_LDFLAGS': ['-Xlinker -rpath -Xlinker @loader_path/../../../../appjs-darwin/libs/'], 'ARCHS': ['i386']}, 'link_settings': {'libraries': ['<(module_root_dir)/deps/cef/Release/lib.target/libcef.dylib', '<(module_root_dir)/build/Release/cef_dll_wrapper.node', '-lobjc']}}], ['OS=="linux"', {'sources': ['src/native_window/native_window_linux.cpp', 'src/native_menu/native_menu_linux.cpp', 'src/native_status_icon/native_status_icon_linux.cpp'], 'defines': ['__LINUX__', '<!@(uname -a | grep "Ubuntu" > /dev/null && echo "__UBUNTU__" || echo "__NOTUBUNTU__")'], 'cflags': ['<!@(pkg-config --cflags gtk+-2.0 gthread-2.0)'], 'link_settings': {'ldflags': ['<!@(pkg-config --libs-only-L --libs-only-other gtk+-2.0 gthread-2.0)', "-Wl,-R,'$$ORIGIN/../../../../appjs-linux-<(target_arch)/libs/'"], 'libraries': ['<!@(pkg-config --libs-only-l gtk+-2.0 gthread-2.0)', '<(module_root_dir)/deps/cef/Release/lib.target/libcef.so', '<(module_root_dir)/build/Release/obj.target/deps/cef/cef_dll_wrapper.node']}}], ['OS=="win"', {'msvs_settings': {'VCCLCompilerTool': {'WholeProgramOptimization': 'true', 'OmitFramePointers': 'true', 'EnableFunctionLevelLinking': 'true', 'EnableIntrinsicFunctions': 'true', 'RuntimeTypeInfo': 'false', 'ExceptionHandling': '1', 'AdditionalOptions': ['/EHsc']}, 'VCLibrarianTool': {'AdditionalOptions': ['/LTCG']}, 'VCLinkerTool': {'LinkTimeCodeGeneration': 1, 'OptimizeReferences': 2, 'EnableCOMDATFolding': 2, 'LinkIncremental': 1}}, 'sources': ['src/includes/util_win.cpp', 'src/native_window/native_window_win.cpp', 'src/native_menu/native_menu_win.cpp', 'src/native_status_icon/native_status_icon_win.cpp'], 'defines': ['__WIN__', '_WINSOCKAPI_', '_UNICODE', 'UNICODE'], 'link_settings': {'libraries': ['GdiPlus.lib', 'Shlwapi.lib', '<(module_root_dir)/deps/cef/lib/Release/libcef.lib', '<(module_root_dir)/build/Release/lib/libcef_dll_wrapper.lib']}}]]}]} |
n, m = map(int, input().split())
ruins = [list(map(int, input().split())) for _ in range(n)]
imos = [0] * (m+1)
sum_s = 0
for i in range(n):
l, r, s = ruins[i]
l -= 1
imos[l] += s
imos[r] -= s
sum_s += s
for i in range(m):
imos[i+1] += imos[i]
print(sum_s - min(imos[:-1]))
| (n, m) = map(int, input().split())
ruins = [list(map(int, input().split())) for _ in range(n)]
imos = [0] * (m + 1)
sum_s = 0
for i in range(n):
(l, r, s) = ruins[i]
l -= 1
imos[l] += s
imos[r] -= s
sum_s += s
for i in range(m):
imos[i + 1] += imos[i]
print(sum_s - min(imos[:-1])) |
input = """
i(0). i(1).
a(X) | -a(X) :- i(X).
ok :- 0 < #count{X:a(X)}< 2.
:- not ok.
"""
output = """
i(0). i(1).
a(X) | -a(X) :- i(X).
ok :- 0 < #count{X:a(X)}< 2.
:- not ok.
"""
| input = '\ni(0). i(1).\na(X) | -a(X) :- i(X).\nok :- 0 < #count{X:a(X)}< 2.\n:- not ok.\n'
output = '\ni(0). i(1).\na(X) | -a(X) :- i(X).\nok :- 0 < #count{X:a(X)}< 2.\n:- not ok.\n' |
def check(s, t):
v = 0
for i in range(len(t)):
if t[i] == s[v]:
v += 1
if v == len(s):
return "Yes"
return "No"
while True:
try:
s, t = input().split()
ans = check(s, t)
print(ans)
except:
break
| def check(s, t):
v = 0
for i in range(len(t)):
if t[i] == s[v]:
v += 1
if v == len(s):
return 'Yes'
return 'No'
while True:
try:
(s, t) = input().split()
ans = check(s, t)
print(ans)
except:
break |
class _descriptor(object):
def __get__(self, *_):
raise RuntimeError("more like funtime error")
class Methods(object):
ok_method = "ok"
err_method = _descriptor()
| class _Descriptor(object):
def __get__(self, *_):
raise runtime_error('more like funtime error')
class Methods(object):
ok_method = 'ok'
err_method = _descriptor() |
'''
+Build Your Dream Python Project Discord Team
Invite: https://dsc.gg/python_team
19 Feb 2021
@alexandros answer to @Subham
https://discord.com/channels/794684213697052712/794684213697052718/812231193213796362
Sublist Yielder
'''
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst):
for sublst in lst:
yield from sublst
yield '\n'
for item in f(lst):
end_char = '' if item == '\n' else ' '
print(item, end = end_char)
# Output
'''
1 3 4
2 5 7
'''
| """
+Build Your Dream Python Project Discord Team
Invite: https://dsc.gg/python_team
19 Feb 2021
@alexandros answer to @Subham
https://discord.com/channels/794684213697052712/794684213697052718/812231193213796362
Sublist Yielder
"""
lst = [[1, 3, 4], [2, 5, 7]]
def f(lst):
for sublst in lst:
yield from sublst
yield '\n'
for item in f(lst):
end_char = '' if item == '\n' else ' '
print(item, end=end_char)
'\n1 3 4 \n2 5 7 \n' |
#----------* CHALLENGE 35 *----------
#Ask the user to enter their name and then display their name three times.
name = input("Enter your name: ")
for i in range (1,4):
print(name+" ") | name = input('Enter your name: ')
for i in range(1, 4):
print(name + ' ') |
edibles = ["ham", "spam","eggs","nuts"]
for food in edibles:
if food == "spams":
print("No more spam please!")
break
print("Great, delicious " + food)
else:
print("I am so glad: No " + food +"!")
print("Finally, I finished stuffing myself") | edibles = ['ham', 'spam', 'eggs', 'nuts']
for food in edibles:
if food == 'spams':
print('No more spam please!')
break
print('Great, delicious ' + food)
else:
print('I am so glad: No ' + food + '!')
print('Finally, I finished stuffing myself') |
domain = 'mycompany.local'
user = 'automation@vsphere.local'
pwd = 'somepassword'
| domain = 'mycompany.local'
user = 'automation@vsphere.local'
pwd = 'somepassword' |
game = "Hello world"
#print(id(game))
def game_board(player=0, row=0, col=0, just_display=False):
game = "Change !"
#print(id(game))
print(game)
print(game)
game_board()
print(game)
#print(id(game))
| game = 'Hello world'
def game_board(player=0, row=0, col=0, just_display=False):
game = 'Change !'
print(game)
print(game)
game_board()
print(game) |
def groupnames(name_iterable):
name_dict = {}
for name in name_iterable:
key = _groupkeyfunc(name)
name_dict.setdefault(key, []).append(name)
for k, v in name_dict.iteritems():
aux = [(_sortkeyfunc(name), name) for name in v]
aux.sort()
name_dict[k] = tuple([ n for __, n in aux ])
return name_dict
| def groupnames(name_iterable):
name_dict = {}
for name in name_iterable:
key = _groupkeyfunc(name)
name_dict.setdefault(key, []).append(name)
for (k, v) in name_dict.iteritems():
aux = [(_sortkeyfunc(name), name) for name in v]
aux.sort()
name_dict[k] = tuple([n for (__, n) in aux])
return name_dict |
class reverse_iter:
def __init__(self, iterable) -> None:
self.iterable = iterable
self.start = len(iterable)
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start > 0:
self.start -= 1
return self.iterable[self.start]
raise StopIteration()
if __name__ == '__main__':
reversed_list = reverse_iter([1, 2, 3, 4])
for item in reversed_list:
print(item)
| class Reverse_Iter:
def __init__(self, iterable) -> None:
self.iterable = iterable
self.start = len(iterable)
def __iter__(self) -> iter:
return self
def __next__(self) -> int:
if self.start > 0:
self.start -= 1
return self.iterable[self.start]
raise stop_iteration()
if __name__ == '__main__':
reversed_list = reverse_iter([1, 2, 3, 4])
for item in reversed_list:
print(item) |
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def insertAtLast(self, data):
node = Node(data)
if self.head == None:
self.head = node
return
currPointer = self.head
while currPointer.next != None:
currPointer = currPointer.next
currPointer.next = node
def deleteNode(self, dataKey):
prevNode = None
currNode = self.head
# if head element is to be deleted
if currNode.data == dataKey:
currNode = currNode.next
self.head = currNode
return
while currNode:
if currNode.data == dataKey:
prevNode.next = currNode.next
return
prevNode = currNode
currNode = currNode.next
print('Node with data key not found')
def __str__(self):
result = ''
currNode = self.head
while currNode:
if currNode.next != None:
result += str(currNode.data) + ' -> '
else:
result += str(currNode.data)
currNode = currNode.next
return result
if __name__ == "__main__":
linkedList = LinkedList()
for i in range(10):
linkedList.insertAtLast(i)
print(linkedList)
# Deletion from head
linkedList.deleteNode(0)
print(linkedList)
# Deletion from mid
linkedList.deleteNode(5)
print(linkedList)
# deletion from last
linkedList.deleteNode(9)
print(linkedList) | class Node:
def __init__(self, data):
self.data = data
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def insert_at_last(self, data):
node = node(data)
if self.head == None:
self.head = node
return
curr_pointer = self.head
while currPointer.next != None:
curr_pointer = currPointer.next
currPointer.next = node
def delete_node(self, dataKey):
prev_node = None
curr_node = self.head
if currNode.data == dataKey:
curr_node = currNode.next
self.head = currNode
return
while currNode:
if currNode.data == dataKey:
prevNode.next = currNode.next
return
prev_node = currNode
curr_node = currNode.next
print('Node with data key not found')
def __str__(self):
result = ''
curr_node = self.head
while currNode:
if currNode.next != None:
result += str(currNode.data) + ' -> '
else:
result += str(currNode.data)
curr_node = currNode.next
return result
if __name__ == '__main__':
linked_list = linked_list()
for i in range(10):
linkedList.insertAtLast(i)
print(linkedList)
linkedList.deleteNode(0)
print(linkedList)
linkedList.deleteNode(5)
print(linkedList)
linkedList.deleteNode(9)
print(linkedList) |
# __init__.py
"""[Module pys.conf]
Parse .ini configuration of cmd -> build and cmd -> expand
"""
__all__ = ['mconf', 'mgroup']
| """[Module pys.conf]
Parse .ini configuration of cmd -> build and cmd -> expand
"""
__all__ = ['mconf', 'mgroup'] |
# 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.incr = 0
def convertBST(self, root: TreeNode) -> TreeNode:
def dfs(node):
if not node:
return 0
self.convertBST(node.right)
self.incr += node.val
node.val = self.incr
self.convertBST(node.left)
dfs(root)
return root
t = TreeNode(5)
t.left = TreeNode(2)
t.right = TreeNode(13)
slu = Solution()
print(slu.convertBST(t))
| class Treenode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def __init__(self):
self.incr = 0
def convert_bst(self, root: TreeNode) -> TreeNode:
def dfs(node):
if not node:
return 0
self.convertBST(node.right)
self.incr += node.val
node.val = self.incr
self.convertBST(node.left)
dfs(root)
return root
t = tree_node(5)
t.left = tree_node(2)
t.right = tree_node(13)
slu = solution()
print(slu.convertBST(t)) |
#import necessary data
df = pd.read_csv('~/lstm_test/input/nu_public_rep.csv', sep=';',
parse_dates={'dt' : ['Date', 'Time']}, infer_datetime_format=True,
low_memory=False, na_values=['nan','?'], index_col='dt')
#fill nan with the means of the columns to handle missing databases
droping_list_all=[]
for j in range(0,7):
if not df.iloc[:, j].notnull().all():
droping_list_all.append(j)
#print(df.iloc[:,j].unique())
droping_list_all
#This small loop will replace any missing vlaues with means of columns (study this!!)
for j in range(0,7):
df.iloc[:,j]=df.iloc[:,j].fillna(df.iloc[:,j].mean())
#Get sum of missing calues - sanity check (should be zero)
df.isnull().sum()
| df = pd.read_csv('~/lstm_test/input/nu_public_rep.csv', sep=';', parse_dates={'dt': ['Date', 'Time']}, infer_datetime_format=True, low_memory=False, na_values=['nan', '?'], index_col='dt')
droping_list_all = []
for j in range(0, 7):
if not df.iloc[:, j].notnull().all():
droping_list_all.append(j)
droping_list_all
for j in range(0, 7):
df.iloc[:, j] = df.iloc[:, j].fillna(df.iloc[:, j].mean())
df.isnull().sum() |
#!/usr/bin/env python
# coding: utf8
def writeResults(links, outfile):
fw = open(outfile, "w")
for link in links:
fw.write(link)
| def write_results(links, outfile):
fw = open(outfile, 'w')
for link in links:
fw.write(link) |
i = get_safe('id')
username = ""
if i != 0:
username = get('username')
username = escape_string(username)
query = 'some query'
it = execute(query + username)
| i = get_safe('id')
username = ''
if i != 0:
username = get('username')
username = escape_string(username)
query = 'some query'
it = execute(query + username) |
'''
file:except.py
exceptions for piclock
'''
class NoConfigError(Exception):
'''
No Config Error Exception
'''
class CharacterNotFound(Exception):
'''
Character not found exception
'''
class MatrixCharError(Exception):
'''
Matrix Character Error
'''
class NoMqttConfigSection(Exception):
'''
No MQTT config Section Error
'''
class NoMqttServerSetting(Exception):
'''
No MQTT server settings in config file
'''
class ColorClassError(Exception):
'''
Color Class error
'''
class FontError(Exception):
'''
Font Error Class
'''
class TemperaturReadError(Exception):
'''
Read Error on temperatur file
'''
| """
file:except.py
exceptions for piclock
"""
class Noconfigerror(Exception):
"""
No Config Error Exception
"""
class Characternotfound(Exception):
"""
Character not found exception
"""
class Matrixcharerror(Exception):
"""
Matrix Character Error
"""
class Nomqttconfigsection(Exception):
"""
No MQTT config Section Error
"""
class Nomqttserversetting(Exception):
"""
No MQTT server settings in config file
"""
class Colorclasserror(Exception):
"""
Color Class error
"""
class Fonterror(Exception):
"""
Font Error Class
"""
class Temperaturreaderror(Exception):
"""
Read Error on temperatur file
""" |
# Objectives
#
# In this stage, you should write a program that:
#
# Reads matrix A A A from the input.
# Reads matrix B B B from the input.
# Outputs their sum if it is possible to add them. Otherwise, it should output the ERROR message.
#
# Each matrix in the input is given in the following way: the first line contains the number of rows
# nnn and the number of columns mmm. Then nnn lines follow, each containing mmm integers
# representing one row of the matrix.
#
# Output the result in the same way but don't print the dimensions of the matrix.
def same_dimensions(n_rows_a, n_columns_a, n_rows_b, n_columns_b):
return n_rows_a == n_rows_b and n_columns_a == n_columns_b
def addition(mat_a, mat_b, n_rows, n_columns):
return [[str(mat_a[i][j] + mat_b[i][j]) for j in range(n_columns)] for i in range(n_rows)]
def print_matrix(mat):
for row in mat:
print(*row)
def add_matrices():
a, b = list(map(int, input().split()))
mat_a = [list(map(int, input().split())) for _ in range(a)]
c, d = list(map(int, input().split()))
mat_b = [list(map(int, input().split())) for _ in range(c)]
if not same_dimensions(a, b, c, d):
print('ERROR')
else:
mat_sum = addition(mat_a, mat_b, a, b)
for row in mat_sum:
print(*row)
if __name__ == '__main__':
add_matrices()
| def same_dimensions(n_rows_a, n_columns_a, n_rows_b, n_columns_b):
return n_rows_a == n_rows_b and n_columns_a == n_columns_b
def addition(mat_a, mat_b, n_rows, n_columns):
return [[str(mat_a[i][j] + mat_b[i][j]) for j in range(n_columns)] for i in range(n_rows)]
def print_matrix(mat):
for row in mat:
print(*row)
def add_matrices():
(a, b) = list(map(int, input().split()))
mat_a = [list(map(int, input().split())) for _ in range(a)]
(c, d) = list(map(int, input().split()))
mat_b = [list(map(int, input().split())) for _ in range(c)]
if not same_dimensions(a, b, c, d):
print('ERROR')
else:
mat_sum = addition(mat_a, mat_b, a, b)
for row in mat_sum:
print(*row)
if __name__ == '__main__':
add_matrices() |
"""Zorro's dependency injection framework
Usage
=====
Declare a class' dependencies::
@has_dependencies
class Hello(object):
world = dependency(World, 'universe')
You must decorate class with ``@has_dependencies``. All dependencies has a
type(class), which is ``World`` in this case, and a name, which is ``universe``
in this case. This is for having multiple similar dependencies.
.. note::
Name of dependency is unique among all services in single dependency
injector and not tied to particular type. This is done to easier support
subclassing of dependencies (and you can also register subclass with abc
instead of subclassing directly)
Then at some initialisation code you create dependency injector, and set
apropriate services::
inj = DependencyInjector()
inj['universe'] = World()
Now you can create ``Hello`` instances and inject dependencies to them::
hello = inj.inject(Hello())
assert hello.world is inj['universe']
And you can propagate dependencies starting from existing instances::
h2 = di(hello).inject(Hello())
assert h2.world is hello.world
"""
def has_dependencies(cls):
"""Class decorator that declares dependencies"""
deps = {}
for i in dir(cls):
val = getattr(cls, i)
if isinstance(val, dependency):
deps[i] = val
cls.__zorro_depends__ = deps
return cls
class dependency:
"""Property that represents single dependency"""
def __init__(self, typ, name):
self.type = typ
self.name = name
def __get__(self, inst, owner):
if inst is None:
return self
raise RuntimeError("Dependency {!r} is not configured".format(self))
def __repr__(self):
return "<dependency {!r}:{!r}>".format(self.type, self.name)
class DependencyInjector(object):
"""Main dependency injector class
Set all dependencies with::
>>> inj = DependencyInjector()
>>> inj['name'] = value
>>> obj = inj.inject(DependentClass())
Propagate dependencies with::
>>> di(obj).inject(NewObject())
"""
def __init__(self):
self._provides = {}
def inject(self, inst, **renames):
"""Injects dependencies and propagates dependency injector"""
if renames:
di = self.clone(**renames)
else:
di = self
pro = di._provides
inst.__zorro_di__ = di
deps = getattr(inst, '__zorro_depends__', None)
if deps:
for attr, dep in deps.items():
val = pro[dep.name]
if not isinstance(val, dep.type):
raise RuntimeError("Wrong provider for {!r}".format(val))
setattr(inst, attr, val)
meth = getattr(inst, '__zorro_di_done__', None)
if meth is not None:
meth()
return inst
def inject_subset(self, inst, *names, **renames):
"""Injects only specified dependencies, and does not propagate others
"""
# TODO(tailhook) may be optimize if names == _provides.keys()
di = self.__class__()
mypro = self._provides
pro = di._provides
for name in names:
pro[name] = mypro[name]
for name, alias in renames.items():
pro[name] = mypro[alias]
inst.__zorro_di__ = di
deps = getattr(inst, '__zorro_depends__', None)
if deps:
for attr, dep in deps.items():
if dep.name not in pro:
continue
val = pro[dep.name]
if not isinstance(val, dep.type):
raise RuntimeError("Wrong provider for {!r}".format(val))
setattr(inst, attr, val)
meth = getattr(inst, '__zorro_di_done__', None)
if meth is not None:
meth()
return inst
def __setitem__(self, name, value):
if name in self._provides:
raise RuntimeError("Two providers for {!r}".format(name))
self._provides[name] = value
def __getitem__(self, name):
return self._provides[name]
def __contains__(self, name):
return name in self._provides
def clone(self, **renames):
di = self.__class__()
mypro = self._provides
pro = di._provides
pro.update(mypro)
for name, alias in renames.items():
pro[name] = mypro[alias]
return di
def dependencies(cls):
"""Returns dict of dependencies of a class declared with
``@has_dependencies``
"""
return getattr(cls, '__zorro_depends__', {})
def di(obj):
"""Returns dependency injector used to construct class
This instance is useful to propagate dependencies
"""
try:
return obj.__zorro_di__
except AttributeError:
raise RuntimeError("No dependency injector found")
| """Zorro's dependency injection framework
Usage
=====
Declare a class' dependencies::
@has_dependencies
class Hello(object):
world = dependency(World, 'universe')
You must decorate class with ``@has_dependencies``. All dependencies has a
type(class), which is ``World`` in this case, and a name, which is ``universe``
in this case. This is for having multiple similar dependencies.
.. note::
Name of dependency is unique among all services in single dependency
injector and not tied to particular type. This is done to easier support
subclassing of dependencies (and you can also register subclass with abc
instead of subclassing directly)
Then at some initialisation code you create dependency injector, and set
apropriate services::
inj = DependencyInjector()
inj['universe'] = World()
Now you can create ``Hello`` instances and inject dependencies to them::
hello = inj.inject(Hello())
assert hello.world is inj['universe']
And you can propagate dependencies starting from existing instances::
h2 = di(hello).inject(Hello())
assert h2.world is hello.world
"""
def has_dependencies(cls):
"""Class decorator that declares dependencies"""
deps = {}
for i in dir(cls):
val = getattr(cls, i)
if isinstance(val, dependency):
deps[i] = val
cls.__zorro_depends__ = deps
return cls
class Dependency:
"""Property that represents single dependency"""
def __init__(self, typ, name):
self.type = typ
self.name = name
def __get__(self, inst, owner):
if inst is None:
return self
raise runtime_error('Dependency {!r} is not configured'.format(self))
def __repr__(self):
return '<dependency {!r}:{!r}>'.format(self.type, self.name)
class Dependencyinjector(object):
"""Main dependency injector class
Set all dependencies with::
>>> inj = DependencyInjector()
>>> inj['name'] = value
>>> obj = inj.inject(DependentClass())
Propagate dependencies with::
>>> di(obj).inject(NewObject())
"""
def __init__(self):
self._provides = {}
def inject(self, inst, **renames):
"""Injects dependencies and propagates dependency injector"""
if renames:
di = self.clone(**renames)
else:
di = self
pro = di._provides
inst.__zorro_di__ = di
deps = getattr(inst, '__zorro_depends__', None)
if deps:
for (attr, dep) in deps.items():
val = pro[dep.name]
if not isinstance(val, dep.type):
raise runtime_error('Wrong provider for {!r}'.format(val))
setattr(inst, attr, val)
meth = getattr(inst, '__zorro_di_done__', None)
if meth is not None:
meth()
return inst
def inject_subset(self, inst, *names, **renames):
"""Injects only specified dependencies, and does not propagate others
"""
di = self.__class__()
mypro = self._provides
pro = di._provides
for name in names:
pro[name] = mypro[name]
for (name, alias) in renames.items():
pro[name] = mypro[alias]
inst.__zorro_di__ = di
deps = getattr(inst, '__zorro_depends__', None)
if deps:
for (attr, dep) in deps.items():
if dep.name not in pro:
continue
val = pro[dep.name]
if not isinstance(val, dep.type):
raise runtime_error('Wrong provider for {!r}'.format(val))
setattr(inst, attr, val)
meth = getattr(inst, '__zorro_di_done__', None)
if meth is not None:
meth()
return inst
def __setitem__(self, name, value):
if name in self._provides:
raise runtime_error('Two providers for {!r}'.format(name))
self._provides[name] = value
def __getitem__(self, name):
return self._provides[name]
def __contains__(self, name):
return name in self._provides
def clone(self, **renames):
di = self.__class__()
mypro = self._provides
pro = di._provides
pro.update(mypro)
for (name, alias) in renames.items():
pro[name] = mypro[alias]
return di
def dependencies(cls):
"""Returns dict of dependencies of a class declared with
``@has_dependencies``
"""
return getattr(cls, '__zorro_depends__', {})
def di(obj):
"""Returns dependency injector used to construct class
This instance is useful to propagate dependencies
"""
try:
return obj.__zorro_di__
except AttributeError:
raise runtime_error('No dependency injector found') |
rows = 9
for i in range(rows):
# nested loop
for j in range(i):
# display number
print(i, end=' ')
# new line after each row
print('')
| rows = 9
for i in range(rows):
for j in range(i):
print(i, end=' ')
print('') |
"""
_
__ _ ___ ___ __ _| | ___
/ _` |/ _ \ / _ \ / _` | |/ _ \
| (_| | (_) | (_) | (_| | | __/
\__, |\___/ \___/ \__, |_|\___|
|___/ |___/
Author: Aaditya Chapagain
version: 1.0.1
description: scripts which will make google API's easy in python.
""" | """
_
__ _ ___ ___ __ _| | ___
/ _` |/ _ \\ / _ \\ / _` | |/ _ | (_| | (_) | (_) | (_| | | __/
\\__, |\\___/ \\___/ \\__, |_|\\___|
|___/ |___/
Author: Aaditya Chapagain
version: 1.0.1
description: scripts which will make google API's easy in python.
""" |
# OpenWeatherMap API Key
weather_api_key = "ea45174aae3e4fc5de1af5d14f74cd81"
# Google API Key
g_key = "AIzaSyCiyVKYg3FYX0fAR2S2RGR1m-kUN947W9s" | weather_api_key = 'ea45174aae3e4fc5de1af5d14f74cd81'
g_key = 'AIzaSyCiyVKYg3FYX0fAR2S2RGR1m-kUN947W9s' |
def editDistance(str1, str2, m, n, ci=1,crm=1,crp=1):
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif str1[i-1] == str2[j-1]:
dp[i][j] = dp[i-1][j-1]
else:
dp[i][j] = min((dp[i][j-1] + ci), # Insert
(dp[i-1][j] + crm), # Remove
(dp[i-1][j-1] + crp)) # Replace
return dp[m][n] ##or dp[-1][-1]
str1 = "MARCH"
str2 = "CART"
cost_insert = 1
cost_remove = 1
cost_replace = 1
ed=editDistance(str1, str2, len(str1), len(str2), cost_insert,cost_remove,cost_replace)
print('Minimum Edit Distance:',ed)
## OUTPUT:
'''
Minimum Edit Distance: 3
''' | def edit_distance(str1, str2, m, n, ci=1, crm=1, crp=1):
dp = [[0 for i in range(n + 1)] for j in range(m + 1)]
for i in range(m + 1):
for j in range(n + 1):
if i == 0:
dp[i][j] = j
elif j == 0:
dp[i][j] = i
elif str1[i - 1] == str2[j - 1]:
dp[i][j] = dp[i - 1][j - 1]
else:
dp[i][j] = min(dp[i][j - 1] + ci, dp[i - 1][j] + crm, dp[i - 1][j - 1] + crp)
return dp[m][n]
str1 = 'MARCH'
str2 = 'CART'
cost_insert = 1
cost_remove = 1
cost_replace = 1
ed = edit_distance(str1, str2, len(str1), len(str2), cost_insert, cost_remove, cost_replace)
print('Minimum Edit Distance:', ed)
'\nMinimum Edit Distance: 3\n\n' |
"""
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
2,3,4,-1,1 => 2
1,2,3,0 => 3
"""
def func(arr):
A = set(arr)
A1 = set([i for i in range(min(A), max(A)+1)])
diff = A1.difference(A)
if len(diff) == 0:
return max(A)+1
for i in diff:
if i > 0:
return i
A = [3, 4, -1, 1]
# A = [1, 2, 0]
print(func(A)) | """
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
2,3,4,-1,1 => 2
1,2,3,0 => 3
"""
def func(arr):
a = set(arr)
a1 = set([i for i in range(min(A), max(A) + 1)])
diff = A1.difference(A)
if len(diff) == 0:
return max(A) + 1
for i in diff:
if i > 0:
return i
a = [3, 4, -1, 1]
print(func(A)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def funcion_generadora_print():
try:
print("GENERADOR: Se va a generar un PRIMER dato")
yield "valorGenerado1"
print("GENERADOR: Se va a generar un SEGUNDO dato")
yield "valorGenerado2"
print("GENERADOR: Se va a generar un TERCER dato")
yield "valorGenerado3"
finally:
print("GENERADOR: Terminando y limpiando")
if __name__ == "__main__":
generador = funcion_generadora_print()
for elemento in generador:
print(elemento)
| def funcion_generadora_print():
try:
print('GENERADOR: Se va a generar un PRIMER dato')
yield 'valorGenerado1'
print('GENERADOR: Se va a generar un SEGUNDO dato')
yield 'valorGenerado2'
print('GENERADOR: Se va a generar un TERCER dato')
yield 'valorGenerado3'
finally:
print('GENERADOR: Terminando y limpiando')
if __name__ == '__main__':
generador = funcion_generadora_print()
for elemento in generador:
print(elemento) |
"""Provides classes for connecting to and controlling real and mock Spectrum digitiser cards and StarHubs."""
# Christian Baker, King's College London
# Copyright (c) 2021 School of Biomedical Engineering & Imaging Sciences, King's College London
# Licensed under the MIT. You may obtain a copy at https://opensource.org/licenses/MIT.
| """Provides classes for connecting to and controlling real and mock Spectrum digitiser cards and StarHubs.""" |
file_input="dump.seq_e10.mci.I12"
num=1
output=open('assign_cluster_num.out','w')
for i in open(file_input):
i=i.replace('\n','')
o=i.split()
for j in o:
output.write(j+'\t'+str(num)+'\n')
num+=1
output.close()
| file_input = 'dump.seq_e10.mci.I12'
num = 1
output = open('assign_cluster_num.out', 'w')
for i in open(file_input):
i = i.replace('\n', '')
o = i.split()
for j in o:
output.write(j + '\t' + str(num) + '\n')
num += 1
output.close() |
t=int(input('Tabuada do : '))
r1 = t * 1
r2 = t * 2
r3 = t * 3
r4 = t * 4
r5 = t * 5
r6 = t * 6
r7 = t * 7
r8 = t * 8
r9 = t * 9
r10 = t * 10
print("RESUlTADO\n------------------------")
print('{} x 1 = {}'.format(t,r1))
print('{} x 2 = {}'.format(t,r2))
print('{} x 3 = {}'.format(t,r3))
print('{} x 4 = {}'.format(t,r4))
print('{} x 5 = {}'.format(t,r5))
print('{} x 6 = {}'.format(t,r6))
print('{} x 7 = {}'.format(t,r7))
print('{} x 8 = {}'.format(t,r8))
print('{} x 9 = {}'.format(t,r9))
print('{} x 10 = {}'.format(t,r10))
#Gabarito
print("-"*20)
print('{} x {:2} = {}'.format(t, 1, t*1))
print('{} x {:2} = {}'.format(t, 2, t*2))
print('{} x {:2} = {}'.format(t, 3, t*3))
print('{} x {:2} = {}'.format(t, 4, t*4))
print('{} x {:2} = {}'.format(t, 5, t*5))
print('{} x {:2} = {}'.format(t, 6, t*6))
print('{} x {:2} = {}'.format(t, 7, t*7))
print('{} x {:2} = {}'.format(t, 8, t*8))
print('{} x {:2} = {}'.format(t, 9, t*9))
print('{} x {:2} = {}'.format(t, 10, t*10))
print("-"*20) | t = int(input('Tabuada do : '))
r1 = t * 1
r2 = t * 2
r3 = t * 3
r4 = t * 4
r5 = t * 5
r6 = t * 6
r7 = t * 7
r8 = t * 8
r9 = t * 9
r10 = t * 10
print('RESUlTADO\n------------------------')
print('{} x 1 = {}'.format(t, r1))
print('{} x 2 = {}'.format(t, r2))
print('{} x 3 = {}'.format(t, r3))
print('{} x 4 = {}'.format(t, r4))
print('{} x 5 = {}'.format(t, r5))
print('{} x 6 = {}'.format(t, r6))
print('{} x 7 = {}'.format(t, r7))
print('{} x 8 = {}'.format(t, r8))
print('{} x 9 = {}'.format(t, r9))
print('{} x 10 = {}'.format(t, r10))
print('-' * 20)
print('{} x {:2} = {}'.format(t, 1, t * 1))
print('{} x {:2} = {}'.format(t, 2, t * 2))
print('{} x {:2} = {}'.format(t, 3, t * 3))
print('{} x {:2} = {}'.format(t, 4, t * 4))
print('{} x {:2} = {}'.format(t, 5, t * 5))
print('{} x {:2} = {}'.format(t, 6, t * 6))
print('{} x {:2} = {}'.format(t, 7, t * 7))
print('{} x {:2} = {}'.format(t, 8, t * 8))
print('{} x {:2} = {}'.format(t, 9, t * 9))
print('{} x {:2} = {}'.format(t, 10, t * 10))
print('-' * 20) |
class Palettes: # pylint: disable=too-few-public-methods
"""Color palettes applied to Map visualizations in the style helper methods.
By default, each color helper method has its own default palette.
More information at https://carto.com/carto-colors/
Example:
Create color bins style with the burg palette
>>> color_bins_style('column name', palette=palettes.burg)
"""
pass
PALETTES = [
'BURG',
'BURGYL',
'REDOR',
'ORYEL',
'PEACH',
'PINKYL',
'MINT',
'BLUGRN',
'DARKMINT',
'EMRLD',
'AG_GRNYL',
'BLUYL',
'TEAL',
'TEALGRN',
'PURP',
'PURPOR',
'SUNSET',
'MAGENTA',
'SUNSETDARK',
'AG_SUNSET',
'BRWNYL',
'ARMYROSE',
'FALL',
'GEYSER',
'TEMPS',
'TEALROSE',
'TROPIC',
'EARTH',
'ANTIQUE',
'BOLD',
'PASTEL',
'PRISM',
'SAFE',
'VIVID'
'CB_YLGN',
'CB_YLGNBU',
'CB_GNBU',
'CB_BUGN',
'CB_PUBUGN',
'CB_PUBU',
'CB_BUPU',
'CB_RDPU',
'CB_PURD',
'CB_ORRD',
'CB_YLORRD',
'CB_YLORBR',
'CB_PURPLES',
'CB_BLUES',
'CB_GREENS',
'CB_ORANGES',
'CB_REDS',
'CB_GREYS',
'CB_PUOR',
'CB_BRBG',
'CB_PRGN',
'CB_PIYG',
'CB_RDBU',
'CB_RDGY',
'CB_RDYLBU',
'CB_SPECTRAL',
'CB_RDYLGN',
'CB_ACCENT',
'CB_DARK2',
'CB_PAIRED',
'CB_PASTEL1',
'CB_PASTEL2',
'CB_SET1',
'CB_SET2',
'CB_SET3'
]
for palette in PALETTES:
setattr(Palettes, palette.lower(), palette)
| class Palettes:
"""Color palettes applied to Map visualizations in the style helper methods.
By default, each color helper method has its own default palette.
More information at https://carto.com/carto-colors/
Example:
Create color bins style with the burg palette
>>> color_bins_style('column name', palette=palettes.burg)
"""
pass
palettes = ['BURG', 'BURGYL', 'REDOR', 'ORYEL', 'PEACH', 'PINKYL', 'MINT', 'BLUGRN', 'DARKMINT', 'EMRLD', 'AG_GRNYL', 'BLUYL', 'TEAL', 'TEALGRN', 'PURP', 'PURPOR', 'SUNSET', 'MAGENTA', 'SUNSETDARK', 'AG_SUNSET', 'BRWNYL', 'ARMYROSE', 'FALL', 'GEYSER', 'TEMPS', 'TEALROSE', 'TROPIC', 'EARTH', 'ANTIQUE', 'BOLD', 'PASTEL', 'PRISM', 'SAFE', 'VIVIDCB_YLGN', 'CB_YLGNBU', 'CB_GNBU', 'CB_BUGN', 'CB_PUBUGN', 'CB_PUBU', 'CB_BUPU', 'CB_RDPU', 'CB_PURD', 'CB_ORRD', 'CB_YLORRD', 'CB_YLORBR', 'CB_PURPLES', 'CB_BLUES', 'CB_GREENS', 'CB_ORANGES', 'CB_REDS', 'CB_GREYS', 'CB_PUOR', 'CB_BRBG', 'CB_PRGN', 'CB_PIYG', 'CB_RDBU', 'CB_RDGY', 'CB_RDYLBU', 'CB_SPECTRAL', 'CB_RDYLGN', 'CB_ACCENT', 'CB_DARK2', 'CB_PAIRED', 'CB_PASTEL1', 'CB_PASTEL2', 'CB_SET1', 'CB_SET2', 'CB_SET3']
for palette in PALETTES:
setattr(Palettes, palette.lower(), palette) |
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
with plt.xkcd():
fig = plt.figure(figsize=(fig_w, fig_h))
my_plot(x, auditory, visual, posterior_pointwise)
plt.title('Sample output')
plt.show() | auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
with plt.xkcd():
fig = plt.figure(figsize=(fig_w, fig_h))
my_plot(x, auditory, visual, posterior_pointwise)
plt.title('Sample output')
plt.show() |
def get_google_folder_id(service, folder_name):
"""Get folder id of a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
folder_name: name of the folder you wish to get the ID of.
"""
page_token = None
while True:
children = service.files().list(q="mimeType='application/vnd.google-apps.folder'", spaces='drive',fields='nextPageToken, files(id, name)').execute()
for i in children['files']:
if i['name'] == folder_name:
folder_id = i['id']
break
page_token = children.get('nextPageToken', None)
if page_token is None:
break
return folder_id
def get_google_folders_in_folder(service, folder_id):
"""Get a list of folders in a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
folder_id: id of the folder you wish to get the folders list of.
"""
files_list = []
page_token = None
while True:
children = service.files().list(q="mimeType='application/vnd.google-apps.folder' and parents='"+folder_id+"' and trashed=false",
spaces='drive',
fields='nextPageToken, files(id, name)').execute()
for file in children.get('files', []):
files_list.append({'name':file.get('name'), 'id':file.get('id')})
page_token = children.get('nextPageToken', None)
if page_token is None:
break
return files_list
def get_google_files_in_folder(service, folder_id):
"""Get a list of files and folders in a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
folder_id: id of the folder you wish to get the folders list of.
"""
files_list = []
page_token = None
while True:
children = service.files().list(q="parents='"+folder_id+"' and trashed=false",
spaces='drive',
fields='nextPageToken, files(id, name)').execute()
for file in children.get('files', []):
files_list.append({'name':file.get('name'), 'id':file.get('id')})
page_token = children.get('nextPageToken', None)
if page_token is None:
break
return files_list
def uplaod_google_file(service, MediaFileUpload, parent_id, file_name):
"""Upload a file in a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
MediaFileUpload: function of oauth2client.service_account. see www.pypi.com for a full example.
parent_id: id of the folder you wish to get the folders list of.
file_name: local path to the file. If the file is in the same folder as your script, then you should only enter here the name of your file.
"""
file_metadata = {
'parents' : [parent_id],
'name': file_name}
media = MediaFileUpload(file_name)
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
return parent_id
def find_google_fileid_tree(service, fileId):
"""Find the folder tree of a file
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
fileId: id of the file you wish to get the tree for.
"""
file = service.files().get(fileId=fileId, fields='id, name, parents').execute()
tree = []
parent = file.get('parents')
if parent:
while True:
folder = service.files().get(
fileId=parent[0], fields='id, name, parents').execute()
parent = folder.get('parents')
if parent is None:
break
tree.append({'id': parent[0], 'name': folder.get('name')})
return tree | def get_google_folder_id(service, folder_name):
"""Get folder id of a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
folder_name: name of the folder you wish to get the ID of.
"""
page_token = None
while True:
children = service.files().list(q="mimeType='application/vnd.google-apps.folder'", spaces='drive', fields='nextPageToken, files(id, name)').execute()
for i in children['files']:
if i['name'] == folder_name:
folder_id = i['id']
break
page_token = children.get('nextPageToken', None)
if page_token is None:
break
return folder_id
def get_google_folders_in_folder(service, folder_id):
"""Get a list of folders in a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
folder_id: id of the folder you wish to get the folders list of.
"""
files_list = []
page_token = None
while True:
children = service.files().list(q="mimeType='application/vnd.google-apps.folder' and parents='" + folder_id + "' and trashed=false", spaces='drive', fields='nextPageToken, files(id, name)').execute()
for file in children.get('files', []):
files_list.append({'name': file.get('name'), 'id': file.get('id')})
page_token = children.get('nextPageToken', None)
if page_token is None:
break
return files_list
def get_google_files_in_folder(service, folder_id):
"""Get a list of files and folders in a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
folder_id: id of the folder you wish to get the folders list of.
"""
files_list = []
page_token = None
while True:
children = service.files().list(q="parents='" + folder_id + "' and trashed=false", spaces='drive', fields='nextPageToken, files(id, name)').execute()
for file in children.get('files', []):
files_list.append({'name': file.get('name'), 'id': file.get('id')})
page_token = children.get('nextPageToken', None)
if page_token is None:
break
return files_list
def uplaod_google_file(service, MediaFileUpload, parent_id, file_name):
"""Upload a file in a folder in Google Drive
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
MediaFileUpload: function of oauth2client.service_account. see www.pypi.com for a full example.
parent_id: id of the folder you wish to get the folders list of.
file_name: local path to the file. If the file is in the same folder as your script, then you should only enter here the name of your file.
"""
file_metadata = {'parents': [parent_id], 'name': file_name}
media = media_file_upload(file_name)
file = service.files().create(body=file_metadata, media_body=media, fields='id').execute()
return parent_id
def find_google_fileid_tree(service, fileId):
"""Find the folder tree of a file
Arguments:
service: in order to use any of this library, the user needs to first build the service class using google ServiceAccountCredentials. see https://pypi.org/project/google-api-v3-helper/ or https://github.com/sbi-rviot/google_api_helper for a full example.
fileId: id of the file you wish to get the tree for.
"""
file = service.files().get(fileId=fileId, fields='id, name, parents').execute()
tree = []
parent = file.get('parents')
if parent:
while True:
folder = service.files().get(fileId=parent[0], fields='id, name, parents').execute()
parent = folder.get('parents')
if parent is None:
break
tree.append({'id': parent[0], 'name': folder.get('name')})
return tree |
# Tutorial skipper snippet
def skip_tutorial():
MAPLE_ADMINISTARTOR = 2007
quests_to_complete = [
20820, # The City of Ereve
20821, # Knight's Orientation
20822, # The Path of Bravery
20823, # Question and Answer
20824, # Knight's Cavalier
20825, # Well-Behaved Student
20826, # Lesson 1 - Ereve History
20827, # What's Next?
20828, # Lesson 2 - Physical Training
20829, # Lesson 3 - Battle Basics 1
20830, # A Much-Needed Break
20831, # Lesson 3 - Battle Basics 2
20832, # Lesson, Interrupted
20833, # Tiny Bird
20834, # The Tranquil Garden
20835, # The Chief Knights
20836, # Lesson, Resumed
20837, # Lesson 5 - Skills
20838, # Certified Knight
20839, # Meeting with the Empress
]
map_to_warp = 130000000 # Ereve
target_level = 10
sm.setSpeakerID(MAPLE_ADMINISTARTOR)
sm.removeEscapeButton()
sm.lockInGameUI(True)
if sm.sendAskYesNo("Would you like to skip the tutorial questline and instantly arrive at #m" + str(map_to_warp) + "#?"):
if sm.getChr().getLevel() < target_level:
sm.addLevel(target_level - sm.getChr().getLevel())
for quest in quests_to_complete:
sm.completeQuestNoRewards(quest)
sm.warp(map_to_warp)
sm.lockInGameUI(False)
sm.dispose()
skip_tutorial()
sm.showEffect("Effect/OnUserEff.img/guideEffect/cygnusTutorial/0", 0, 0)
sm.invokeAfterDelay(5000, "showEffect", "Effect/OnUserEff.img/guideEffect/cygnusTutorial/1", 0, 0) | def skip_tutorial():
maple_administartor = 2007
quests_to_complete = [20820, 20821, 20822, 20823, 20824, 20825, 20826, 20827, 20828, 20829, 20830, 20831, 20832, 20833, 20834, 20835, 20836, 20837, 20838, 20839]
map_to_warp = 130000000
target_level = 10
sm.setSpeakerID(MAPLE_ADMINISTARTOR)
sm.removeEscapeButton()
sm.lockInGameUI(True)
if sm.sendAskYesNo('Would you like to skip the tutorial questline and instantly arrive at #m' + str(map_to_warp) + '#?'):
if sm.getChr().getLevel() < target_level:
sm.addLevel(target_level - sm.getChr().getLevel())
for quest in quests_to_complete:
sm.completeQuestNoRewards(quest)
sm.warp(map_to_warp)
sm.lockInGameUI(False)
sm.dispose()
skip_tutorial()
sm.showEffect('Effect/OnUserEff.img/guideEffect/cygnusTutorial/0', 0, 0)
sm.invokeAfterDelay(5000, 'showEffect', 'Effect/OnUserEff.img/guideEffect/cygnusTutorial/1', 0, 0) |
class ATM:
def __init__(self,balance,bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def show_withdrawals(self):
for withdrawal in self.withdrawals_list:
print("withdrawal: "+str(withdrawal))
def print_information(self):
print("Welcome to "+ self.bank_name)
print("current balance: " + str(self.balance))
def check_balance(self , request):
if self.balance < request:
print("Can't give you all this money !!")
elif request < 0:
print("More than zero plz!")
def withdraw(self, request):
self.withdrawals_list.append(request)
notes = [100,50,10,5]
if self.balance > request:
self.balance = self.balance - request
for note in notes:
while request >= note:
request -= note
print("Give " + str(note))
balance1 = 500
balance2 = 1000
atm1 = ATM(balance1, "islamy bank")
atm2 = ATM(balance2, "baraka bank")
atm1.print_information()
atm1.check_balance(300)
atm1.withdraw(300)
atm1.print_information()
atm1.check_balance(250)
atm1.withdraw(250)
atm1.show_withdrawals()
atm2.print_information()
atm2.check_balance(500)
atm2.withdraw(500)
atm2.print_information()
atm2.check_balance(455)
atm2.withdraw(455)
atm2.show_withdrawals() | class Atm:
def __init__(self, balance, bank_name):
self.balance = balance
self.bank_name = bank_name
self.withdrawals_list = []
def show_withdrawals(self):
for withdrawal in self.withdrawals_list:
print('withdrawal: ' + str(withdrawal))
def print_information(self):
print('Welcome to ' + self.bank_name)
print('current balance: ' + str(self.balance))
def check_balance(self, request):
if self.balance < request:
print("Can't give you all this money !!")
elif request < 0:
print('More than zero plz!')
def withdraw(self, request):
self.withdrawals_list.append(request)
notes = [100, 50, 10, 5]
if self.balance > request:
self.balance = self.balance - request
for note in notes:
while request >= note:
request -= note
print('Give ' + str(note))
balance1 = 500
balance2 = 1000
atm1 = atm(balance1, 'islamy bank')
atm2 = atm(balance2, 'baraka bank')
atm1.print_information()
atm1.check_balance(300)
atm1.withdraw(300)
atm1.print_information()
atm1.check_balance(250)
atm1.withdraw(250)
atm1.show_withdrawals()
atm2.print_information()
atm2.check_balance(500)
atm2.withdraw(500)
atm2.print_information()
atm2.check_balance(455)
atm2.withdraw(455)
atm2.show_withdrawals() |
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# brute force
ar = nums1 + nums2
ar.sort()
n = len(ar)
median = ar[n//2]
if n%2 != 0:
return median
else:
return (median + ar[(n//2)-1])/2 | class Solution:
def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float:
ar = nums1 + nums2
ar.sort()
n = len(ar)
median = ar[n // 2]
if n % 2 != 0:
return median
else:
return (median + ar[n // 2 - 1]) / 2 |
defines = {}
specials = {}
defines.update(globals()["__builtins__"])
def define(fnc):
defines[fnc.__name__] = fnc
return fnc
def rename(name):
def deco(fnc):
fnc.__name__ = name
return define(fnc)
return deco
def special(fnc):
specials[fnc.__name__] = fnc
return fnc
def register(name, value):
defines[name] = value
| defines = {}
specials = {}
defines.update(globals()['__builtins__'])
def define(fnc):
defines[fnc.__name__] = fnc
return fnc
def rename(name):
def deco(fnc):
fnc.__name__ = name
return define(fnc)
return deco
def special(fnc):
specials[fnc.__name__] = fnc
return fnc
def register(name, value):
defines[name] = value |
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[i] < array[j]:
array[i], array[j] = array[j], array[i]
j -= 1
i -= 1
return array
def test_insertion_sort_simple():
assert insertion_sort([4, 2, 5, 1, 7]) == [1, 2, 4, 5, 7]
def test_insertion_sort_one_number():
assert insertion_sort([1]) == [1]
def test_insertion_sort_already_sorted():
assert insertion_sort([1, 2]) == [1, 2]
| def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i - 1
while j >= 0 and array[i] < array[j]:
(array[i], array[j]) = (array[j], array[i])
j -= 1
i -= 1
return array
def test_insertion_sort_simple():
assert insertion_sort([4, 2, 5, 1, 7]) == [1, 2, 4, 5, 7]
def test_insertion_sort_one_number():
assert insertion_sort([1]) == [1]
def test_insertion_sort_already_sorted():
assert insertion_sort([1, 2]) == [1, 2] |
def generatorA(value, stop):
i = 0
while i < stop:
value = (value * 16807) % 2147483647
yield value
i += 1
def generatorB(value, stop):
i = 0
while i < stop:
value = (value * 48271) % 2147483647
yield value
i += 1
def generatorAPart2(value, stop):
i = 0
while i < stop:
value = (value * 16807) % 2147483647
while value % 4 != 0:
value = (value * 16807) % 2147483647
yield value
i += 1
def generatorBPart2(value, stop):
i = 0
while i < stop:
value = (value * 48271) % 2147483647
while value % 8 != 0:
value = (value * 48271) % 2147483647
yield value
i += 1
| def generator_a(value, stop):
i = 0
while i < stop:
value = value * 16807 % 2147483647
yield value
i += 1
def generator_b(value, stop):
i = 0
while i < stop:
value = value * 48271 % 2147483647
yield value
i += 1
def generator_a_part2(value, stop):
i = 0
while i < stop:
value = value * 16807 % 2147483647
while value % 4 != 0:
value = value * 16807 % 2147483647
yield value
i += 1
def generator_b_part2(value, stop):
i = 0
while i < stop:
value = value * 48271 % 2147483647
while value % 8 != 0:
value = value * 48271 % 2147483647
yield value
i += 1 |
# https://www.codechef.com/ELE32018/problems/JACKJILL
t=int(input())
for _ in range(t):
n,k,d=[int(x) for x in input().strip().split()]
a=[int(x) for x in input().strip().split()]
b=[int(x) for x in input().strip().split()]
flag=0
res1=0
res2=0
for i in range(k):
res1 += a[i]
res2 += b[i]
if(res1+res2 >= d):
flag=1
else:
for i in range(k,n):
res1 = res1 + a[i] - a[i-k]
res2 = res2 + b[i] - b[i-k]
if(res1+res2 >= d):
flag=1
break
if(flag):
print("no")
else:
print("yes")
| t = int(input())
for _ in range(t):
(n, k, d) = [int(x) for x in input().strip().split()]
a = [int(x) for x in input().strip().split()]
b = [int(x) for x in input().strip().split()]
flag = 0
res1 = 0
res2 = 0
for i in range(k):
res1 += a[i]
res2 += b[i]
if res1 + res2 >= d:
flag = 1
else:
for i in range(k, n):
res1 = res1 + a[i] - a[i - k]
res2 = res2 + b[i] - b[i - k]
if res1 + res2 >= d:
flag = 1
break
if flag:
print('no')
else:
print('yes') |
# Copyright 2011 Google Inc. All Rights Reserved.
"""Specify the modules for which a Python 2.7 stub exists."""
# pylint: disable=undefined-all-variable
__all__ = [
# These reside here.
'httplib',
'socket',
'subprocess',
'threading',
'urllib',
]
MODULE_OVERRIDES = __all__
| """Specify the modules for which a Python 2.7 stub exists."""
__all__ = ['httplib', 'socket', 'subprocess', 'threading', 'urllib']
module_overrides = __all__ |
class Solution(object):
def isValid(self, S):
"""
:type S: str
:rtype: bool
"""
stack = []
for s in S:
if s == 'c':
valid = [s]
for i in range(2):
if not stack:
return False
valid.append(stack.pop())
if valid != ['c', 'b', 'a']:
return False
else:
stack.append(s)
return len(stack) == 0
def test_is_valid():
s = Solution()
assert s.isValid("aabcbc")
assert s.isValid("abcabcababcc")
assert s.isValid("abccba") is False
assert s.isValid("cababc") is False
| class Solution(object):
def is_valid(self, S):
"""
:type S: str
:rtype: bool
"""
stack = []
for s in S:
if s == 'c':
valid = [s]
for i in range(2):
if not stack:
return False
valid.append(stack.pop())
if valid != ['c', 'b', 'a']:
return False
else:
stack.append(s)
return len(stack) == 0
def test_is_valid():
s = solution()
assert s.isValid('aabcbc')
assert s.isValid('abcabcababcc')
assert s.isValid('abccba') is False
assert s.isValid('cababc') is False |
class Solution(object):
def findMaxConsecutiveOnes(self, nums):
ans = 0
cnt = 0
for i in range(len(nums)):
if nums[i] == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans
| class Solution(object):
def find_max_consecutive_ones(self, nums):
ans = 0
cnt = 0
for i in range(len(nums)):
if nums[i] == 1:
cnt += 1
ans = max(ans, cnt)
else:
cnt = 0
return ans |
# Accept one int and one float type value & display average
a = int(input("Enter int no.: "))
b = float(input("Enter float no.: "))
c = (a+b)/2
print(f"Average value {c}")
| a = int(input('Enter int no.: '))
b = float(input('Enter float no.: '))
c = (a + b) / 2
print(f'Average value {c}') |
class Solution:
def minimizeError(self, prices: List[str], target: int) -> str:
# A[i] := (costCeil - costFloor, costCeil, costFloor)
# the lower the costCeil - costFloor, the cheaper to ceil it
A = []
sumFloored = 0
sumCeiled = 0
for price in map(float, prices):
floored = math.floor(price)
ceiled = math.ceil(price)
sumFloored += floored
sumCeiled += ceiled
costFloor = price - floored
costCeil = ceiled - price
A.append((costCeil - costFloor, costCeil, costFloor))
if not sumFloored <= target <= sumCeiled:
return '-1'
A.sort()
nCeiled = target - sumFloored
return '{:.3f}'.format(sum(a[1] for a in A[:nCeiled]) +
sum(a[2] for a in A[nCeiled:]))
| class Solution:
def minimize_error(self, prices: List[str], target: int) -> str:
a = []
sum_floored = 0
sum_ceiled = 0
for price in map(float, prices):
floored = math.floor(price)
ceiled = math.ceil(price)
sum_floored += floored
sum_ceiled += ceiled
cost_floor = price - floored
cost_ceil = ceiled - price
A.append((costCeil - costFloor, costCeil, costFloor))
if not sumFloored <= target <= sumCeiled:
return '-1'
A.sort()
n_ceiled = target - sumFloored
return '{:.3f}'.format(sum((a[1] for a in A[:nCeiled])) + sum((a[2] for a in A[nCeiled:]))) |
# GENERATED VERSION FILE
# TIME: Mon Oct 11 04:02:23 2021
__version__ = '1.2.0+f83fd55'
short_version = '1.2.0'
version_info = (1, 2, 0)
| __version__ = '1.2.0+f83fd55'
short_version = '1.2.0'
version_info = (1, 2, 0) |
# -*- coding: utf-8 -*-
# goma
# ----
# Generic object mapping algorithm.
#
# Author: sonntagsgesicht, based on a fork of Deutsche Postbank [pbrisk]
# Version: 0.2, copyright Wednesday, 18 September 2019
# Website: https://github.com/sonntagsgesicht/goma
# License: Apache License 2.0 (see LICENSE file)
class BaseMatch(object):
""" Base match class """
def match(self, *args):
""" return match results """
pass # functions are implemented in sub classes
def _has_relation_operator(self, condition_str):
return str(condition_str)[:1] in ['<', '>', '!', '=', '(', '[']
def _apply_relation_match(self, match_value, detail_value):
""" return relation match results """
match_value = match_value.replace(' ', '')
# if interval
if match_value[:1] in ['[', '(']:
rel_vals = [type(detail_value)(val) for val in match_value[1:-1].split(',')]
rel_ops = [self._repl_relation_operator(op) for op in [match_value[0], match_value[-1]]]
# fixme NO eval usage !!!
cmd = 'detail_value ' + rel_ops[0] + ' rel_vals[0] and detail_value ' + rel_ops[1] + ' rel_vals[1]'
# match_res = eval(cmd)
# else
else:
if self._repl_relation_operator(match_value[:2]):
rel_ops = match_value[:2]
rel_val = type(detail_value)(match_value[2:])
else:
rel_ops = match_value[:1]
rel_val = type(detail_value)(match_value[1:])
# fixme NO eval usage !!!
cmd = 'detail_value ' + rel_ops + ' rel_val'
# match_res = eval(cmd)
# return match_res
raise NotImplementedError('Relation match will be fixed in future releases.')
def _repl_relation_operator(self, relation_symbol):
if relation_symbol == '[': return '>='
if relation_symbol == '(': return '>'
if relation_symbol == ']': return '<='
if relation_symbol == ')': return '<'
if relation_symbol in ['<=', '=<']: return '<='
if relation_symbol in ['>=', '=>']: return '>='
if relation_symbol == '==': return '=='
if relation_symbol == '!=': return '!='
return relation_symbol
| class Basematch(object):
""" Base match class """
def match(self, *args):
""" return match results """
pass
def _has_relation_operator(self, condition_str):
return str(condition_str)[:1] in ['<', '>', '!', '=', '(', '[']
def _apply_relation_match(self, match_value, detail_value):
""" return relation match results """
match_value = match_value.replace(' ', '')
if match_value[:1] in ['[', '(']:
rel_vals = [type(detail_value)(val) for val in match_value[1:-1].split(',')]
rel_ops = [self._repl_relation_operator(op) for op in [match_value[0], match_value[-1]]]
cmd = 'detail_value ' + rel_ops[0] + ' rel_vals[0] and detail_value ' + rel_ops[1] + ' rel_vals[1]'
else:
if self._repl_relation_operator(match_value[:2]):
rel_ops = match_value[:2]
rel_val = type(detail_value)(match_value[2:])
else:
rel_ops = match_value[:1]
rel_val = type(detail_value)(match_value[1:])
cmd = 'detail_value ' + rel_ops + ' rel_val'
raise not_implemented_error('Relation match will be fixed in future releases.')
def _repl_relation_operator(self, relation_symbol):
if relation_symbol == '[':
return '>='
if relation_symbol == '(':
return '>'
if relation_symbol == ']':
return '<='
if relation_symbol == ')':
return '<'
if relation_symbol in ['<=', '=<']:
return '<='
if relation_symbol in ['>=', '=>']:
return '>='
if relation_symbol == '==':
return '=='
if relation_symbol == '!=':
return '!='
return relation_symbol |
class InvalidServiceBusMessage(Exception):
"""
Raised when a message is not valid
"""
def __init__(self, reason='InvalidServiceBusMessage', description='The received message is not valid') -> None:
self.reason = reason
self.description = description
super().__init__(self.reason)
def is_invalid_message(exception_type) -> bool:
"""
Check if the exception is a InvalidServiceBusMessage or a subclass of it
"""
return issubclass(exception_type, InvalidServiceBusMessage)
| class Invalidservicebusmessage(Exception):
"""
Raised when a message is not valid
"""
def __init__(self, reason='InvalidServiceBusMessage', description='The received message is not valid') -> None:
self.reason = reason
self.description = description
super().__init__(self.reason)
def is_invalid_message(exception_type) -> bool:
"""
Check if the exception is a InvalidServiceBusMessage or a subclass of it
"""
return issubclass(exception_type, InvalidServiceBusMessage) |
"""
class attribute
class method
static method
"""
class Person:
number_of_people = 0
def __init__(self, name) -> None:
self.name = name
Person.number_of_people += 1
Person.add_person()
@classmethod
def add_person(cls):
cls.number_of_people + 1
@classmethod
def number_of_people_(cls):
return cls.number_of_people
class Math:
@staticmethod
def adds(x):
return x + 5
if __name__=="__main__":
p1 = Person("Tom")
p2 = Person("Bob")
p3 = Person("Jerry")
print(Person.number_of_people_())
print(Math.adds(5))
| """
class attribute
class method
static method
"""
class Person:
number_of_people = 0
def __init__(self, name) -> None:
self.name = name
Person.number_of_people += 1
Person.add_person()
@classmethod
def add_person(cls):
cls.number_of_people + 1
@classmethod
def number_of_people_(cls):
return cls.number_of_people
class Math:
@staticmethod
def adds(x):
return x + 5
if __name__ == '__main__':
p1 = person('Tom')
p2 = person('Bob')
p3 = person('Jerry')
print(Person.number_of_people_())
print(Math.adds(5)) |
values = input("Enter comma separated values: ")
list = values.split(",")
tuple = tuple(list)
#this is a forked branch
print("list: {}".format(list))
print("tuple: {}".format(tuple))
| values = input('Enter comma separated values: ')
list = values.split(',')
tuple = tuple(list)
print('list: {}'.format(list))
print('tuple: {}'.format(tuple)) |
def add_replicaset(instance, alias, roles, servers,
status='healthy', all_rw=False, weight=None):
r_uuid = '{}-uuid'.format(alias)
r_servers = []
for s in servers: # servers = ['alias-1', 'alias-2']
r_servers.append({
'alias': s,
'uuid': '{}-uuid'.format(s),
'uri': '{}-uri'.format(s),
'status': 'healthy',
'replicaset': {
'uuid': r_uuid,
'alias': alias,
'roles': roles,
}
})
instance.add_topology_servers(r_servers)
replicaset = {
'uuid': r_uuid,
'alias': alias,
'status': status,
'roles': roles,
'weight': weight,
'all_rw': all_rw,
'servers': [{'alias': s, 'priority': i + 1} for i, s in enumerate(servers)]
}
instance.add_topology_replicaset(replicaset)
return replicaset
def set_box_cfg(instace, memtx_memory):
instace.set_box_cfd({
'memtx_memory': memtx_memory,
})
| def add_replicaset(instance, alias, roles, servers, status='healthy', all_rw=False, weight=None):
r_uuid = '{}-uuid'.format(alias)
r_servers = []
for s in servers:
r_servers.append({'alias': s, 'uuid': '{}-uuid'.format(s), 'uri': '{}-uri'.format(s), 'status': 'healthy', 'replicaset': {'uuid': r_uuid, 'alias': alias, 'roles': roles}})
instance.add_topology_servers(r_servers)
replicaset = {'uuid': r_uuid, 'alias': alias, 'status': status, 'roles': roles, 'weight': weight, 'all_rw': all_rw, 'servers': [{'alias': s, 'priority': i + 1} for (i, s) in enumerate(servers)]}
instance.add_topology_replicaset(replicaset)
return replicaset
def set_box_cfg(instace, memtx_memory):
instace.set_box_cfd({'memtx_memory': memtx_memory}) |
"""
__version__.py
~~~~~~~~~~~~~~
Information about the current version of the street-situation-detection package.
"""
__title__ = 'street-detection'
__description__ = 'street-detection - A python package for detecting streets'
__version__ = '0.1.0'
__author__ = 'Steven Mi'
__author_email__ = 's0558366@htw-berlin.de'
__license__ = 'Apache 2.0'
__url__ = 'https://github.com/steven-mi/street-situation-detection'
| """
__version__.py
~~~~~~~~~~~~~~
Information about the current version of the street-situation-detection package.
"""
__title__ = 'street-detection'
__description__ = 'street-detection - A python package for detecting streets'
__version__ = '0.1.0'
__author__ = 'Steven Mi'
__author_email__ = 's0558366@htw-berlin.de'
__license__ = 'Apache 2.0'
__url__ = 'https://github.com/steven-mi/street-situation-detection' |
DEBUG = True
SECRET_KEY = "kasih-tau-gak-ya"
BUNDLE_ERRORS = True
MONGO_HOST = 'mongo'
MONGO_DBNAME = 'news-api'
MONGO_PORT = 27017
JSONIFY_PRETTYPRINT_REGULAR = False | debug = True
secret_key = 'kasih-tau-gak-ya'
bundle_errors = True
mongo_host = 'mongo'
mongo_dbname = 'news-api'
mongo_port = 27017
jsonify_prettyprint_regular = False |
class Solution:
def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
'''
T: O(n log n), n = number of words
S: O(n)
'''
for punc in "!?',;.":
paragraph = paragraph.replace(punc, ' ')
words = paragraph.lower().strip().split()
bannedSet = set(banned)
wordCount = {}
for word in words:
if word in bannedSet: continue
wordCount[word] = wordCount.get(word, 0) + 1
words = sorted(wordCount.items(), key = lambda x: (-x[1], x[0]))
return words[0][0]
| class Solution:
def most_common_word(self, paragraph: str, banned: List[str]) -> str:
"""
T: O(n log n), n = number of words
S: O(n)
"""
for punc in "!?',;.":
paragraph = paragraph.replace(punc, ' ')
words = paragraph.lower().strip().split()
banned_set = set(banned)
word_count = {}
for word in words:
if word in bannedSet:
continue
wordCount[word] = wordCount.get(word, 0) + 1
words = sorted(wordCount.items(), key=lambda x: (-x[1], x[0]))
return words[0][0] |
# configuration file
TRAINING_FILE_ORIGINAL = '../mnist_train.csv'
TRAINING_FILE = '../input/mnist_train_folds.csv'
TESTING_FILE = '../input/mnist_test.csv'
MODEL_OUTPUT = "../models/" | training_file_original = '../mnist_train.csv'
training_file = '../input/mnist_train_folds.csv'
testing_file = '../input/mnist_test.csv'
model_output = '../models/' |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 21 10:17:27 2019
@author: Administrator
"""
#class Solution:
# def superPow(self, a: int, b: list) -> int:
# B = 0
# b.reverse()
# for k in range(len(b)):
# B += b[k] * 10 ** k
#
# A = a**B#self.pow(a, B)#
#
## while A >= 1337:
## A -= 1337
## return A
## return A - (A//1337) * 1337
# return A % 1337
#
# def pow(self, p, q):
# if q == 0:
# return 1
# if q == 1:
# return p
# if q % 2 == 0:
# tmp = self.pow(p, q//2)
# return tmp**2
# else:
# tmp = self.pow(p, q//2)
# return tmp**2 * p
class Solution:
def superPow(self, a: int, b: list) -> int:
sum = 0
for i in b:
sum = sum * 10 + i
return pow(a, sum, 1337)
solu = Solution()
a, b = 2, [3]
a, b = 2, [1,0]
#a, b = 2, [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
a, b = 78267, [1,7,7,4,3,1,7,0,1,4,4,9,2,8,5,0,0,9,3,1,2,5,9,6,0,9,9,0,9,6,0,5,3,7,9,8,8,9,8,2,5,4,1,9,3,8,0,5,9,5,6,1,1,8,9,3,7,8,5,8,5,5,3,0,4,3,1,5,4,1,7,9,6,8,8,9,8,0,6,7,8,3,1,1,1,0,6,8,1,1,6,6,9,1,8,5,6,9,0,0,1,7,1,7,7,2,8,5,4,4,5,2,9,6,5,0,8,1,0,9,5,8,7,6,0,6,1,8,7,2,9,8,1,0,7,9,4,7,6,9,2,3,1,3,9,9,6,8,0,8,9,7,7,7,3,9,5,5,7,4,9,8,3,0,1,2,1,5,0,8,4,4,3,8,9,3,7,5,3,9,4,4,9,3,3,2,4,8,9,3,3,8,2,8,1,3,2,2,8,4,2,5,0,6,3,0,9,0,5,4,1,1,8,0,4,2,5,8,2,4,2,7,5,4,7,6,9,0,8,9,6,1,4,7,7,9,7,8,1,4,4,3,6,4,5,2,6,0,1,1,5,3,8,0,9,8,8,0,0,6,1,6,9,6,5,8,7,4,8,9,9,2,4,7,7,9,9,5,2,2,6,9,7,7,9,8,5,9,8,5,5,0,3,5,8,9,5,7,3,4,6,4,6,2,3,5,2,3,1,4,5,9,3,3,6,4,1,3,3,2,0,0,4,4,7,2,3,3,9,8,7,8,5,5,0,8,3,4,1,4,0,9,5,5,4,4,9,7,7,4,1,8,7,5,2,4,9,7,9,1,7,8,9,2,4,1,1,7,6,4,3,6,5,0,2,1,4,3,9,2,0,0,2,9,8,4,5,7,3,5,8,2,3,9,5,9,1,8,8,9,2,3,7,0,4,1,1,8,7,0,2,7,3,4,6,1,0,3,8,5,8,9,8,4,8,3,5,1,1,4,2,5,9,0,5,3,1,7,4,8,9,6,7,2,3,5,5,3,9,6,9,9,5,7,3,5,2,9,9,5,5,1,0,6,3,8,0,5,5,6,5,6,4,5,1,7,0,6,3,9,4,4,9,1,3,4,7,7,5,8,2,0,9,2,7,3,0,9,0,7,7,7,4,1,2,5,1,3,3,6,4,8,2,5,9,5,0,8,2,5,6,4,8,8,8,7,3,1,8,5,0,5,2,4,8,5,1,1,0,7,9,6,5,1,2,6,6,4,7,0,9,5,6,9,3,7,8,8,8,6,5,8,3,8,5,4,5,8,5,7,5,7,3,2,8,7,1,7,1,8,7,3,3,6,2,9,3,3,9,3,1,5,1,5,5,8,1,2,7,8,9,2,5,4,5,4,2,6,1,3,6,0,6,9,6,1,0,1,4,0,4,5,5,8,2,2,6,3,4,3,4,3,8,9,7,5,5,9,1,8,5,9,9,1,8,7,2,1,1,8,1,5,6,8,5,8,0,2,4,4,7,8,9,5,9,8,0,5,0,3,5,5,2,6,8,3,4,1,4,7,1,7,2,7,5,8,8,7,2,2,3,9,2,2,7,3,2,9,0,2,3,6,9,7,2,8,0,8,1,6,5,2,3,0,2,0,0,0,9,2,2,2,3,6,6,0,9,1,0,0,3,5,8,3,2,0,3,5,1,4,1,6,8,7,6,0,9,8,0,1,0,4,5,6,0,2,8,2,5,0,2,8,5,2,3,0,2,6,7,3,0,0,2,1,9,0,1,9,9,2,0,1,6,7,7,9,9,6,1,4,8,5,5,6,7,0,6,1,7,3,5,9,3,9,0,5,9,2,4,8,6,6,2,2,3,9,3,5,7,4,1,6,9,8,2,6,9,0,0,8,5,7,7,0,6,0,5,7,4,9,6,0,7,8,4,3,9,8,8,7,4,1,5,6,0,9,4,1,9,4,9,4,1,8,6,7,8,2,5,2,3,3,4,3,3,1,6,4,1,6,1,5,7,8,1,9,7,6,0,8,0,1,4,4,0,1,1,8,3,8,3,8,3,9,1,6,0,7,1,3,3,4,9,3,5,2,4,2,0,7,3,3,8,7,7,8,8,0,9,3,1,2,2,4,3,3,3,6,1,6,9,6,2,0,1,7,5,6,2,5,3,5,0,3,2,7,2,3,0,3,6,1,7,8,7,0,4,0,6,7,6,6,3,9,8,5,8,3,3,0,9,6,7,1,9,2,1,3,5,1,6,3,4,3,4,1,6,8,4,2,5]
print(solu.superPow(a, b))
#print(solu.pow(2,10))
#for k in range(10000):
# k = [int(x) for x in str(k)]
# print(solu.superPow(2, k)) | """
Created on Fri Jun 21 10:17:27 2019
@author: Administrator
"""
class Solution:
def super_pow(self, a: int, b: list) -> int:
sum = 0
for i in b:
sum = sum * 10 + i
return pow(a, sum, 1337)
solu = solution()
(a, b) = (2, [3])
(a, b) = (2, [1, 0])
(a, b) = (78267, [1, 7, 7, 4, 3, 1, 7, 0, 1, 4, 4, 9, 2, 8, 5, 0, 0, 9, 3, 1, 2, 5, 9, 6, 0, 9, 9, 0, 9, 6, 0, 5, 3, 7, 9, 8, 8, 9, 8, 2, 5, 4, 1, 9, 3, 8, 0, 5, 9, 5, 6, 1, 1, 8, 9, 3, 7, 8, 5, 8, 5, 5, 3, 0, 4, 3, 1, 5, 4, 1, 7, 9, 6, 8, 8, 9, 8, 0, 6, 7, 8, 3, 1, 1, 1, 0, 6, 8, 1, 1, 6, 6, 9, 1, 8, 5, 6, 9, 0, 0, 1, 7, 1, 7, 7, 2, 8, 5, 4, 4, 5, 2, 9, 6, 5, 0, 8, 1, 0, 9, 5, 8, 7, 6, 0, 6, 1, 8, 7, 2, 9, 8, 1, 0, 7, 9, 4, 7, 6, 9, 2, 3, 1, 3, 9, 9, 6, 8, 0, 8, 9, 7, 7, 7, 3, 9, 5, 5, 7, 4, 9, 8, 3, 0, 1, 2, 1, 5, 0, 8, 4, 4, 3, 8, 9, 3, 7, 5, 3, 9, 4, 4, 9, 3, 3, 2, 4, 8, 9, 3, 3, 8, 2, 8, 1, 3, 2, 2, 8, 4, 2, 5, 0, 6, 3, 0, 9, 0, 5, 4, 1, 1, 8, 0, 4, 2, 5, 8, 2, 4, 2, 7, 5, 4, 7, 6, 9, 0, 8, 9, 6, 1, 4, 7, 7, 9, 7, 8, 1, 4, 4, 3, 6, 4, 5, 2, 6, 0, 1, 1, 5, 3, 8, 0, 9, 8, 8, 0, 0, 6, 1, 6, 9, 6, 5, 8, 7, 4, 8, 9, 9, 2, 4, 7, 7, 9, 9, 5, 2, 2, 6, 9, 7, 7, 9, 8, 5, 9, 8, 5, 5, 0, 3, 5, 8, 9, 5, 7, 3, 4, 6, 4, 6, 2, 3, 5, 2, 3, 1, 4, 5, 9, 3, 3, 6, 4, 1, 3, 3, 2, 0, 0, 4, 4, 7, 2, 3, 3, 9, 8, 7, 8, 5, 5, 0, 8, 3, 4, 1, 4, 0, 9, 5, 5, 4, 4, 9, 7, 7, 4, 1, 8, 7, 5, 2, 4, 9, 7, 9, 1, 7, 8, 9, 2, 4, 1, 1, 7, 6, 4, 3, 6, 5, 0, 2, 1, 4, 3, 9, 2, 0, 0, 2, 9, 8, 4, 5, 7, 3, 5, 8, 2, 3, 9, 5, 9, 1, 8, 8, 9, 2, 3, 7, 0, 4, 1, 1, 8, 7, 0, 2, 7, 3, 4, 6, 1, 0, 3, 8, 5, 8, 9, 8, 4, 8, 3, 5, 1, 1, 4, 2, 5, 9, 0, 5, 3, 1, 7, 4, 8, 9, 6, 7, 2, 3, 5, 5, 3, 9, 6, 9, 9, 5, 7, 3, 5, 2, 9, 9, 5, 5, 1, 0, 6, 3, 8, 0, 5, 5, 6, 5, 6, 4, 5, 1, 7, 0, 6, 3, 9, 4, 4, 9, 1, 3, 4, 7, 7, 5, 8, 2, 0, 9, 2, 7, 3, 0, 9, 0, 7, 7, 7, 4, 1, 2, 5, 1, 3, 3, 6, 4, 8, 2, 5, 9, 5, 0, 8, 2, 5, 6, 4, 8, 8, 8, 7, 3, 1, 8, 5, 0, 5, 2, 4, 8, 5, 1, 1, 0, 7, 9, 6, 5, 1, 2, 6, 6, 4, 7, 0, 9, 5, 6, 9, 3, 7, 8, 8, 8, 6, 5, 8, 3, 8, 5, 4, 5, 8, 5, 7, 5, 7, 3, 2, 8, 7, 1, 7, 1, 8, 7, 3, 3, 6, 2, 9, 3, 3, 9, 3, 1, 5, 1, 5, 5, 8, 1, 2, 7, 8, 9, 2, 5, 4, 5, 4, 2, 6, 1, 3, 6, 0, 6, 9, 6, 1, 0, 1, 4, 0, 4, 5, 5, 8, 2, 2, 6, 3, 4, 3, 4, 3, 8, 9, 7, 5, 5, 9, 1, 8, 5, 9, 9, 1, 8, 7, 2, 1, 1, 8, 1, 5, 6, 8, 5, 8, 0, 2, 4, 4, 7, 8, 9, 5, 9, 8, 0, 5, 0, 3, 5, 5, 2, 6, 8, 3, 4, 1, 4, 7, 1, 7, 2, 7, 5, 8, 8, 7, 2, 2, 3, 9, 2, 2, 7, 3, 2, 9, 0, 2, 3, 6, 9, 7, 2, 8, 0, 8, 1, 6, 5, 2, 3, 0, 2, 0, 0, 0, 9, 2, 2, 2, 3, 6, 6, 0, 9, 1, 0, 0, 3, 5, 8, 3, 2, 0, 3, 5, 1, 4, 1, 6, 8, 7, 6, 0, 9, 8, 0, 1, 0, 4, 5, 6, 0, 2, 8, 2, 5, 0, 2, 8, 5, 2, 3, 0, 2, 6, 7, 3, 0, 0, 2, 1, 9, 0, 1, 9, 9, 2, 0, 1, 6, 7, 7, 9, 9, 6, 1, 4, 8, 5, 5, 6, 7, 0, 6, 1, 7, 3, 5, 9, 3, 9, 0, 5, 9, 2, 4, 8, 6, 6, 2, 2, 3, 9, 3, 5, 7, 4, 1, 6, 9, 8, 2, 6, 9, 0, 0, 8, 5, 7, 7, 0, 6, 0, 5, 7, 4, 9, 6, 0, 7, 8, 4, 3, 9, 8, 8, 7, 4, 1, 5, 6, 0, 9, 4, 1, 9, 4, 9, 4, 1, 8, 6, 7, 8, 2, 5, 2, 3, 3, 4, 3, 3, 1, 6, 4, 1, 6, 1, 5, 7, 8, 1, 9, 7, 6, 0, 8, 0, 1, 4, 4, 0, 1, 1, 8, 3, 8, 3, 8, 3, 9, 1, 6, 0, 7, 1, 3, 3, 4, 9, 3, 5, 2, 4, 2, 0, 7, 3, 3, 8, 7, 7, 8, 8, 0, 9, 3, 1, 2, 2, 4, 3, 3, 3, 6, 1, 6, 9, 6, 2, 0, 1, 7, 5, 6, 2, 5, 3, 5, 0, 3, 2, 7, 2, 3, 0, 3, 6, 1, 7, 8, 7, 0, 4, 0, 6, 7, 6, 6, 3, 9, 8, 5, 8, 3, 3, 0, 9, 6, 7, 1, 9, 2, 1, 3, 5, 1, 6, 3, 4, 3, 4, 1, 6, 8, 4, 2, 5])
print(solu.superPow(a, b)) |
# -*- coding: utf-8 -*-
class MunicipalityRecord(object):
"""
The base document class.
Args:
fosnr (int): The unique id bfs of the municipality.
name (unicode): The zipcode for this address.
published (bool): Is this municipality ready for publishing via server.
logo (pyramid_oereb.lib.records.image.ImageRecord): The municipality logo.
geom (str or None): The geometry which is representing this municipality as a WKT.
"""
def __init__(self, fosnr, name, published, geom=None):
self.fosnr = fosnr
self.name = name
self.published = published
self.geom = geom
| class Municipalityrecord(object):
"""
The base document class.
Args:
fosnr (int): The unique id bfs of the municipality.
name (unicode): The zipcode for this address.
published (bool): Is this municipality ready for publishing via server.
logo (pyramid_oereb.lib.records.image.ImageRecord): The municipality logo.
geom (str or None): The geometry which is representing this municipality as a WKT.
"""
def __init__(self, fosnr, name, published, geom=None):
self.fosnr = fosnr
self.name = name
self.published = published
self.geom = geom |
"""The :func:`deephyper.nas.run.quick.run` function is a function used to check the good behaviour of a neural architecture search algorithm. It will simply return the sum of the scalar values encoding a neural architecture in the ``config["arch_seq"]`` key.
"""
def run(config: dict) -> float:
return sum(config['arch_seq'])
| """The :func:`deephyper.nas.run.quick.run` function is a function used to check the good behaviour of a neural architecture search algorithm. It will simply return the sum of the scalar values encoding a neural architecture in the ``config["arch_seq"]`` key.
"""
def run(config: dict) -> float:
return sum(config['arch_seq']) |
__all__ = [
"BoundHandler",
"ClassHook",
"Handler",
"Hook",
"Hookable",
"HookableMeta",
"HookDescriptor",
"InstanceHook",
"hookable",
]
| __all__ = ['BoundHandler', 'ClassHook', 'Handler', 'Hook', 'Hookable', 'HookableMeta', 'HookDescriptor', 'InstanceHook', 'hookable'] |
class gen_config(object):
vocab_size = 35000
train_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/"
data_dir = "/home/ssc/project/dataset/dataset/weibo/v0.0/"
buckets = [(5, 10), (10, 15), (20, 25), (40, 50)] | class Gen_Config(object):
vocab_size = 35000
train_dir = '/home/ssc/project/dataset/dataset/weibo/v0.0/'
data_dir = '/home/ssc/project/dataset/dataset/weibo/v0.0/'
buckets = [(5, 10), (10, 15), (20, 25), (40, 50)] |
"""
Problem
Given two rectangles, determine if they overlap. The rectangles are defined as a Dictionary:
r1 = {
# x and y coordinates of the bottom-left corner of the rectangle
'x': 2, 'y': 4,
# Width and Height of rectangle
'w': 5, 'h': 12
}
If the rectangles do overlap, return the dictionary which describes the overlapping section
"""
def calc_overlap(coord_1, dim_1, coord_2, dim_2):
greater = max(coord_1, coord_2)
lower = min(coord_1 + dim_1, coord_2 + dim_2)
if greater >= lower:
return None, None
overlap = lower - greater
return greater, overlap
def calc_rect_overlap(r1, r2):
x_overlap, w_overlap = calc_overlap(
r1['x'], r1['w'],
r2['x'], r2['w']
)
y_overlap, h_overlap = calc_overlap(
r1['y'], r1['h'],
r2['y'], r2['h']
)
if not w_overlap or not h_overlap:
print('No overlap')
return None
return {
'x': x_overlap,
'y': y_overlap,
'w': w_overlap,
'h': h_overlap
}
if __name__ == '__main__':
r1 = {'x': 2, 'y': 4, 'w': 5, 'h': 12}
r2 = {'x': 1, 'y': 5, 'w': 7, 'h': 14}
o = calc_rect_overlap(r1, r2)
print(o)
| """
Problem
Given two rectangles, determine if they overlap. The rectangles are defined as a Dictionary:
r1 = {
# x and y coordinates of the bottom-left corner of the rectangle
'x': 2, 'y': 4,
# Width and Height of rectangle
'w': 5, 'h': 12
}
If the rectangles do overlap, return the dictionary which describes the overlapping section
"""
def calc_overlap(coord_1, dim_1, coord_2, dim_2):
greater = max(coord_1, coord_2)
lower = min(coord_1 + dim_1, coord_2 + dim_2)
if greater >= lower:
return (None, None)
overlap = lower - greater
return (greater, overlap)
def calc_rect_overlap(r1, r2):
(x_overlap, w_overlap) = calc_overlap(r1['x'], r1['w'], r2['x'], r2['w'])
(y_overlap, h_overlap) = calc_overlap(r1['y'], r1['h'], r2['y'], r2['h'])
if not w_overlap or not h_overlap:
print('No overlap')
return None
return {'x': x_overlap, 'y': y_overlap, 'w': w_overlap, 'h': h_overlap}
if __name__ == '__main__':
r1 = {'x': 2, 'y': 4, 'w': 5, 'h': 12}
r2 = {'x': 1, 'y': 5, 'w': 7, 'h': 14}
o = calc_rect_overlap(r1, r2)
print(o) |
#!/usr/bin/env python
# Assumption for the star format:
# contain one or more 'data_*' blocks, for each block,
# either
'''
data_*
loop_
item1 #1
...
itemn #n
item1_data ... itemn_data
...
item1_data ... itemn_data
'''
# or
'''
data_*
item1 item1_data
...
itemn itemn_data
'''
def star_data(star):
# return 2 dict: {data1:line_num, data2:line_num}, {data1:lines, data2:lines}
data_dict = {}
with open(star) as read:
for i, line in enumerate(read.readlines()):
if line[:5] == 'data_':
line = line.strip()
data_dict[line] = i
# get an inverse dictionary
inv = {v: k for k, v in data_dict.items()}
# get the lines for each key
d_lines_dict = {}
with open(star) as read:
lines = read.readlines()
line_num = sorted(inv)
for i, num in enumerate(line_num):
try:
newline = line_num[i+1]
except IndexError:
newline = len(lines) + 1
d_lines_dict[inv[num]] = lines[num-1:newline-1]
return data_dict, d_lines_dict
def data_parse(d_lines):
# return a dict, whose keys are 'data_', ('loop_'), and items in 'data_'/'loop_'
item_dict = {}
if d_lines[3][:5] == 'loop_':
n = 4
else:
n = 3
item_dict['data_'] = d_lines[:n]
for i, line in enumerate(d_lines[n:]):
if line[:4] != '_rln': break
item_dict['loop_'] = d_lines[n:n+i]
for j in item_dict['loop_']:
k, v = j.split()
# change the value to an integer and minus 1, to be convenient
if n == 4:
item_dict[k] = int(v.strip('#')) - 1
elif n == 3:
item_dict[k] = v.strip()
return item_dict
def star_parse(star, data):
# parse a star file containing the data label.
# return a dict, whose keys are 'data_', ('loop_'), and items in 'data_'/'loop_'
d_lines = star_data(star)[1][data]
return data_parse(d_lines)
| """
data_*
loop_
item1 #1
...
itemn #n
item1_data ... itemn_data
...
item1_data ... itemn_data
"""
'\n\ndata_*\n\nitem1 item1_data\n...\nitemn itemn_data\n\n'
def star_data(star):
data_dict = {}
with open(star) as read:
for (i, line) in enumerate(read.readlines()):
if line[:5] == 'data_':
line = line.strip()
data_dict[line] = i
inv = {v: k for (k, v) in data_dict.items()}
d_lines_dict = {}
with open(star) as read:
lines = read.readlines()
line_num = sorted(inv)
for (i, num) in enumerate(line_num):
try:
newline = line_num[i + 1]
except IndexError:
newline = len(lines) + 1
d_lines_dict[inv[num]] = lines[num - 1:newline - 1]
return (data_dict, d_lines_dict)
def data_parse(d_lines):
item_dict = {}
if d_lines[3][:5] == 'loop_':
n = 4
else:
n = 3
item_dict['data_'] = d_lines[:n]
for (i, line) in enumerate(d_lines[n:]):
if line[:4] != '_rln':
break
item_dict['loop_'] = d_lines[n:n + i]
for j in item_dict['loop_']:
(k, v) = j.split()
if n == 4:
item_dict[k] = int(v.strip('#')) - 1
elif n == 3:
item_dict[k] = v.strip()
return item_dict
def star_parse(star, data):
d_lines = star_data(star)[1][data]
return data_parse(d_lines) |
def get_book_info(book_id, books):
"""Obtain meta data of certain books.
:param book_id: Books to look up
:type: int or list of ints
:param books: Dataframe containing the meta data
:type: pandas dataframe
:return: Meta data for the book ids
:rtype: List[str], List[str], List[str]
"""
if not isinstance(book_id, list):
book_id = [book_id]
book_authors, book_titles, book_img_urls = [], [], []
for i in book_id:
book_info = books.loc[books["book_id"]==i].squeeze()
if book_info.shape[0]==0:
raise ValueError("Could not find book_id {} in the dataset.".format(book_id))
book_authors.append(book_info.authors)
book_titles.append(book_info.title)
book_img_urls.append(book_info.image_url)
return book_authors, book_titles, book_img_urls
def get_books_liked_by_user(user_id, user_book_rating, min_rating):
"""Get books which the user liked.
:param user_id: User for which the closest neighbor will be find
:type: int
:param user_book_rating: Ratings of each user for each book read
:type: pandas dataframe with cols ["user_id", "book_id", "rating"]
:param min_rating: Minimal rating that defines if a user liked a book
:type: int
:return: Books which got at least the minimal rating by the user
:rtype: List of ints
"""
user2_book_rating = user_book_rating[user_book_rating["user_id"]==user_id]
books_liked = user2_book_rating[user2_book_rating["rating"] >= min_rating]["book_id"].to_list()
return books_liked
def find_in_string(sub, string):
"""Check if a substring is contained in another string.
:param sub: Substring
:type: str
:param string: String which is checked if the substring is contained
:type: str
:return: Result if the substring is contained in the string
:rtype: boolean
"""
sub_l = sub.lower()
string_l = string.lower()
if sub_l in string_l or string_l in sub_l:
return 1
else:
return 0
def find_book_ids(books, author=None, title=None):
"""Find books by author and/or title in the dataset.
:param books: Dataframe containing the meta data
:type: pandas dataframe
:param author: Author to look up
:type: str
:param title: Title to look up
:type: str
:param dist_th
"""
if not author and not title:
print("Please add an author and/or a title.")
else:
book_candidates = []
all_authors = books["authors"].to_list()
all_titles = books["title"].to_list()
if author is not None:
# find all books with this author
for idx, a in enumerate(all_authors):
if find_in_string(author, a):
book_candidates.append(books.iloc[idx]["book_id"])
# iterate over books from author
relevant_book_ids = book_candidates.copy()
if title:
titles_from_author = []
for book_id in book_candidates:
t = books.loc[books["book_id"]==book_id].squeeze().title
if not find_in_string(t, title):
relevant_book_ids.remove(book_id)
else:
# if author is not given, go only through titles
relevant_book_ids = []
for idx, t in enumerate(all_titles):
if find_in_string(title, t):
relevant_book_ids.append(books.iloc[idx]["book_id"])
return relevant_book_ids | def get_book_info(book_id, books):
"""Obtain meta data of certain books.
:param book_id: Books to look up
:type: int or list of ints
:param books: Dataframe containing the meta data
:type: pandas dataframe
:return: Meta data for the book ids
:rtype: List[str], List[str], List[str]
"""
if not isinstance(book_id, list):
book_id = [book_id]
(book_authors, book_titles, book_img_urls) = ([], [], [])
for i in book_id:
book_info = books.loc[books['book_id'] == i].squeeze()
if book_info.shape[0] == 0:
raise value_error('Could not find book_id {} in the dataset.'.format(book_id))
book_authors.append(book_info.authors)
book_titles.append(book_info.title)
book_img_urls.append(book_info.image_url)
return (book_authors, book_titles, book_img_urls)
def get_books_liked_by_user(user_id, user_book_rating, min_rating):
"""Get books which the user liked.
:param user_id: User for which the closest neighbor will be find
:type: int
:param user_book_rating: Ratings of each user for each book read
:type: pandas dataframe with cols ["user_id", "book_id", "rating"]
:param min_rating: Minimal rating that defines if a user liked a book
:type: int
:return: Books which got at least the minimal rating by the user
:rtype: List of ints
"""
user2_book_rating = user_book_rating[user_book_rating['user_id'] == user_id]
books_liked = user2_book_rating[user2_book_rating['rating'] >= min_rating]['book_id'].to_list()
return books_liked
def find_in_string(sub, string):
"""Check if a substring is contained in another string.
:param sub: Substring
:type: str
:param string: String which is checked if the substring is contained
:type: str
:return: Result if the substring is contained in the string
:rtype: boolean
"""
sub_l = sub.lower()
string_l = string.lower()
if sub_l in string_l or string_l in sub_l:
return 1
else:
return 0
def find_book_ids(books, author=None, title=None):
"""Find books by author and/or title in the dataset.
:param books: Dataframe containing the meta data
:type: pandas dataframe
:param author: Author to look up
:type: str
:param title: Title to look up
:type: str
:param dist_th
"""
if not author and (not title):
print('Please add an author and/or a title.')
else:
book_candidates = []
all_authors = books['authors'].to_list()
all_titles = books['title'].to_list()
if author is not None:
for (idx, a) in enumerate(all_authors):
if find_in_string(author, a):
book_candidates.append(books.iloc[idx]['book_id'])
relevant_book_ids = book_candidates.copy()
if title:
titles_from_author = []
for book_id in book_candidates:
t = books.loc[books['book_id'] == book_id].squeeze().title
if not find_in_string(t, title):
relevant_book_ids.remove(book_id)
else:
relevant_book_ids = []
for (idx, t) in enumerate(all_titles):
if find_in_string(title, t):
relevant_book_ids.append(books.iloc[idx]['book_id'])
return relevant_book_ids |
#
# PySNMP MIB module TRANGOP5830S-RU-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRANGOP5830S-RU-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:19:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, iso, Unsigned32, Counter64, enterprises, ObjectIdentity, MibIdentifier, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, Counter32, Gauge32, IpAddress, ModuleIdentity, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "iso", "Unsigned32", "Counter64", "enterprises", "ObjectIdentity", "MibIdentifier", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "Counter32", "Gauge32", "IpAddress", "ModuleIdentity", "TimeTicks")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class DisplayString(OctetString):
pass
trango = MibIdentifier((1, 3, 6, 1, 4, 1, 5454))
tbw = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1))
p5830sru = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24))
rusys = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1))
rurf = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2))
mibinfo = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 5))
ruversion = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1))
ruswitches = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8))
rutraffic = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9))
ruipconfig = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13))
rurftable = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4))
ruism = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5))
ruunii = MibIdentifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6))
ruversionHW = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruversionHW.setStatus('mandatory')
ruversionFW = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 80))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruversionFW.setStatus('mandatory')
ruversionFPGA = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(4, 4)).setFixedLength(4)).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruversionFPGA.setStatus('mandatory')
ruversionFWChecksum = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(4, 4)).setFixedLength(4)).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruversionFWChecksum.setStatus('mandatory')
ruversionFPGAChecksum = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(4, 4)).setFixedLength(4)).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruversionFPGAChecksum.setStatus('mandatory')
rusysDeviceId = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(6, 6)).setFixedLength(6)).setMaxAccess("readonly")
if mibBuilder.loadTexts: rusysDeviceId.setStatus('mandatory')
rusysDefOpMode = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(16, 0))).clone(namedValues=NamedValues(("on", 16), ("off", 0)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rusysDefOpMode.setStatus('mandatory')
rusysCurOpMode = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(16, 0))).clone(namedValues=NamedValues(("on", 16), ("off", 0)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rusysCurOpMode.setStatus('mandatory')
rusysActivateOpmode = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("deactivated", 0), ("activated", 1))).clone('deactivated')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rusysActivateOpmode.setStatus('mandatory')
rusysReadCommStr = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 6), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rusysReadCommStr.setStatus('mandatory')
rusysWriteCommStr = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rusysWriteCommStr.setStatus('mandatory')
ruswitchesBlockBroadcastMulticast = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("passed", 0), ("blocked", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruswitchesBlockBroadcastMulticast.setStatus('mandatory')
ruswitchesHTTPD = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruswitchesHTTPD.setStatus('mandatory')
ruswitchesAutoScanMasterSignal = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruswitchesAutoScanMasterSignal.setStatus('mandatory')
rutrafficEthInOctets = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rutrafficEthInOctets.setStatus('mandatory')
rutrafficEthOutOctets = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rutrafficEthOutOctets.setStatus('mandatory')
rutrafficRfInOctets = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rutrafficRfInOctets.setStatus('mandatory')
rutrafficRfOutOctets = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rutrafficRfOutOctets.setStatus('mandatory')
rusysTemperature = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rusysTemperature.setStatus('mandatory')
rusysUpdateFlashAndActivate = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("no", 0), ("yes", 1))).clone('no')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rusysUpdateFlashAndActivate.setStatus('mandatory')
rusysReboot = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("deactivated", 0), ("activated", 1))).clone('deactivated')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rusysReboot.setStatus('mandatory')
ruipconfigIpAddress = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13, 1), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruipconfigIpAddress.setStatus('mandatory')
ruipconfigSubnet = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13, 2), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruipconfigSubnet.setStatus('mandatory')
ruipconfigDefaultGateway = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13, 3), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruipconfigDefaultGateway.setStatus('mandatory')
rurfRSSI = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: rurfRSSI.setStatus('mandatory')
rurftableChannel1 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel1.setStatus('mandatory')
rurftableChannel2 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel2.setStatus('mandatory')
rurftableChannel3 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel3.setStatus('mandatory')
rurftableChannel4 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel4.setStatus('mandatory')
rurftableChannel5 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel5.setStatus('mandatory')
rurftableChannel6 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel6.setStatus('mandatory')
rurftableChannel7 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel7.setStatus('mandatory')
rurftableChannel8 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel8.setStatus('mandatory')
rurftableChannel9 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel9.setStatus('mandatory')
rurftableChannel10 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel10.setStatus('mandatory')
rurftableChannel11 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel11.setStatus('mandatory')
rurftableChannel12 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel12.setStatus('mandatory')
rurftableChannel13 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel13.setStatus('mandatory')
rurftableChannel14 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel14.setStatus('mandatory')
rurftableChannel15 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel15.setStatus('mandatory')
rurftableChannel16 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel16.setStatus('mandatory')
rurftableChannel17 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel17.setStatus('mandatory')
rurftableChannel18 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel18.setStatus('mandatory')
rurftableChannel19 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel19.setStatus('mandatory')
rurftableChannel20 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel20.setStatus('mandatory')
rurftableChannel21 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel21.setStatus('mandatory')
rurftableChannel22 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel22.setStatus('mandatory')
rurftableChannel23 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 23), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel23.setStatus('mandatory')
rurftableChannel24 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel24.setStatus('mandatory')
rurftableChannel25 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 25), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel25.setStatus('mandatory')
rurftableChannel26 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel26.setStatus('mandatory')
rurftableChannel27 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel27.setStatus('mandatory')
rurftableChannel28 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel28.setStatus('mandatory')
rurftableChannel29 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel29.setStatus('mandatory')
rurftableChannel30 = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(5260, 5340), ValueRangeConstraint(5736, 5836), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rurftableChannel30.setStatus('mandatory')
ruismTxPowerMax = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruismTxPowerMax.setStatus('mandatory')
ruismTxPowerMin = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruismTxPowerMin.setStatus('mandatory')
ruismTxPower = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruismTxPower.setStatus('mandatory')
ruismRxThreshold = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-90, -90), ValueRangeConstraint(-85, -85), ValueRangeConstraint(-80, -80), ValueRangeConstraint(-75, -75), ValueRangeConstraint(-70, -70), ValueRangeConstraint(-65, -65), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruismRxThreshold.setStatus('mandatory')
ruuniiTxPowerMax = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruuniiTxPowerMax.setStatus('mandatory')
ruuniiTxPowerMin = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ruuniiTxPowerMin.setStatus('mandatory')
ruuniiTxPower = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-128, 127))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruuniiTxPower.setStatus('mandatory')
ruuniiRxThreshold = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(-90, -90), ValueRangeConstraint(-85, -85), ValueRangeConstraint(-80, -80), ValueRangeConstraint(-75, -75), ValueRangeConstraint(-70, -70), ValueRangeConstraint(-65, -65), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ruuniiRxThreshold.setStatus('mandatory')
mibinfoVersion = MibScalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 5, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mibinfoVersion.setStatus('mandatory')
mibBuilder.exportSymbols("TRANGOP5830S-RU-MIB", mibinfo=mibinfo, rurftableChannel9=rurftableChannel9, ruswitchesAutoScanMasterSignal=ruswitchesAutoScanMasterSignal, ruversionFWChecksum=ruversionFWChecksum, rusysActivateOpmode=rusysActivateOpmode, ruversionHW=ruversionHW, rurftableChannel24=rurftableChannel24, rurftableChannel27=rurftableChannel27, rurftableChannel2=rurftableChannel2, rutrafficEthInOctets=rutrafficEthInOctets, rurftableChannel14=rurftableChannel14, ruismTxPowerMax=ruismTxPowerMax, rusys=rusys, ruunii=ruunii, rurftableChannel15=rurftableChannel15, rusysCurOpMode=rusysCurOpMode, rurftableChannel5=rurftableChannel5, rurftableChannel11=rurftableChannel11, ruversionFPGAChecksum=ruversionFPGAChecksum, rurftableChannel12=rurftableChannel12, rusysDeviceId=rusysDeviceId, rurftableChannel25=rurftableChannel25, ruswitches=ruswitches, ruismTxPowerMin=ruismTxPowerMin, ruuniiTxPower=ruuniiTxPower, ruversionFPGA=ruversionFPGA, rurftableChannel8=rurftableChannel8, p5830sru=p5830sru, rutrafficRfInOctets=rutrafficRfInOctets, ruismTxPower=ruismTxPower, rusysReboot=rusysReboot, rusysUpdateFlashAndActivate=rusysUpdateFlashAndActivate, rurftableChannel4=rurftableChannel4, rurftable=rurftable, rurftableChannel6=rurftableChannel6, rurftableChannel16=rurftableChannel16, rusysReadCommStr=rusysReadCommStr, ruversionFW=ruversionFW, ruswitchesBlockBroadcastMulticast=ruswitchesBlockBroadcastMulticast, rurftableChannel30=rurftableChannel30, rurftableChannel18=rurftableChannel18, ruipconfig=ruipconfig, ruismRxThreshold=ruismRxThreshold, rurftableChannel28=rurftableChannel28, rurftableChannel10=rurftableChannel10, rutraffic=rutraffic, rurftableChannel13=rurftableChannel13, rurftableChannel3=rurftableChannel3, ruuniiTxPowerMax=ruuniiTxPowerMax, rusysTemperature=rusysTemperature, rusysWriteCommStr=rusysWriteCommStr, rurftableChannel22=rurftableChannel22, mibinfoVersion=mibinfoVersion, tbw=tbw, ruipconfigDefaultGateway=ruipconfigDefaultGateway, rurftableChannel17=rurftableChannel17, ruswitchesHTTPD=ruswitchesHTTPD, rurftableChannel21=rurftableChannel21, ruipconfigIpAddress=ruipconfigIpAddress, ruuniiTxPowerMin=ruuniiTxPowerMin, rurftableChannel26=rurftableChannel26, ruism=ruism, rurftableChannel19=rurftableChannel19, trango=trango, rurfRSSI=rurfRSSI, rutrafficRfOutOctets=rutrafficRfOutOctets, rurftableChannel23=rurftableChannel23, rutrafficEthOutOctets=rutrafficEthOutOctets, ruversion=ruversion, rurftableChannel20=rurftableChannel20, rurftableChannel1=rurftableChannel1, DisplayString=DisplayString, ruipconfigSubnet=ruipconfigSubnet, rurftableChannel7=rurftableChannel7, rurftableChannel29=rurftableChannel29, rusysDefOpMode=rusysDefOpMode, rurf=rurf, ruuniiRxThreshold=ruuniiRxThreshold)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_union, value_range_constraint, constraints_intersection, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(integer32, iso, unsigned32, counter64, enterprises, object_identity, mib_identifier, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, counter32, gauge32, ip_address, module_identity, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'iso', 'Unsigned32', 'Counter64', 'enterprises', 'ObjectIdentity', 'MibIdentifier', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'Counter32', 'Gauge32', 'IpAddress', 'ModuleIdentity', 'TimeTicks')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
class Displaystring(OctetString):
pass
trango = mib_identifier((1, 3, 6, 1, 4, 1, 5454))
tbw = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1))
p5830sru = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24))
rusys = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1))
rurf = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2))
mibinfo = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 5))
ruversion = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1))
ruswitches = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8))
rutraffic = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9))
ruipconfig = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13))
rurftable = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4))
ruism = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5))
ruunii = mib_identifier((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6))
ruversion_hw = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 1), octet_string().subtype(subtypeSpec=value_size_constraint(2, 2)).setFixedLength(2)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruversionHW.setStatus('mandatory')
ruversion_fw = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 80))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruversionFW.setStatus('mandatory')
ruversion_fpga = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(4, 4)).setFixedLength(4)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruversionFPGA.setStatus('mandatory')
ruversion_fw_checksum = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 4), octet_string().subtype(subtypeSpec=value_size_constraint(4, 4)).setFixedLength(4)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruversionFWChecksum.setStatus('mandatory')
ruversion_fpga_checksum = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 1, 5), octet_string().subtype(subtypeSpec=value_size_constraint(4, 4)).setFixedLength(4)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruversionFPGAChecksum.setStatus('mandatory')
rusys_device_id = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 2), octet_string().subtype(subtypeSpec=value_size_constraint(6, 6)).setFixedLength(6)).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rusysDeviceId.setStatus('mandatory')
rusys_def_op_mode = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(16, 0))).clone(namedValues=named_values(('on', 16), ('off', 0)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rusysDefOpMode.setStatus('mandatory')
rusys_cur_op_mode = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(16, 0))).clone(namedValues=named_values(('on', 16), ('off', 0)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rusysCurOpMode.setStatus('mandatory')
rusys_activate_opmode = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('deactivated', 0), ('activated', 1))).clone('deactivated')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rusysActivateOpmode.setStatus('mandatory')
rusys_read_comm_str = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 6), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rusysReadCommStr.setStatus('mandatory')
rusys_write_comm_str = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 7), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rusysWriteCommStr.setStatus('mandatory')
ruswitches_block_broadcast_multicast = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('passed', 0), ('blocked', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruswitchesBlockBroadcastMulticast.setStatus('mandatory')
ruswitches_httpd = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disabled', 0), ('enabled', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruswitchesHTTPD.setStatus('mandatory')
ruswitches_auto_scan_master_signal = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 8, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disabled', 0), ('enabled', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruswitchesAutoScanMasterSignal.setStatus('mandatory')
rutraffic_eth_in_octets = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rutrafficEthInOctets.setStatus('mandatory')
rutraffic_eth_out_octets = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rutrafficEthOutOctets.setStatus('mandatory')
rutraffic_rf_in_octets = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rutrafficRfInOctets.setStatus('mandatory')
rutraffic_rf_out_octets = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 9, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rutrafficRfOutOctets.setStatus('mandatory')
rusys_temperature = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rusysTemperature.setStatus('mandatory')
rusys_update_flash_and_activate = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('no', 0), ('yes', 1))).clone('no')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rusysUpdateFlashAndActivate.setStatus('mandatory')
rusys_reboot = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('deactivated', 0), ('activated', 1))).clone('deactivated')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rusysReboot.setStatus('mandatory')
ruipconfig_ip_address = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13, 1), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruipconfigIpAddress.setStatus('mandatory')
ruipconfig_subnet = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13, 2), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruipconfigSubnet.setStatus('mandatory')
ruipconfig_default_gateway = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 1, 13, 3), ip_address()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruipconfigDefaultGateway.setStatus('mandatory')
rurf_rssi = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 1), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rurfRSSI.setStatus('mandatory')
rurftable_channel1 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 1), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel1.setStatus('mandatory')
rurftable_channel2 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 2), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel2.setStatus('mandatory')
rurftable_channel3 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 3), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel3.setStatus('mandatory')
rurftable_channel4 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 4), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel4.setStatus('mandatory')
rurftable_channel5 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 5), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel5.setStatus('mandatory')
rurftable_channel6 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 6), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel6.setStatus('mandatory')
rurftable_channel7 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 7), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel7.setStatus('mandatory')
rurftable_channel8 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 8), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel8.setStatus('mandatory')
rurftable_channel9 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 9), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel9.setStatus('mandatory')
rurftable_channel10 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 10), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel10.setStatus('mandatory')
rurftable_channel11 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 11), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel11.setStatus('mandatory')
rurftable_channel12 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 12), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel12.setStatus('mandatory')
rurftable_channel13 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 13), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel13.setStatus('mandatory')
rurftable_channel14 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 14), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel14.setStatus('mandatory')
rurftable_channel15 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 15), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel15.setStatus('mandatory')
rurftable_channel16 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 16), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel16.setStatus('mandatory')
rurftable_channel17 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 17), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel17.setStatus('mandatory')
rurftable_channel18 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 18), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel18.setStatus('mandatory')
rurftable_channel19 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 19), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel19.setStatus('mandatory')
rurftable_channel20 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 20), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel20.setStatus('mandatory')
rurftable_channel21 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 21), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel21.setStatus('mandatory')
rurftable_channel22 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 22), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel22.setStatus('mandatory')
rurftable_channel23 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 23), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel23.setStatus('mandatory')
rurftable_channel24 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 24), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel24.setStatus('mandatory')
rurftable_channel25 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 25), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel25.setStatus('mandatory')
rurftable_channel26 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 26), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel26.setStatus('mandatory')
rurftable_channel27 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 27), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel27.setStatus('mandatory')
rurftable_channel28 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 28), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel28.setStatus('mandatory')
rurftable_channel29 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 29), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel29.setStatus('mandatory')
rurftable_channel30 = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 4, 30), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(5260, 5340), value_range_constraint(5736, 5836)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rurftableChannel30.setStatus('mandatory')
ruism_tx_power_max = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 1), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruismTxPowerMax.setStatus('mandatory')
ruism_tx_power_min = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 2), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruismTxPowerMin.setStatus('mandatory')
ruism_tx_power = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 3), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruismTxPower.setStatus('mandatory')
ruism_rx_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 5, 4), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(-90, -90), value_range_constraint(-85, -85), value_range_constraint(-80, -80), value_range_constraint(-75, -75), value_range_constraint(-70, -70), value_range_constraint(-65, -65)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruismRxThreshold.setStatus('mandatory')
ruunii_tx_power_max = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 1), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruuniiTxPowerMax.setStatus('mandatory')
ruunii_tx_power_min = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 2), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ruuniiTxPowerMin.setStatus('mandatory')
ruunii_tx_power = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 3), integer32().subtype(subtypeSpec=value_range_constraint(-128, 127))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruuniiTxPower.setStatus('mandatory')
ruunii_rx_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 2, 6, 4), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(-90, -90), value_range_constraint(-85, -85), value_range_constraint(-80, -80), value_range_constraint(-75, -75), value_range_constraint(-70, -70), value_range_constraint(-65, -65)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ruuniiRxThreshold.setStatus('mandatory')
mibinfo_version = mib_scalar((1, 3, 6, 1, 4, 1, 5454, 1, 24, 5, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mibinfoVersion.setStatus('mandatory')
mibBuilder.exportSymbols('TRANGOP5830S-RU-MIB', mibinfo=mibinfo, rurftableChannel9=rurftableChannel9, ruswitchesAutoScanMasterSignal=ruswitchesAutoScanMasterSignal, ruversionFWChecksum=ruversionFWChecksum, rusysActivateOpmode=rusysActivateOpmode, ruversionHW=ruversionHW, rurftableChannel24=rurftableChannel24, rurftableChannel27=rurftableChannel27, rurftableChannel2=rurftableChannel2, rutrafficEthInOctets=rutrafficEthInOctets, rurftableChannel14=rurftableChannel14, ruismTxPowerMax=ruismTxPowerMax, rusys=rusys, ruunii=ruunii, rurftableChannel15=rurftableChannel15, rusysCurOpMode=rusysCurOpMode, rurftableChannel5=rurftableChannel5, rurftableChannel11=rurftableChannel11, ruversionFPGAChecksum=ruversionFPGAChecksum, rurftableChannel12=rurftableChannel12, rusysDeviceId=rusysDeviceId, rurftableChannel25=rurftableChannel25, ruswitches=ruswitches, ruismTxPowerMin=ruismTxPowerMin, ruuniiTxPower=ruuniiTxPower, ruversionFPGA=ruversionFPGA, rurftableChannel8=rurftableChannel8, p5830sru=p5830sru, rutrafficRfInOctets=rutrafficRfInOctets, ruismTxPower=ruismTxPower, rusysReboot=rusysReboot, rusysUpdateFlashAndActivate=rusysUpdateFlashAndActivate, rurftableChannel4=rurftableChannel4, rurftable=rurftable, rurftableChannel6=rurftableChannel6, rurftableChannel16=rurftableChannel16, rusysReadCommStr=rusysReadCommStr, ruversionFW=ruversionFW, ruswitchesBlockBroadcastMulticast=ruswitchesBlockBroadcastMulticast, rurftableChannel30=rurftableChannel30, rurftableChannel18=rurftableChannel18, ruipconfig=ruipconfig, ruismRxThreshold=ruismRxThreshold, rurftableChannel28=rurftableChannel28, rurftableChannel10=rurftableChannel10, rutraffic=rutraffic, rurftableChannel13=rurftableChannel13, rurftableChannel3=rurftableChannel3, ruuniiTxPowerMax=ruuniiTxPowerMax, rusysTemperature=rusysTemperature, rusysWriteCommStr=rusysWriteCommStr, rurftableChannel22=rurftableChannel22, mibinfoVersion=mibinfoVersion, tbw=tbw, ruipconfigDefaultGateway=ruipconfigDefaultGateway, rurftableChannel17=rurftableChannel17, ruswitchesHTTPD=ruswitchesHTTPD, rurftableChannel21=rurftableChannel21, ruipconfigIpAddress=ruipconfigIpAddress, ruuniiTxPowerMin=ruuniiTxPowerMin, rurftableChannel26=rurftableChannel26, ruism=ruism, rurftableChannel19=rurftableChannel19, trango=trango, rurfRSSI=rurfRSSI, rutrafficRfOutOctets=rutrafficRfOutOctets, rurftableChannel23=rurftableChannel23, rutrafficEthOutOctets=rutrafficEthOutOctets, ruversion=ruversion, rurftableChannel20=rurftableChannel20, rurftableChannel1=rurftableChannel1, DisplayString=DisplayString, ruipconfigSubnet=ruipconfigSubnet, rurftableChannel7=rurftableChannel7, rurftableChannel29=rurftableChannel29, rusysDefOpMode=rusysDefOpMode, rurf=rurf, ruuniiRxThreshold=ruuniiRxThreshold) |
class CarrinhoCompras:
def __init__(self):
self.produtos = []
def insere_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
for produto in self.produtos:
total += produto.valor
return total
class Produto:
def __init__(self, nome, valor):
self.nome = nome
self.valor = valor
carrinho = CarrinhoCompras()
prod1 = Produto("camisa", 50)
prod2 = Produto("short", 90)
prod3 = Produto("meias", 25)
carrinho.insere_produto(prod1)
carrinho.insere_produto(prod2)
carrinho.insere_produto(prod3)
carrinho.insere_produto(prod1)
carrinho.lista_produtos()
print(carrinho.soma_total())
| class Carrinhocompras:
def __init__(self):
self.produtos = []
def insere_produto(self, produto):
self.produtos.append(produto)
def lista_produtos(self):
for produto in self.produtos:
print(produto.nome, produto.valor)
def soma_total(self):
total = 0
for produto in self.produtos:
total += produto.valor
return total
class Produto:
def __init__(self, nome, valor):
self.nome = nome
self.valor = valor
carrinho = carrinho_compras()
prod1 = produto('camisa', 50)
prod2 = produto('short', 90)
prod3 = produto('meias', 25)
carrinho.insere_produto(prod1)
carrinho.insere_produto(prod2)
carrinho.insere_produto(prod3)
carrinho.insere_produto(prod1)
carrinho.lista_produtos()
print(carrinho.soma_total()) |
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '8.3.beta3'
date = '2018-05-27'
| version = '8.3.beta3'
date = '2018-05-27' |
class Judge:
PAPER_LIMIT = 7
def __init__(
self,
judge_id,
first,
last,
email,
phone,
preferred_categories,
is_paper_reviewer,
presentation_availability,
):
self.judge_id = judge_id # int
self.first = first # str
self.last = last # str
self.email = email # str
self.phone = phone # str
self.preferred_categories = preferred_categories # list of int
self.is_paper_reviewer = is_paper_reviewer # bool
self.presentation_availability = presentation_availability # list of float
self.presentation_slots = len(self.presentation_availability) # int
self.assigned_presentations = [] # list of Student
self.assigned_times = [] # list of float
self.assigned_papers = [] # list of Student
def __eq__(self, other):
return self.judge_id == other.judge_id
def assign_presentation(self, student, time_index=None):
if not self.presentation_slots:
raise Exception("No slots available")
if len(student.presentation_judges) >= 2:
raise Exception("Too many presentation judges")
if (
len(student.presentation_judges) == 1
and student.presentation_judges[0] == self
):
raise Exception("Trying to add same judge twice")
self.presentation_slots -= 1
self.assigned_presentations.append(student)
if not time_index:
time_index = self.presentation_availability[self.presentation_slots]
self.assigned_times.append(time_index)
student.presentation_judges.append(self)
student.presentation_time = time_index
def assign_paper(self, student):
# if len(self.assigned_papers) >= self.PAPER_LIMIT:
# raise Exception("Paper limit reached")
if len(student.paper_judges) >= 2:
raise Exception("Too many paper judges")
if len(student.paper_judges) == 1 and student.paper_judges[0] == self:
raise Exception("Trying to add same judge twice")
self.assigned_papers.append(student)
student.paper_judges.append(self)
def __str__(self):
return f"{self.first} {self.last}"
# return "\n".join(
# [f"{field}: {value}" for field, value in self.__dict__.items()]
# )
| class Judge:
paper_limit = 7
def __init__(self, judge_id, first, last, email, phone, preferred_categories, is_paper_reviewer, presentation_availability):
self.judge_id = judge_id
self.first = first
self.last = last
self.email = email
self.phone = phone
self.preferred_categories = preferred_categories
self.is_paper_reviewer = is_paper_reviewer
self.presentation_availability = presentation_availability
self.presentation_slots = len(self.presentation_availability)
self.assigned_presentations = []
self.assigned_times = []
self.assigned_papers = []
def __eq__(self, other):
return self.judge_id == other.judge_id
def assign_presentation(self, student, time_index=None):
if not self.presentation_slots:
raise exception('No slots available')
if len(student.presentation_judges) >= 2:
raise exception('Too many presentation judges')
if len(student.presentation_judges) == 1 and student.presentation_judges[0] == self:
raise exception('Trying to add same judge twice')
self.presentation_slots -= 1
self.assigned_presentations.append(student)
if not time_index:
time_index = self.presentation_availability[self.presentation_slots]
self.assigned_times.append(time_index)
student.presentation_judges.append(self)
student.presentation_time = time_index
def assign_paper(self, student):
if len(student.paper_judges) >= 2:
raise exception('Too many paper judges')
if len(student.paper_judges) == 1 and student.paper_judges[0] == self:
raise exception('Trying to add same judge twice')
self.assigned_papers.append(student)
student.paper_judges.append(self)
def __str__(self):
return f'{self.first} {self.last}' |
class dispatcher:
name = 'dispatcher'
def __init__(self, function_to_exec):
self.function = function_to_exec
return self.function
def get_name(self):
return self.name
def function_one(a,b):
return a + b
def function_two():
return 'function two' | class Dispatcher:
name = 'dispatcher'
def __init__(self, function_to_exec):
self.function = function_to_exec
return self.function
def get_name(self):
return self.name
def function_one(a, b):
return a + b
def function_two():
return 'function two' |
"""
ice_pick.exceptions
~~~~~~~~~~~~~~~~~~~
This module implements contains the Ice Pick exceptions.
Copyright 2014 Demand Media.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class APIRequestException(Exception):
def __init__(self, request_method, request_url, status_code):
msg = '%s request to %s returned status %d' % (request_method,
request_url,
status_code)
super(Exception, self).__init__(msg)
| """
ice_pick.exceptions
~~~~~~~~~~~~~~~~~~~
This module implements contains the Ice Pick exceptions.
Copyright 2014 Demand Media.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
class Apirequestexception(Exception):
def __init__(self, request_method, request_url, status_code):
msg = '%s request to %s returned status %d' % (request_method, request_url, status_code)
super(Exception, self).__init__(msg) |
class UniformExchange(object):
def __init__(self, A):
if not isinstance(A, (float, int)) or A <= 0:
raise ValueError('Exchange constant must be positive float/int.')
else:
self.A = A
def get_mif(self):
# Create mif string.
mif = '# UniformExchange\n'
mif += 'Specify Oxs_UniformExchange {\n'
mif += '\tA {}\n'.format(self.A)
mif += '}\n\n'
return mif
| class Uniformexchange(object):
def __init__(self, A):
if not isinstance(A, (float, int)) or A <= 0:
raise value_error('Exchange constant must be positive float/int.')
else:
self.A = A
def get_mif(self):
mif = '# UniformExchange\n'
mif += 'Specify Oxs_UniformExchange {\n'
mif += '\tA {}\n'.format(self.A)
mif += '}\n\n'
return mif |
# model
model = Model()
i1 = Input("op1", "TENSOR_QUANT8_ASYMM", "{1, 2, 2, 1}, 0.8, 5")
i2 = Output("op2", "TENSOR_QUANT8_ASYMM", "{1, 3, 3, 1}, 0.8, 5")
w = Int32Scalar("width", 3)
h = Int32Scalar("height", 3)
model = model.Operation("RESIZE_BILINEAR", i1, w, h).To(i2)
# Example 1. Input in operand 0,
input0 = {i1: # input 0
[1, 1, 2, 2]}
output0 = {i2: # output 0
[1, 1, 1,
2, 2, 2,
2, 2, 2]}
# Instantiate an example
Example((input0, output0))
| model = model()
i1 = input('op1', 'TENSOR_QUANT8_ASYMM', '{1, 2, 2, 1}, 0.8, 5')
i2 = output('op2', 'TENSOR_QUANT8_ASYMM', '{1, 3, 3, 1}, 0.8, 5')
w = int32_scalar('width', 3)
h = int32_scalar('height', 3)
model = model.Operation('RESIZE_BILINEAR', i1, w, h).To(i2)
input0 = {i1: [1, 1, 2, 2]}
output0 = {i2: [1, 1, 1, 2, 2, 2, 2, 2, 2]}
example((input0, output0)) |
def add(a, b):
print(f"ADDING {a} + {b}")
return a + b
def subtract(a, b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a, b):
print(f"MULTIPLYING {a} * {b}")
return a * b
def divide(a, b):
print(f"DIVIDING {a} / {b}")
return a / b
a = float(input("input a:"))
b = float(input("input b:"))
c = float(input("input c:"))
d = float(input("input d:"))
e = float(input("input e:"))
print("calculate (a+b)*c-(d/e)")
print("Directly:",(a+b)*c-(d/e))
print("Using the functions:", subtract(multiply(add(a,b),c), divide(d, e)))
| def add(a, b):
print(f'ADDING {a} + {b}')
return a + b
def subtract(a, b):
print(f'SUBTRACTING {a} - {b}')
return a - b
def multiply(a, b):
print(f'MULTIPLYING {a} * {b}')
return a * b
def divide(a, b):
print(f'DIVIDING {a} / {b}')
return a / b
a = float(input('input a:'))
b = float(input('input b:'))
c = float(input('input c:'))
d = float(input('input d:'))
e = float(input('input e:'))
print('calculate (a+b)*c-(d/e)')
print('Directly:', (a + b) * c - d / e)
print('Using the functions:', subtract(multiply(add(a, b), c), divide(d, e))) |
# Description: Pass Statement in Python
# Pass statement in for loop
for var in range(5):
pass
# Pass statement in a while loop
while True:
pass # Busy-wait for keyboard interrupt (Ctrl + C)
# This is commonly used for creating minimal classes:
class MyEmptyClass:
pass
# Pass can also be used is as a place-holder for a function or conditional body while working on new code
def defineAFunction():
pass # Remember to implement this!
| for var in range(5):
pass
while True:
pass
class Myemptyclass:
pass
def define_a_function():
pass |
number_dict = {
"0" : {
"color" : (187,173,160),
"font_size" : 45,
"backgroud_color" : (205,193,180),
"coordinate" : [(0,0), (0,0), (0,0), (0,0)]
},
"2" : {
"color" : (119, 110, 101),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (238, 228, 218),
"coordinate" : [(40,10), (30,3), (25,2), (22,3)]
},
"4" : {
"color" : (119, 110, 101),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (237, 224, 200),
"coordinate" : [(40,10), (30,3), (25,2), (22,3)]
},
"8" : {
"color" : (249, 246, 242),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (242, 177, 121),
"coordinate" : [(40,10), (30,3), (25,2), (22,3)]
},
"16" : {
"color" : (249, 246, 242),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (235, 140, 82),
"coordinate" : [(15,10), (8,3), (6,2), (6,3)]
},
"32" : {
"color" : (249, 246, 242),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (245, 124, 95),
"coordinate" : [(20,10), (10,3), (8,2), (9,3)]
},
"64" : {
"color" : (249, 246, 242),
"font_size" : [70, 60, 50, 40],
"backgroud_color" : (233, 89, 55),
"coordinate" : [(20,10), (10,3), (8,2), (9,3)]
},
"128" : {
"color" : (249, 246, 242),
"font_size" : [50, 40, 30, 25],
"backgroud_color" : (242, 216, 106),
"coordinate" : [(15,25), (10,15), (10,15), (10,15)]
},
"256" : {
"color" : (249, 246, 242),
"font_size" : [50, 40, 30, 25],
"backgroud_color" : (237, 202, 75),
"coordinate" : [(15,25), (10,15), (10,15), (10,15)]
},
"512" : {
"color" : (249, 246, 242),
"font_size" : [50, 40, 30, 25],
"backgroud_color" : (228, 192, 42),
"coordinate" : [(15,25), (10,15), (10,15), (10,15)]
},
"1024" : {
"color" : (249, 246, 242),
"font_size" : [40, 30, 24, 20],
"backgroud_color" : (237, 195, 20),
"coordinate" : [(11,30), (8,23), (8,20), (8,18)]
},
"2048" : {
"color" : (249, 246, 242),
"font_size" : [40, 30, 24, 20],
"backgroud_color" : (237, 195, 20),
"coordinate" : [(13,30), (10,23), (10,20), (10,18)]
},
"4096" : {
"color" : (249, 246, 242),
"font_size" : [40, 30, 24, 20],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(13,30), (10,23), (10,20), (10,18)]
},
"8192" : {
"color" : (249, 246, 242),
"font_size" : [40, 30, 24, 20],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(13,30), (10,23), (10,20), (10,18)]
},
"16384" : {
"color" : (249, 246, 242),
"font_size" : [32, 24, 19, 16],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(11,35), (10,28), (10,25), (9,20)]
},
"32768" : {
"color" : (249, 246, 242),
"font_size" : [32, 24, 19, 16],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(12,35), (11,28), (11,25), (10,20)]
},
"65536" : {
"color" : (249, 246, 242),
"font_size" : [32, 24, 19, 16],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(14,35), (12,28), (11,25), (10,20)]
},
"131072" : {
"color" : (249, 246, 242),
"font_size" : [28, 20, 16, 13],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(10,37), (10,32), (9,26), (9,23)]
},
"262144" : {
"color" : (249, 246, 242),
"font_size" : [28, 20, 16, 13],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(11,39), (11,32), (10,26), (9,23)]
},
"524288" : {
"color" : (249, 246, 242),
"font_size" : [28, 20, 16, 13],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(12,37), (11,32), (11,26), (9,23)]
},
"1048576" : {
"color" : (249, 246, 242),
"font_size" : [24, 17, 14, 12],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(9,42), (9,33), (8,28), (8,24)]
},
"2097152" : {
"color" : (249, 246, 242),
"font_size" : [24, 17, 14, 12],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(11,42), (10,33), (9,28), (9,24)]
},
"4194304" : {
"color" : (249, 246, 242),
"font_size" : [24, 17, 14, 12],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(10,42), (10,33), (9,28), (9,24)]
},
"8388608" : {
"color" : (249, 246, 242),
"font_size" : [24, 17, 14, 12],
"backgroud_color" : (71, 71, 82),
"coordinate" : [(11,42), (11,33), (10,28), (9,24)]
}
} | number_dict = {'0': {'color': (187, 173, 160), 'font_size': 45, 'backgroud_color': (205, 193, 180), 'coordinate': [(0, 0), (0, 0), (0, 0), (0, 0)]}, '2': {'color': (119, 110, 101), 'font_size': [70, 60, 50, 40], 'backgroud_color': (238, 228, 218), 'coordinate': [(40, 10), (30, 3), (25, 2), (22, 3)]}, '4': {'color': (119, 110, 101), 'font_size': [70, 60, 50, 40], 'backgroud_color': (237, 224, 200), 'coordinate': [(40, 10), (30, 3), (25, 2), (22, 3)]}, '8': {'color': (249, 246, 242), 'font_size': [70, 60, 50, 40], 'backgroud_color': (242, 177, 121), 'coordinate': [(40, 10), (30, 3), (25, 2), (22, 3)]}, '16': {'color': (249, 246, 242), 'font_size': [70, 60, 50, 40], 'backgroud_color': (235, 140, 82), 'coordinate': [(15, 10), (8, 3), (6, 2), (6, 3)]}, '32': {'color': (249, 246, 242), 'font_size': [70, 60, 50, 40], 'backgroud_color': (245, 124, 95), 'coordinate': [(20, 10), (10, 3), (8, 2), (9, 3)]}, '64': {'color': (249, 246, 242), 'font_size': [70, 60, 50, 40], 'backgroud_color': (233, 89, 55), 'coordinate': [(20, 10), (10, 3), (8, 2), (9, 3)]}, '128': {'color': (249, 246, 242), 'font_size': [50, 40, 30, 25], 'backgroud_color': (242, 216, 106), 'coordinate': [(15, 25), (10, 15), (10, 15), (10, 15)]}, '256': {'color': (249, 246, 242), 'font_size': [50, 40, 30, 25], 'backgroud_color': (237, 202, 75), 'coordinate': [(15, 25), (10, 15), (10, 15), (10, 15)]}, '512': {'color': (249, 246, 242), 'font_size': [50, 40, 30, 25], 'backgroud_color': (228, 192, 42), 'coordinate': [(15, 25), (10, 15), (10, 15), (10, 15)]}, '1024': {'color': (249, 246, 242), 'font_size': [40, 30, 24, 20], 'backgroud_color': (237, 195, 20), 'coordinate': [(11, 30), (8, 23), (8, 20), (8, 18)]}, '2048': {'color': (249, 246, 242), 'font_size': [40, 30, 24, 20], 'backgroud_color': (237, 195, 20), 'coordinate': [(13, 30), (10, 23), (10, 20), (10, 18)]}, '4096': {'color': (249, 246, 242), 'font_size': [40, 30, 24, 20], 'backgroud_color': (71, 71, 82), 'coordinate': [(13, 30), (10, 23), (10, 20), (10, 18)]}, '8192': {'color': (249, 246, 242), 'font_size': [40, 30, 24, 20], 'backgroud_color': (71, 71, 82), 'coordinate': [(13, 30), (10, 23), (10, 20), (10, 18)]}, '16384': {'color': (249, 246, 242), 'font_size': [32, 24, 19, 16], 'backgroud_color': (71, 71, 82), 'coordinate': [(11, 35), (10, 28), (10, 25), (9, 20)]}, '32768': {'color': (249, 246, 242), 'font_size': [32, 24, 19, 16], 'backgroud_color': (71, 71, 82), 'coordinate': [(12, 35), (11, 28), (11, 25), (10, 20)]}, '65536': {'color': (249, 246, 242), 'font_size': [32, 24, 19, 16], 'backgroud_color': (71, 71, 82), 'coordinate': [(14, 35), (12, 28), (11, 25), (10, 20)]}, '131072': {'color': (249, 246, 242), 'font_size': [28, 20, 16, 13], 'backgroud_color': (71, 71, 82), 'coordinate': [(10, 37), (10, 32), (9, 26), (9, 23)]}, '262144': {'color': (249, 246, 242), 'font_size': [28, 20, 16, 13], 'backgroud_color': (71, 71, 82), 'coordinate': [(11, 39), (11, 32), (10, 26), (9, 23)]}, '524288': {'color': (249, 246, 242), 'font_size': [28, 20, 16, 13], 'backgroud_color': (71, 71, 82), 'coordinate': [(12, 37), (11, 32), (11, 26), (9, 23)]}, '1048576': {'color': (249, 246, 242), 'font_size': [24, 17, 14, 12], 'backgroud_color': (71, 71, 82), 'coordinate': [(9, 42), (9, 33), (8, 28), (8, 24)]}, '2097152': {'color': (249, 246, 242), 'font_size': [24, 17, 14, 12], 'backgroud_color': (71, 71, 82), 'coordinate': [(11, 42), (10, 33), (9, 28), (9, 24)]}, '4194304': {'color': (249, 246, 242), 'font_size': [24, 17, 14, 12], 'backgroud_color': (71, 71, 82), 'coordinate': [(10, 42), (10, 33), (9, 28), (9, 24)]}, '8388608': {'color': (249, 246, 242), 'font_size': [24, 17, 14, 12], 'backgroud_color': (71, 71, 82), 'coordinate': [(11, 42), (11, 33), (10, 28), (9, 24)]}} |
""" Install the latest Windows binary wheel package from PyPI """
def install_gitfat_win():
""" Install the latest Windows binary wheel package from PyPI """
# TODO: Parse all available packages through PyPI Simple:
# https://pypi.python.org/simple/git-fat/
raise NotImplementedError("TODO: Installing pypi/git-fat on Windows")
def main():
install_gitfat_win()
if __name__ == "__main__":
main()
| """ Install the latest Windows binary wheel package from PyPI """
def install_gitfat_win():
""" Install the latest Windows binary wheel package from PyPI """
raise not_implemented_error('TODO: Installing pypi/git-fat on Windows')
def main():
install_gitfat_win()
if __name__ == '__main__':
main() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.