content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
envs_dict = {
# "Standard" Mujoco Envs
"halfcheetah": "gym.envs.mujoco.half_cheetah:HalfCheetahEnv",
"ant": "gym.envs.mujoco.ant:AntEnv",
"hopper": "gym.envs.mujoco.hopper:HopperEnv",
"walker": "gym.envs.mujoco.walker2d:Walker2dEnv",
"humanoid": "gym.envs.mujoco.humanoid:HumanoidEnv",
"swimmer": "gym.envs.mujoco.swimmer:SwimmerEnv",
"inverteddoublependulum": "gym.envs.mujoco.inverted_double_pendulum:InvertedDoublePendulum2dEnv",
"invertedpendulum": "gym.envs.mujoco.inverted_pendulum:InvertedPendulum",
# normal envs
"lunarlandercont": "gym.envs.box2d.lunar_lander:LunarLanderContinuous",
}
| envs_dict = {'halfcheetah': 'gym.envs.mujoco.half_cheetah:HalfCheetahEnv', 'ant': 'gym.envs.mujoco.ant:AntEnv', 'hopper': 'gym.envs.mujoco.hopper:HopperEnv', 'walker': 'gym.envs.mujoco.walker2d:Walker2dEnv', 'humanoid': 'gym.envs.mujoco.humanoid:HumanoidEnv', 'swimmer': 'gym.envs.mujoco.swimmer:SwimmerEnv', 'inverteddoublependulum': 'gym.envs.mujoco.inverted_double_pendulum:InvertedDoublePendulum2dEnv', 'invertedpendulum': 'gym.envs.mujoco.inverted_pendulum:InvertedPendulum', 'lunarlandercont': 'gym.envs.box2d.lunar_lander:LunarLanderContinuous'} |
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""
testlink.testlink
"""
class TestSuite(object):
def __init__(self, name='', details='', testcase_list=None, sub_suites=None):
"""
TestSuite (TODO(devin): there is an infinite recursive reference problem with initializing an empty list)
:param name: test suite name
:param details: test suite detail infomation
:param testcase_list: test case list
:param sub_suites: sub test suite list
"""
self.name = name
self.details = details
self.testcase_list = testcase_list
self.sub_suites = sub_suites
def to_dict(self):
data = {
'name': self.name,
'details': self.details,
'testcase_list': [],
'sub_suites': []
}
if self.sub_suites:
for suite in self.sub_suites:
data['sub_suites'].append(suite.to_dict())
if self.testcase_list:
for case in self.testcase_list:
data['testcase_list'].append(case.to_dict())
return data
class TestCase(object):
def __init__(self, name='', version=1, summary='', preconditions='', execution_type=1, importance=2, estimated_exec_duration=3, status=7, steps=None):
"""
TestCase
:param name: test case name
:param version: test case version infomation
:param summary: test case summary infomation
:param preconditions: test case pre condition
:param execution_type: manual or automate
:param importance: high:1, middle:2, low:3
:param estimated_exec_duration: estimated execution duration
:param status: draft:1, ready ro review:2, review in progress:3, rework:4, obsolete:5, future:6, final:7
:param steps: test case step list
"""
self.name = name
self.version = version
self.summary = summary
self.preconditions = preconditions
self.execution_type = execution_type
self.importance = importance
self.estimated_exec_duration = estimated_exec_duration
self.status = status
self.steps = steps
def to_dict(self):
data = {
'name': self.name,
'version': self.version, # TODO(devin): get version content
'summary': self.summary,
'preconditions': self.preconditions,
'execution_type': self.execution_type,
'importance': self.importance,
'estimated_exec_duration': self.estimated_exec_duration, # TODO(devin): get estimated content
'status': self.status, # TODO(devin): get status content
'steps': []
}
if self.steps:
for step in self.steps:
data['steps'].append(step.to_dict())
return data
class TestStep(object):
def __init__(self, step_number=1, actions='', expectedresults='', execution_type=1):
"""
TestStep
:param step_number: test step number
:param actions: test step actions
:param expectedresults: test step expected results
:param execution_type: test step execution type
"""
self.step_number = step_number
self.actions = actions
self.expectedresults = expectedresults
self.execution_type = execution_type # TODO(devin): get execution type content
def to_dict(self):
data = {
'step_number': self.step_number,
'actions': self.actions,
'expectedresults': self.expectedresults,
'execution_type': self.execution_type
}
return data
| """
testlink.testlink
"""
class Testsuite(object):
def __init__(self, name='', details='', testcase_list=None, sub_suites=None):
"""
TestSuite (TODO(devin): there is an infinite recursive reference problem with initializing an empty list)
:param name: test suite name
:param details: test suite detail infomation
:param testcase_list: test case list
:param sub_suites: sub test suite list
"""
self.name = name
self.details = details
self.testcase_list = testcase_list
self.sub_suites = sub_suites
def to_dict(self):
data = {'name': self.name, 'details': self.details, 'testcase_list': [], 'sub_suites': []}
if self.sub_suites:
for suite in self.sub_suites:
data['sub_suites'].append(suite.to_dict())
if self.testcase_list:
for case in self.testcase_list:
data['testcase_list'].append(case.to_dict())
return data
class Testcase(object):
def __init__(self, name='', version=1, summary='', preconditions='', execution_type=1, importance=2, estimated_exec_duration=3, status=7, steps=None):
"""
TestCase
:param name: test case name
:param version: test case version infomation
:param summary: test case summary infomation
:param preconditions: test case pre condition
:param execution_type: manual or automate
:param importance: high:1, middle:2, low:3
:param estimated_exec_duration: estimated execution duration
:param status: draft:1, ready ro review:2, review in progress:3, rework:4, obsolete:5, future:6, final:7
:param steps: test case step list
"""
self.name = name
self.version = version
self.summary = summary
self.preconditions = preconditions
self.execution_type = execution_type
self.importance = importance
self.estimated_exec_duration = estimated_exec_duration
self.status = status
self.steps = steps
def to_dict(self):
data = {'name': self.name, 'version': self.version, 'summary': self.summary, 'preconditions': self.preconditions, 'execution_type': self.execution_type, 'importance': self.importance, 'estimated_exec_duration': self.estimated_exec_duration, 'status': self.status, 'steps': []}
if self.steps:
for step in self.steps:
data['steps'].append(step.to_dict())
return data
class Teststep(object):
def __init__(self, step_number=1, actions='', expectedresults='', execution_type=1):
"""
TestStep
:param step_number: test step number
:param actions: test step actions
:param expectedresults: test step expected results
:param execution_type: test step execution type
"""
self.step_number = step_number
self.actions = actions
self.expectedresults = expectedresults
self.execution_type = execution_type
def to_dict(self):
data = {'step_number': self.step_number, 'actions': self.actions, 'expectedresults': self.expectedresults, 'execution_type': self.execution_type}
return data |
# This file MUST be configured in order for the code to run properly
# Make sure you put all your input images into an 'assets' folder.
# Each layer (or category) of images must be put in a folder of its own.
# CONFIG is an array of objects where each object represents a layer
# THESE LAYERS MUST BE ORDERED.
# Each layer needs to specify the following
# 1. id: A number representing a particular layer
# 2. name: The name of the layer. Does not necessarily have to be the same as the directory name containing the layer images.
# 3. directory: The folder inside assets that contain traits for the particular layer
# 4. required: If the particular layer is required (True) or optional (False). The first layer must always be set to true.
# 5. rarity_weights: Denotes the rarity distribution of traits. It can take on three types of values.
# - None: This makes all the traits defined in the layer equally rare (or common)
# - "random": Assigns rarity weights at random.
# - array: An array of numbers where each number represents a weight.
# If required is True, this array must be equal to the number of images in the layer directory. The first number is the weight of the first image (in alphabetical order) and so on...
# If required is False, this array must be equal to one plus the number of images in the layer directory. The first number is the weight of having no image at all for this layer. The second number is the weight of the first image and so on...
# Be sure to check out the tutorial in the README for more details.
CONFIG = [
{
'id': 1,
'name': 'asset1',
'directory': 'asset1',
'required': True,
'rarity_weights': [20, 16, 17, 8, 18, 15, 9, 6],
},
{
'id': 2,
'name': 'asset2',
'directory': 'asset2',
'required': True,
'rarity_weights': [8, 24, 16, 20, 13, 19, 6],
},
{
'id': 3,
'name': 'asset3',
'directory': 'asset3',
'required': True,
'rarity_weights': [6, 25, 15, 12, 20, 9, 16, 7, 15, 19, 5],
},
{
'id': 4,
'name': 'asset4',
'directory': 'asset4',
'required': False,
'rarity_weights': [100, 9, 30, 20, 19, 25, 22, 33, 19, 12, 14, 18, 7, 3, 10, 24],
},
{
'id': 5,
'name': 'asset5',
'directory': 'asset5',
'required': True,
'rarity_weights': [19, 12, 6, 12, 20, 24, 9, 8],
},
{
'id': 5,
'name': 'asset6',
'directory': 'asset6',
'required': False,
'rarity_weights': [100, 24, 19, 6, 14, 20, 24, 12, 16],
},
]
| config = [{'id': 1, 'name': 'asset1', 'directory': 'asset1', 'required': True, 'rarity_weights': [20, 16, 17, 8, 18, 15, 9, 6]}, {'id': 2, 'name': 'asset2', 'directory': 'asset2', 'required': True, 'rarity_weights': [8, 24, 16, 20, 13, 19, 6]}, {'id': 3, 'name': 'asset3', 'directory': 'asset3', 'required': True, 'rarity_weights': [6, 25, 15, 12, 20, 9, 16, 7, 15, 19, 5]}, {'id': 4, 'name': 'asset4', 'directory': 'asset4', 'required': False, 'rarity_weights': [100, 9, 30, 20, 19, 25, 22, 33, 19, 12, 14, 18, 7, 3, 10, 24]}, {'id': 5, 'name': 'asset5', 'directory': 'asset5', 'required': True, 'rarity_weights': [19, 12, 6, 12, 20, 24, 9, 8]}, {'id': 5, 'name': 'asset6', 'directory': 'asset6', 'required': False, 'rarity_weights': [100, 24, 19, 6, 14, 20, 24, 12, 16]}] |
def setData(field, value, path):
f = open(path, "r")
lines = f.readlines()
f.close()
f = open(path, "w+")
for line in lines:
if (line.find(field) != -1):
f.write(field + "=" + str(value) + "\n")
else:
f.write(line)
f.close()
return True
def getData(path):
f = open(path, "r")
lines = f.readlines()
f.close()
data = {}
for line in lines:
parts = line.split("=")
data[parts[0]] = parts[1].strip()
return data
def addData(field, value, path):
f = open(path, "a")
f.write(field + "=" + str(value) + "\n")
f.close()
return
def deleteData(field, value, path):
f = open(path, "r")
lines = f.readlines()
f.close()
f = open(path, "w+")
for line in lines:
if (line.find(field) == -1):
f.write(line)
f.close()
return True | def set_data(field, value, path):
f = open(path, 'r')
lines = f.readlines()
f.close()
f = open(path, 'w+')
for line in lines:
if line.find(field) != -1:
f.write(field + '=' + str(value) + '\n')
else:
f.write(line)
f.close()
return True
def get_data(path):
f = open(path, 'r')
lines = f.readlines()
f.close()
data = {}
for line in lines:
parts = line.split('=')
data[parts[0]] = parts[1].strip()
return data
def add_data(field, value, path):
f = open(path, 'a')
f.write(field + '=' + str(value) + '\n')
f.close()
return
def delete_data(field, value, path):
f = open(path, 'r')
lines = f.readlines()
f.close()
f = open(path, 'w+')
for line in lines:
if line.find(field) == -1:
f.write(line)
f.close()
return True |
class Event:
def __init__(self):
self.handlers = []
def call(self, *args, **kwargs):
for h in self.handlers:
h(*args, **kwargs)
def __call__(self, *args, **kwargs):
self.call(*args, **kwargs)
| class Event:
def __init__(self):
self.handlers = []
def call(self, *args, **kwargs):
for h in self.handlers:
h(*args, **kwargs)
def __call__(self, *args, **kwargs):
self.call(*args, **kwargs) |
"""
module for menus
and ascii arts
"""
ascii_art = """
8888888b. .d8888b. .d88888b. 888
888 Y88b d88P Y88b d88P" "Y88b 888
888 888 Y88b. 888 888 888
888 d88P 888 888 "Y888b. 888 888 888
8888888P" 888 888 "Y88b. 888 888 888
888 888 888 "888 888 Y8b 888 888
888 Y88b 888 Y88b d88P Y88b.Y8b88P 888
888 "Y88888 "Y8888P" "Y888888" 88888888
888 Y8b
Y8b d88P
"Y88P"
"""
menu = """
OPTIONS
-a about Shows information about PySQL
-c commands Display available commands
-d def user Default User options
-h help Display this help message
-v version Display application version
-u updates Check for PySQL updates
-q quit Exit the program
"""
about = """
PySQL: Python - MySQL wrapper tool
PySQL is a command line tool for making MySQL queries easier, made using Python
See https://github.com/Devansh3712/PySQL for more information
"""
commands = """
COMMANDS
ddl Displays Data Definition Language commands
dml Displays Data Manipulation Language commands
export Export table/database
import Import database
all Displays all available commands
"""
default_user = """
DEFAULT USER
adduser Create a default user for PySQL login
removeuser Remove the current default user
"""
data_definition_language = """
DDL COMMANDS
showdb Display all databases in MySQL server
usedb Use a database
createdb DB_NAME Create a new database
dropdb DB_NAME Delete a database
showtb Display all tables in current db
createtb TB_NAME, ARGS Create a new table in current db
droptb TB_NAME Delete a table in current db
trunctb TB_NAME Truncate a table in current db
desctb TB_NAME Display structure of a table in current db
altertb TB_NAME, ARGS Alter contents of table in current db
"""
data_manipulation_language = """
DML COMMANDS
select TB_NAME, COLUMNS, ARGS Displays selected columns of a table
insert -s TB_NAME, ARGS Insert a single row in a table
-m TB_NAME, NUM, ARGS Insert `NUM` rows in a table
-f TB_NAME, FILE_NAME Insert values in a table from CSV file
update TB_NAME, COLUMNS, ARGS Updates values of columns in a table
delete TB_NAME, COLUMN Deletes values of row in a table
"""
all_commands = """
ALL COMMANDS
select TB_NAME, COLUMNS, ARGS Displays selected columns of a table
insert -s TB_NAME, ARGS Insert a single row in a table
-m TB_NAME, NUM, ARGS Insert `NUM` rows in a table
-f TB_NAME, FILE_NAME Insert values in a table from CSV file
update TB_NAME, COLUMNS, ARGS Updates values of columns in a table
delete TB_NAME, COLUMN Deletes values of row in a table
showdb Display all databases in MySQL server
usedb Use a database
createdb DB_NAME Create a new database
dropdb DB_NAME Delete a database
showtb Display all tables in current db
createtb TB_NAME, ARGS Create a new table in current db
droptb TB_NAME Delete a table in current db
trunctb TB_NAME Truncate a table in current db
desctb TB_NAME Display structure of a table in current db
altertb TB_NAME, ARGS Alter contents of table in current db
exportdb DB_NAME, PATH Export db as `.sql` file to path
exporttb -json TB_NAME, PATH Export table as `.txt` file to path
-csv TB_NAME, PATH Export table as `.csv` file to path
-sql TB_NAME, PATH Export table schema as `.sql` file to path
exportall -json PATH Export all tables in db as `.txt` file to path
-csv PATH Export all tables in db as `.csv` file to path
-sql PATH Export all tables schema in db as `.sql` file to path
importdb DB_NAME, PATH Import `.sql` file into input database
importtb DB_NAME, PATH Import `.sql` table schema into input table
"""
export = """
EXPORT
exportdb DB_NAME, PATH Export db as `.sql` file to path
exporttb -json TB_NAME, PATH Export table as `.txt` file to path
-csv TB_NAME, PATH Export table as `.csv` file to path
-sql TB_NAME, PATH Export table schema as `.sql` file to path
exportall -json PATH Export all tables in db as `.txt` file to path
-csv PATH Export all tables in db as `.csv` file to path
-sql PATH Export all tables schema in db as `.sql` file to path
"""
import_ = """
IMPORT
importdb DB_NAME, PATH Import `.sql` file into input database
importtb DB_NAME, PATH Import `.sql` table schema into input table
"""
"""
PySQL
Devansh Singh, 2021
"""
| """
module for menus
and ascii arts
"""
ascii_art = '\n\n8888888b. .d8888b. .d88888b. 888 \n888 Y88b d88P Y88b d88P" "Y88b 888 \n888 888 Y88b. 888 888 888 \n888 d88P 888 888 "Y888b. 888 888 888 \n8888888P" 888 888 "Y88b. 888 888 888 \n888 888 888 "888 888 Y8b 888 888 \n888 Y88b 888 Y88b d88P Y88b.Y8b88P 888 \n888 "Y88888 "Y8888P" "Y888888" 88888888 \n 888 Y8b \n Y8b d88P \n "Y88P" \n'
menu = '\nOPTIONS\n\n -a about Shows information about PySQL\n -c commands Display available commands\n -d def user Default User options\n -h help Display this help message\n -v version Display application version\n -u updates Check for PySQL updates\n -q quit Exit the program\n'
about = '\nPySQL: Python - MySQL wrapper tool\n\nPySQL is a command line tool for making MySQL queries easier, made using Python\nSee https://github.com/Devansh3712/PySQL for more information\n'
commands = '\nCOMMANDS\n\n ddl Displays Data Definition Language commands\n dml Displays Data Manipulation Language commands\n export Export table/database\n import Import database\n all Displays all available commands\n'
default_user = '\nDEFAULT USER\n\n adduser Create a default user for PySQL login\n removeuser Remove the current default user\n'
data_definition_language = '\nDDL COMMANDS\n\n showdb Display all databases in MySQL server\n usedb Use a database\n createdb DB_NAME Create a new database\n dropdb DB_NAME Delete a database\n showtb Display all tables in current db\n createtb TB_NAME, ARGS Create a new table in current db\n droptb TB_NAME Delete a table in current db\n trunctb TB_NAME Truncate a table in current db\n desctb TB_NAME Display structure of a table in current db\n altertb TB_NAME, ARGS Alter contents of table in current db\n'
data_manipulation_language = '\nDML COMMANDS\n\n select TB_NAME, COLUMNS, ARGS Displays selected columns of a table\n insert -s TB_NAME, ARGS Insert a single row in a table\n -m TB_NAME, NUM, ARGS Insert `NUM` rows in a table\n -f TB_NAME, FILE_NAME Insert values in a table from CSV file\n update TB_NAME, COLUMNS, ARGS Updates values of columns in a table\n delete TB_NAME, COLUMN Deletes values of row in a table\n'
all_commands = '\nALL COMMANDS\n\n select TB_NAME, COLUMNS, ARGS Displays selected columns of a table\n insert -s TB_NAME, ARGS Insert a single row in a table\n -m TB_NAME, NUM, ARGS Insert `NUM` rows in a table\n -f TB_NAME, FILE_NAME Insert values in a table from CSV file\n update TB_NAME, COLUMNS, ARGS Updates values of columns in a table\n delete TB_NAME, COLUMN Deletes values of row in a table\n showdb Display all databases in MySQL server\n usedb Use a database\n createdb DB_NAME Create a new database\n dropdb DB_NAME Delete a database\n showtb Display all tables in current db\n createtb TB_NAME, ARGS Create a new table in current db\n droptb TB_NAME Delete a table in current db\n trunctb TB_NAME Truncate a table in current db\n desctb TB_NAME Display structure of a table in current db\n altertb TB_NAME, ARGS Alter contents of table in current db\n exportdb DB_NAME, PATH Export db as `.sql` file to path\n exporttb -json TB_NAME, PATH Export table as `.txt` file to path\n -csv TB_NAME, PATH Export table as `.csv` file to path\n -sql TB_NAME, PATH Export table schema as `.sql` file to path\n exportall -json PATH Export all tables in db as `.txt` file to path\n -csv PATH Export all tables in db as `.csv` file to path\n -sql PATH Export all tables schema in db as `.sql` file to path\n importdb DB_NAME, PATH Import `.sql` file into input database\n importtb DB_NAME, PATH Import `.sql` table schema into input table\n'
export = '\nEXPORT\n\n exportdb DB_NAME, PATH Export db as `.sql` file to path\n exporttb -json TB_NAME, PATH Export table as `.txt` file to path\n -csv TB_NAME, PATH Export table as `.csv` file to path\n -sql TB_NAME, PATH Export table schema as `.sql` file to path\n exportall -json PATH Export all tables in db as `.txt` file to path\n -csv PATH Export all tables in db as `.csv` file to path\n -sql PATH Export all tables schema in db as `.sql` file to path\n'
import_ = '\nIMPORT\n\n importdb DB_NAME, PATH Import `.sql` file into input database\n importtb DB_NAME, PATH Import `.sql` table schema into input table\n'
'\nPySQL\nDevansh Singh, 2021\n' |
class ExampleJob:
def __init__(self, id):
self.id = id
self.retry_count = 10
self.retry_pause_sec = 10
def run(self, runtime):
pass | class Examplejob:
def __init__(self, id):
self.id = id
self.retry_count = 10
self.retry_pause_sec = 10
def run(self, runtime):
pass |
#! /usr/bin/env python
__author__ = 'Tser'
__email__ = '807447312@qq.com'
__project__ = 'jicaiauto'
__script__ = '__version__.py'
__create_time__ = '2020/7/15 23:21'
VERSION = (0, 0, 2, 0)
__version__ = '.'.join(map(str, VERSION)) | __author__ = 'Tser'
__email__ = '807447312@qq.com'
__project__ = 'jicaiauto'
__script__ = '__version__.py'
__create_time__ = '2020/7/15 23:21'
version = (0, 0, 2, 0)
__version__ = '.'.join(map(str, VERSION)) |
_base_ = './pascal_voc12.py'
# dataset settings
data = dict(
samples_per_gpu=2,
train=dict(
ann_dir=['SegmentationClass', 'SegmentationClassAug'],
split=[
'ImageSets/Segmentation/train.txt',
'ImageSets/Segmentation/aug.txt'
]))
| _base_ = './pascal_voc12.py'
data = dict(samples_per_gpu=2, train=dict(ann_dir=['SegmentationClass', 'SegmentationClassAug'], split=['ImageSets/Segmentation/train.txt', 'ImageSets/Segmentation/aug.txt'])) |
""" Staircase """
def staircase(n):
i = 1
while (n + 1) - i:
blanks = " " * (n-i)
pattern = "#" * i
print(blanks+pattern)
i += 1
if __name__ == "__main__":
staircase(4)
| """ Staircase """
def staircase(n):
i = 1
while n + 1 - i:
blanks = ' ' * (n - i)
pattern = '#' * i
print(blanks + pattern)
i += 1
if __name__ == '__main__':
staircase(4) |
# Copyright 2018 Contributors to Hyperledger Sawtooth
#
# 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.
# -----------------------------------------------------------------------------
USER_SEARCH_ALL = "(objectClass=person)"
USER_SEARCH_BY_DN = "(&(objectClass=person)(distinguishedName={}))"
USER_SEARCH_AFTER_DATE = "(&(objectClass=person)(whenChanged>=%s))"
GROUP_SEARCH_ALL = "(objectClass=group)"
GROUP_SEARCH_BY_DN = "(&(objectClass=group)(distinguishedName={}))"
GROUP_SEARCH_AFTER_DATE = "(&(objectClass=group)(whenChanged>=%s))"
| user_search_all = '(objectClass=person)'
user_search_by_dn = '(&(objectClass=person)(distinguishedName={}))'
user_search_after_date = '(&(objectClass=person)(whenChanged>=%s))'
group_search_all = '(objectClass=group)'
group_search_by_dn = '(&(objectClass=group)(distinguishedName={}))'
group_search_after_date = '(&(objectClass=group)(whenChanged>=%s))' |
class StatusWirelessStaRemoteUnms:
status: int
timestamp: str
def __init__(self, data):
self.status = data.get("status")
self.timestamp = data.get("timestamp")
| class Statuswirelessstaremoteunms:
status: int
timestamp: str
def __init__(self, data):
self.status = data.get('status')
self.timestamp = data.get('timestamp') |
class Movie:
"""
This is an abstract a movie structure
"""
def __init__(self, leading_actor='Leonardo DiCaprio',
supporting_actor='Brad Pitt',
run_time=130):
self.leading_actor = leading_actor
self.supporting_actor = supporting_actor
self.run_time = run_time
def who_is_leading(self):
"""
Who is the star of the film
"""
print('The leading star is {}'.format(self.leading_actor))
def who_is_supporting(self):
"""
Who is the supporting actor?
"""
print('The supporting actor is {}'.format(self.supporting_actor))
def what_is_run_time(self):
"""
What is the running time?
"""
print('The running time is {}'.format(self.run_time)) | class Movie:
"""
This is an abstract a movie structure
"""
def __init__(self, leading_actor='Leonardo DiCaprio', supporting_actor='Brad Pitt', run_time=130):
self.leading_actor = leading_actor
self.supporting_actor = supporting_actor
self.run_time = run_time
def who_is_leading(self):
"""
Who is the star of the film
"""
print('The leading star is {}'.format(self.leading_actor))
def who_is_supporting(self):
"""
Who is the supporting actor?
"""
print('The supporting actor is {}'.format(self.supporting_actor))
def what_is_run_time(self):
"""
What is the running time?
"""
print('The running time is {}'.format(self.run_time)) |
"""f90nml.fpy
=============
Module for conversion between basic data types and Fortran string
representations.
:copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
:license: Apache License, Version 2.0, see LICENSE for details.
"""
def pyfloat(v_str):
"""Convert string repr of Fortran floating point to Python double."""
# NOTE: There is no loss of information from SP to DP floats
return float(v_str.lower().replace('d', 'e'))
def pycomplex(v_str):
"""Convert string repr of Fortran complex to Python complex."""
assert isinstance(v_str, str)
if v_str[0] == '(' and v_str[-1] == ')' and len(v_str.split(',')) == 2:
v_re, v_im = v_str[1:-1].split(',', 1)
# NOTE: Failed float(str) will raise ValueError
return complex(pyfloat(v_re), pyfloat(v_im))
else:
raise ValueError('{0} must be in complex number form (x, y).'
''.format(v_str))
def pybool(v_str, strict_logical=True):
"""Convert string repr of Fortran logical to Python logical."""
assert isinstance(v_str, str)
assert isinstance(strict_logical, bool)
if strict_logical:
v_bool = v_str.lower()
else:
try:
if v_str.startswith('.'):
v_bool = v_str[1].lower()
else:
v_bool = v_str[0].lower()
except IndexError:
raise ValueError('{0} is not a valid logical constant.'
''.format(v_str))
if v_bool in ('.true.', '.t.', 'true', 't'):
return True
elif v_bool in ('.false.', '.f.', 'false', 'f'):
return False
else:
raise ValueError('{0} is not a valid logical constant.'.format(v_str))
def pystr(v_str):
"""Convert string repr of Fortran string to Python string."""
assert isinstance(v_str, str)
if v_str[0] in ("'", '"') and v_str[0] == v_str[-1]:
return v_str[1:-1]
else:
return v_str
| """f90nml.fpy
=============
Module for conversion between basic data types and Fortran string
representations.
:copyright: Copyright 2014 Marshall Ward, see AUTHORS for details.
:license: Apache License, Version 2.0, see LICENSE for details.
"""
def pyfloat(v_str):
"""Convert string repr of Fortran floating point to Python double."""
return float(v_str.lower().replace('d', 'e'))
def pycomplex(v_str):
"""Convert string repr of Fortran complex to Python complex."""
assert isinstance(v_str, str)
if v_str[0] == '(' and v_str[-1] == ')' and (len(v_str.split(',')) == 2):
(v_re, v_im) = v_str[1:-1].split(',', 1)
return complex(pyfloat(v_re), pyfloat(v_im))
else:
raise value_error('{0} must be in complex number form (x, y).'.format(v_str))
def pybool(v_str, strict_logical=True):
"""Convert string repr of Fortran logical to Python logical."""
assert isinstance(v_str, str)
assert isinstance(strict_logical, bool)
if strict_logical:
v_bool = v_str.lower()
else:
try:
if v_str.startswith('.'):
v_bool = v_str[1].lower()
else:
v_bool = v_str[0].lower()
except IndexError:
raise value_error('{0} is not a valid logical constant.'.format(v_str))
if v_bool in ('.true.', '.t.', 'true', 't'):
return True
elif v_bool in ('.false.', '.f.', 'false', 'f'):
return False
else:
raise value_error('{0} is not a valid logical constant.'.format(v_str))
def pystr(v_str):
"""Convert string repr of Fortran string to Python string."""
assert isinstance(v_str, str)
if v_str[0] in ("'", '"') and v_str[0] == v_str[-1]:
return v_str[1:-1]
else:
return v_str |
class Zone:
def __init__(self) -> None:
self._display_name = ""
self._offset = 0
def get_display_name(self) -> str:
return self._display_name
def get_offset(self) -> int:
return self._offset
| class Zone:
def __init__(self) -> None:
self._display_name = ''
self._offset = 0
def get_display_name(self) -> str:
return self._display_name
def get_offset(self) -> int:
return self._offset |
def is_prime(n):
for x in range(2, n):
if n % x == 0:
return False
return True
def get_prime_numbers(n):
for x in range(n, 1, -1):
if is_prime(x):
yield x
def get_two_sum(primes, number):
for i, q in enumerate(primes):
next_values = primes[i + 1:]
for p in next_values:
if p <= q and p + q == number:
return p, q
n = int(input("> "))
numbers = []
for _ in range(n):
num = int(input("> "))
primes = list(get_prime_numbers(num))
nums = get_two_sum(primes, num)
numbers.append(nums)
for (p, q) in numbers:
print(p, q) | def is_prime(n):
for x in range(2, n):
if n % x == 0:
return False
return True
def get_prime_numbers(n):
for x in range(n, 1, -1):
if is_prime(x):
yield x
def get_two_sum(primes, number):
for (i, q) in enumerate(primes):
next_values = primes[i + 1:]
for p in next_values:
if p <= q and p + q == number:
return (p, q)
n = int(input('> '))
numbers = []
for _ in range(n):
num = int(input('> '))
primes = list(get_prime_numbers(num))
nums = get_two_sum(primes, num)
numbers.append(nums)
for (p, q) in numbers:
print(p, q) |
opcodes = {
'STOP': [0x00, 0, 0, 0],
'ADD': [0x01, 2, 1, 3],
'MUL': [0x02, 2, 1, 5],
'SUB': [0x03, 2, 1, 3],
'DIV': [0x04, 2, 1, 5],
'SDIV': [0x05, 2, 1, 5],
'MOD': [0x06, 2, 1, 5],
'SMOD': [0x07, 2, 1, 5],
'ADDMOD': [0x08, 3, 1, 8],
'MULMOD': [0x09, 3, 1, 8],
'EXP': [0x0a, 2, 1, 10],
'SIGNEXTEND': [0x0b, 2, 1, 5],
'LT': [0x10, 2, 1, 3],
'GT': [0x11, 2, 1, 3],
'SLT': [0x12, 2, 1, 3],
'SGT': [0x13, 2, 1, 3],
'EQ': [0x14, 2, 1, 3],
'ISZERO': [0x15, 1, 1, 3],
'AND': [0x16, 2, 1, 3],
'OR': [0x17, 2, 1, 3],
'XOR': [0x18, 2, 1, 3],
'NOT': [0x19, 1, 1, 3],
'BYTE': [0x1a, 2, 1, 3],
'SHA3': [0x20, 2, 1, 30],
'ADDRESS': [0x30, 0, 1, 2],
'BALANCE': [0x31, 1, 1, 400],
'ORIGIN': [0x32, 0, 1, 2],
'CALLER': [0x33, 0, 1, 2],
'CALLVALUE': [0x34, 0, 1, 2],
'CALLDATALOAD': [0x35, 1, 1, 3],
'CALLDATASIZE': [0x36, 0, 1, 2],
'CALLDATACOPY': [0x37, 3, 0, 3],
'CODESIZE': [0x38, 0, 1, 2],
'CODECOPY': [0x39, 3, 0, 3],
'GASPRICE': [0x3a, 0, 1, 2],
'EXTCODESIZE': [0x3b, 1, 1, 700],
'EXTCODECOPY': [0x3c, 4, 0, 700],
'BLOCKHASH': [0x40, 1, 1, 20],
'COINBASE': [0x41, 0, 1, 2],
'TIMESTAMP': [0x42, 0, 1, 2],
'NUMBER': [0x43, 0, 1, 2],
'DIFFICULTY': [0x44, 0, 1, 2],
'GASLIMIT': [0x45, 0, 1, 2],
'POP': [0x50, 1, 0, 2],
'MLOAD': [0x51, 1, 1, 3],
'MSTORE': [0x52, 2, 0, 3],
'MSTORE8': [0x53, 2, 0, 3],
'SLOAD': [0x54, 1, 1, 200],
'SSTORE': [0x55, 2, 0, 5000],
'JUMP': [0x56, 1, 0, 8],
'JUMPI': [0x57, 2, 0, 10],
'PC': [0x58, 0, 1, 2],
'MSIZE': [0x59, 0, 1, 2],
'GAS': [0x5a, 0, 1, 2],
'JUMPDEST': [0x5b, 0, 0, 1],
'LOG0': [0xa0, 2, 0, 375],
'LOG1': [0xa1, 3, 0, 750],
'LOG2': [0xa2, 4, 0, 1125],
'LOG3': [0xa3, 5, 0, 1500],
'LOG4': [0xa4, 6, 0, 1875],
'CREATE': [0xf0, 3, 1, 32000],
'CALL': [0xf1, 7, 1, 700],
'CALLCODE': [0xf2, 7, 1, 700],
'RETURN': [0xf3, 2, 0, 0],
'DELEGATECALL': [0xf4, 6, 1, 700],
'CALLBLACKBOX': [0xf5, 7, 1, 700],
'SELFDESTRUCT': [0xff, 1, 0, 25000],
'STATICCALL': [0xfa, 6, 1, 40],
'REVERT': [0xfd, 2, 0, 0],
'SUICIDE': [0xff, 1, 0, 5000],
'INVALID': [0xfe, 0, 0, 0],
}
pseudo_opcodes = {
'CLAMP': [None, 3, 1, 70],
'UCLAMPLT': [None, 2, 1, 25],
'UCLAMPLE': [None, 2, 1, 30],
'CLAMP_NONZERO': [None, 1, 1, 19],
'ASSERT': [None, 1, 0, 85],
'PASS': [None, 0, 0, 0],
'BREAK': [None, 0, 0, 20],
'SHA3_32': [None, 1, 1, 72],
'SLE': [None, 2, 1, 10],
'SGE': [None, 2, 1, 10],
'LE': [None, 2, 1, 10],
'GE': [None, 2, 1, 10],
'CEIL32': [None, 1, 1, 20],
'SET': [None, 2, 0, 20],
'NE': [None, 2, 1, 6],
}
comb_opcodes = {}
for k in opcodes:
comb_opcodes[k] = opcodes[k]
for k in pseudo_opcodes:
comb_opcodes[k] = pseudo_opcodes[k]
| opcodes = {'STOP': [0, 0, 0, 0], 'ADD': [1, 2, 1, 3], 'MUL': [2, 2, 1, 5], 'SUB': [3, 2, 1, 3], 'DIV': [4, 2, 1, 5], 'SDIV': [5, 2, 1, 5], 'MOD': [6, 2, 1, 5], 'SMOD': [7, 2, 1, 5], 'ADDMOD': [8, 3, 1, 8], 'MULMOD': [9, 3, 1, 8], 'EXP': [10, 2, 1, 10], 'SIGNEXTEND': [11, 2, 1, 5], 'LT': [16, 2, 1, 3], 'GT': [17, 2, 1, 3], 'SLT': [18, 2, 1, 3], 'SGT': [19, 2, 1, 3], 'EQ': [20, 2, 1, 3], 'ISZERO': [21, 1, 1, 3], 'AND': [22, 2, 1, 3], 'OR': [23, 2, 1, 3], 'XOR': [24, 2, 1, 3], 'NOT': [25, 1, 1, 3], 'BYTE': [26, 2, 1, 3], 'SHA3': [32, 2, 1, 30], 'ADDRESS': [48, 0, 1, 2], 'BALANCE': [49, 1, 1, 400], 'ORIGIN': [50, 0, 1, 2], 'CALLER': [51, 0, 1, 2], 'CALLVALUE': [52, 0, 1, 2], 'CALLDATALOAD': [53, 1, 1, 3], 'CALLDATASIZE': [54, 0, 1, 2], 'CALLDATACOPY': [55, 3, 0, 3], 'CODESIZE': [56, 0, 1, 2], 'CODECOPY': [57, 3, 0, 3], 'GASPRICE': [58, 0, 1, 2], 'EXTCODESIZE': [59, 1, 1, 700], 'EXTCODECOPY': [60, 4, 0, 700], 'BLOCKHASH': [64, 1, 1, 20], 'COINBASE': [65, 0, 1, 2], 'TIMESTAMP': [66, 0, 1, 2], 'NUMBER': [67, 0, 1, 2], 'DIFFICULTY': [68, 0, 1, 2], 'GASLIMIT': [69, 0, 1, 2], 'POP': [80, 1, 0, 2], 'MLOAD': [81, 1, 1, 3], 'MSTORE': [82, 2, 0, 3], 'MSTORE8': [83, 2, 0, 3], 'SLOAD': [84, 1, 1, 200], 'SSTORE': [85, 2, 0, 5000], 'JUMP': [86, 1, 0, 8], 'JUMPI': [87, 2, 0, 10], 'PC': [88, 0, 1, 2], 'MSIZE': [89, 0, 1, 2], 'GAS': [90, 0, 1, 2], 'JUMPDEST': [91, 0, 0, 1], 'LOG0': [160, 2, 0, 375], 'LOG1': [161, 3, 0, 750], 'LOG2': [162, 4, 0, 1125], 'LOG3': [163, 5, 0, 1500], 'LOG4': [164, 6, 0, 1875], 'CREATE': [240, 3, 1, 32000], 'CALL': [241, 7, 1, 700], 'CALLCODE': [242, 7, 1, 700], 'RETURN': [243, 2, 0, 0], 'DELEGATECALL': [244, 6, 1, 700], 'CALLBLACKBOX': [245, 7, 1, 700], 'SELFDESTRUCT': [255, 1, 0, 25000], 'STATICCALL': [250, 6, 1, 40], 'REVERT': [253, 2, 0, 0], 'SUICIDE': [255, 1, 0, 5000], 'INVALID': [254, 0, 0, 0]}
pseudo_opcodes = {'CLAMP': [None, 3, 1, 70], 'UCLAMPLT': [None, 2, 1, 25], 'UCLAMPLE': [None, 2, 1, 30], 'CLAMP_NONZERO': [None, 1, 1, 19], 'ASSERT': [None, 1, 0, 85], 'PASS': [None, 0, 0, 0], 'BREAK': [None, 0, 0, 20], 'SHA3_32': [None, 1, 1, 72], 'SLE': [None, 2, 1, 10], 'SGE': [None, 2, 1, 10], 'LE': [None, 2, 1, 10], 'GE': [None, 2, 1, 10], 'CEIL32': [None, 1, 1, 20], 'SET': [None, 2, 0, 20], 'NE': [None, 2, 1, 6]}
comb_opcodes = {}
for k in opcodes:
comb_opcodes[k] = opcodes[k]
for k in pseudo_opcodes:
comb_opcodes[k] = pseudo_opcodes[k] |
singular_to_plural_dictionary = {
"1": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions"
},
"1.1": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions"
},
"1.2": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards"
},
"1.3": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects"
},
"1.4": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects"
},
"1.5": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects"
},
"1.6": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects",
"https-layer": "https-layers",
"https-section": "https-sections",
"https-rule": "https-rules"
},
"1.6.1": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects",
"https-layer": "https-layers",
"https-section": "https-sections",
"https-rule": "https-rules"
},
"1.7": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects",
"https-layer": "https-layers",
"https-section": "https-sections",
"https-rule": "https-rules"
},
"1.7.1": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects",
"https-layer": "https-layers",
"https-section": "https-sections",
"https-rule": "https-rules"
},
"1.8": {
"access-role": "access-roles",
"threat-profile": "threat-profiles",
"host": "hosts",
"network": "networks",
"address-range": "address_ranges",
"multicast-address-range": "multicast-address-ranges",
"security-zone": "security-zones",
"time": "times",
"simple-gateway": "simple-gateways",
"dynamic-object": "dynamic-objects",
"trusted-client": "trusted-clients",
"tags": "tags",
"dns-domain": "dns-domains",
"opsec-application": "opsec-applications",
"data-center": "data-centers",
"data-center-object": "data-center-objects",
"service-tcp": "services-tcp",
"service-udp": "services-udp",
"service-icmp": "services-icmp",
"service-icmp6": "services-icmp6",
"service-sctp": "services-sctp",
"service-rpc": "services-rpc",
"service-other": "services-other",
"service-dce-rpc": "services-dce-rpc",
"application-site": "applications-sites",
"application-site-category": "application-site-categories",
"application-site-group": "application-site-groups",
"vpn-community-meshed": "vpn-communities-meshed",
"vpn-community-star": "vpn-communities-star",
"placeholder": "placeholders",
"administrator": "administrators",
"group": "groups",
"group-with-exclusion": "groups-with-exclusion",
"service-group": "service-groups",
"time-group": "time-groups",
"application-group": "application-groups",
"threat-protection": "threat-protections",
"exception-group": "exception-groups",
"generic-object": "",
"access-layer": "access-layers",
"access-section": "access-sections",
"access-rule": "access-rules",
"nat-layer": "nat-layers",
"nat-section": "nat-sections",
"nat-rule": "nat-rules",
"threat-layer": "threat-layers",
"threat-rule": "threat-rules",
"threat-exception-section": "threat-exception-sections",
"threat-exception": "threat-exceptions",
"wildcard": "wildcards",
"updatable-object": "updatable-objects",
"https-layer": "https-layers",
"https-section": "https-sections",
"https-rule": "https-rules"
},
}
unexportable_objects_map = {}
import_priority = {
"vpn-community-meshed": 1,
"vpn-community-star": 1,
"group": 2,
"group-with-exclusion": 3,
"service-group": 2,
"time-group": 2,
"application-group": 2,
}
generic_objects_for_rule_fields = {
"source": ["host", "ip-address"],
"destination": ["host", "ip-address"],
"vpn": ["vpn-community-star"],
"service": ["service-tcp", "port"],
"protected-scope": ["multicast-address-range", "ip-address"],
}
generic_objects_for_duplicates_in_group_members = {
"group": ["host", "ip-address"],
"service-group": ["service-tcp", "port"],
"time-group": ["time"]
}
placeholder_type_by_obj_type = {
"DataType": {
"type": "com.checkpoint.management.data_awareness.objects.DataAwarenessCompound"
},
"DropUserCheckInteractionScheme": {
"bladeName": "APPC",
"type": "com.checkpoint.objects.user_check.DropUserCheckInteractionScheme"
},
"AskUserCheckInteractionScheme": {
"bladeName": "APPC",
"type": "com.checkpoint.objects.user_check.AskUserCheckInteractionScheme"
},
"InformUserCheckInteractionScheme": {
"bladeName": "APPC",
"type": "com.checkpoint.objects.user_check.InformUserCheckInteractionScheme"
},
"CpmiGatewayCluster": {
"ipsBlade": "INSTALLED",
"type": "com.checkpoint.objects.classes.dummy.CpmiGatewayCluster"
},
"CpmiVsClusterNetobj": {
"ipsBlade": "INSTALLED",
"type": "com.checkpoint.objects.classes.dummy.CpmiGatewayCluster"
},
"CpmiGatewayPlain": {
"type": "com.checkpoint.objects.classes.dummy.CpmiGatewayCkp",
"ipaddr": None,
"vpn1": "true"
},
"CpmiIcmpService": {
"type": "com.checkpoint.objects.classes.dummy.CpmiIcmpService"
},
"CpmiIcmp6Service": {
"type": "com.checkpoint.objects.classes.dummy.CpmiIcmp6Service"
},
"CpmiAppfwLimit": {
"type": "com.checkpoint.objects.appfw.dummy.CpmiAppfwLimit",
},
"service-other": {
"type": "com.checkpoint.objects.classes.dummy.CpmiOtherService",
"matchExp": "Dummy Match Expression"
}
}
group_objects_field = {
"group": ["members"],
"vpn-community-star": ["center-gateways", "satellite-gateways"],
"vpn-community-meshed": ["gateways"],
"service-group": ["members"],
"time-group": ["members"],
"application-site-group": ["members"],
"group-with-exclusion": []
}
no_export_fields = {"type"}
no_export_fields_and_subfields = ["read-only", "layer", "package", "owner", "icon",
"domain", "from", "to", "rulebase", "uid", "meta-info", "parent", "groups", "type", "override-default-settings"]
no_export_fields_by_api_type = {
"host": ["standard-port-number", "subnet-mask", "type"],
"network": ["subnet-mask"],
"threat-rule": ["exceptions", "exceptions-layer"],
"simple-gateway": ["forward-logs-to-log-server-schedule-name", "hardware", "dynamic-ip", "sic-name", "sic-state",
"send-alerts-to-server",
"send-logs-to-backup-server", "send-logs-to-server", "interfaces"],
"application-site": ["application-id", "risk", "user-defined"],
"application-site-category": ["user-defined"],
"data-center-object": ["name-in-data-center", "data-center", "data-center-object-meta-info", "deleted",
"type-in-data-center", "additional-properties"]
}
fields_to_change = {
"alert-when-free-disk-space-below-metrics": "free-disk-space-metrics",
"delete-index-files-when-index-size-above-metrics": "free-disk-space-metrics",
"delete-when-free-disk-space-below-metrics": "free-disk-space-metrics",
"stop-logging-when-free-disk-space-below-metrics": "free-disk-space-metrics"
}
fields_to_exclude_in_the_presence_of_other_fields = {
"maximum-limit-for-concurrent-connections": "auto-maximum-limit-for-concurrent-connections",
"maximum-memory-pool-size": "auto-calculate-connections-hash-table-size-and-memory-pool",
"memory-pool-size": "auto-calculate-connections-hash-table-size-and-memory-pool"
}
fields_to_exclude_from_import_by_api_type_and_versions = {
"network": {
"broadcast": ["1"]
}
}
partially_exportable_types = ["simple-gateway"]
special_treatment_types = [
"threat-profile"
]
https_blades_names_map = {
"Anti-Virus": "Anti Virus",
"Anti-Bot": "Anti Bot",
"URL Filtering": "Url Filtering",
"Data Loss Prevention": "DLP",
"Content Awareness": "Data Awareness"
}
commands_support_batch = ['access-role', 'address-range', 'application-site-category',
'application-site-group', 'dns-domain', 'dynamic-object',
'group-with-exclusion', 'host', 'lsv-profile', 'multicast-address-range',
'network', 'package', 'security-zone', 'service-dce-rpc', 'service-group',
'service-icmp', 'service-other', 'service-sctp', 'service-tcp', 'service-udp',
'tacacs-server', 'tacacs-group', 'tag', 'time', 'time-group',
'vpn-community-meshed', 'vpn-community-star', 'wildcard']
rule_support_batch = ['access-rule', 'https-rule', 'nat-rule', 'threat-exception']
not_unique_name_with_dedicated_api = {
"Unknown Traffic": "show-application-site-category"
}
types_not_support_tagging = ["rule", "section", "threat-exception"]
| singular_to_plural_dictionary = {'1': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions'}, '1.1': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions'}, '1.2': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards'}, '1.3': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects'}, '1.4': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects'}, '1.5': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects'}, '1.6': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects', 'https-layer': 'https-layers', 'https-section': 'https-sections', 'https-rule': 'https-rules'}, '1.6.1': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects', 'https-layer': 'https-layers', 'https-section': 'https-sections', 'https-rule': 'https-rules'}, '1.7': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects', 'https-layer': 'https-layers', 'https-section': 'https-sections', 'https-rule': 'https-rules'}, '1.7.1': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects', 'https-layer': 'https-layers', 'https-section': 'https-sections', 'https-rule': 'https-rules'}, '1.8': {'access-role': 'access-roles', 'threat-profile': 'threat-profiles', 'host': 'hosts', 'network': 'networks', 'address-range': 'address_ranges', 'multicast-address-range': 'multicast-address-ranges', 'security-zone': 'security-zones', 'time': 'times', 'simple-gateway': 'simple-gateways', 'dynamic-object': 'dynamic-objects', 'trusted-client': 'trusted-clients', 'tags': 'tags', 'dns-domain': 'dns-domains', 'opsec-application': 'opsec-applications', 'data-center': 'data-centers', 'data-center-object': 'data-center-objects', 'service-tcp': 'services-tcp', 'service-udp': 'services-udp', 'service-icmp': 'services-icmp', 'service-icmp6': 'services-icmp6', 'service-sctp': 'services-sctp', 'service-rpc': 'services-rpc', 'service-other': 'services-other', 'service-dce-rpc': 'services-dce-rpc', 'application-site': 'applications-sites', 'application-site-category': 'application-site-categories', 'application-site-group': 'application-site-groups', 'vpn-community-meshed': 'vpn-communities-meshed', 'vpn-community-star': 'vpn-communities-star', 'placeholder': 'placeholders', 'administrator': 'administrators', 'group': 'groups', 'group-with-exclusion': 'groups-with-exclusion', 'service-group': 'service-groups', 'time-group': 'time-groups', 'application-group': 'application-groups', 'threat-protection': 'threat-protections', 'exception-group': 'exception-groups', 'generic-object': '', 'access-layer': 'access-layers', 'access-section': 'access-sections', 'access-rule': 'access-rules', 'nat-layer': 'nat-layers', 'nat-section': 'nat-sections', 'nat-rule': 'nat-rules', 'threat-layer': 'threat-layers', 'threat-rule': 'threat-rules', 'threat-exception-section': 'threat-exception-sections', 'threat-exception': 'threat-exceptions', 'wildcard': 'wildcards', 'updatable-object': 'updatable-objects', 'https-layer': 'https-layers', 'https-section': 'https-sections', 'https-rule': 'https-rules'}}
unexportable_objects_map = {}
import_priority = {'vpn-community-meshed': 1, 'vpn-community-star': 1, 'group': 2, 'group-with-exclusion': 3, 'service-group': 2, 'time-group': 2, 'application-group': 2}
generic_objects_for_rule_fields = {'source': ['host', 'ip-address'], 'destination': ['host', 'ip-address'], 'vpn': ['vpn-community-star'], 'service': ['service-tcp', 'port'], 'protected-scope': ['multicast-address-range', 'ip-address']}
generic_objects_for_duplicates_in_group_members = {'group': ['host', 'ip-address'], 'service-group': ['service-tcp', 'port'], 'time-group': ['time']}
placeholder_type_by_obj_type = {'DataType': {'type': 'com.checkpoint.management.data_awareness.objects.DataAwarenessCompound'}, 'DropUserCheckInteractionScheme': {'bladeName': 'APPC', 'type': 'com.checkpoint.objects.user_check.DropUserCheckInteractionScheme'}, 'AskUserCheckInteractionScheme': {'bladeName': 'APPC', 'type': 'com.checkpoint.objects.user_check.AskUserCheckInteractionScheme'}, 'InformUserCheckInteractionScheme': {'bladeName': 'APPC', 'type': 'com.checkpoint.objects.user_check.InformUserCheckInteractionScheme'}, 'CpmiGatewayCluster': {'ipsBlade': 'INSTALLED', 'type': 'com.checkpoint.objects.classes.dummy.CpmiGatewayCluster'}, 'CpmiVsClusterNetobj': {'ipsBlade': 'INSTALLED', 'type': 'com.checkpoint.objects.classes.dummy.CpmiGatewayCluster'}, 'CpmiGatewayPlain': {'type': 'com.checkpoint.objects.classes.dummy.CpmiGatewayCkp', 'ipaddr': None, 'vpn1': 'true'}, 'CpmiIcmpService': {'type': 'com.checkpoint.objects.classes.dummy.CpmiIcmpService'}, 'CpmiIcmp6Service': {'type': 'com.checkpoint.objects.classes.dummy.CpmiIcmp6Service'}, 'CpmiAppfwLimit': {'type': 'com.checkpoint.objects.appfw.dummy.CpmiAppfwLimit'}, 'service-other': {'type': 'com.checkpoint.objects.classes.dummy.CpmiOtherService', 'matchExp': 'Dummy Match Expression'}}
group_objects_field = {'group': ['members'], 'vpn-community-star': ['center-gateways', 'satellite-gateways'], 'vpn-community-meshed': ['gateways'], 'service-group': ['members'], 'time-group': ['members'], 'application-site-group': ['members'], 'group-with-exclusion': []}
no_export_fields = {'type'}
no_export_fields_and_subfields = ['read-only', 'layer', 'package', 'owner', 'icon', 'domain', 'from', 'to', 'rulebase', 'uid', 'meta-info', 'parent', 'groups', 'type', 'override-default-settings']
no_export_fields_by_api_type = {'host': ['standard-port-number', 'subnet-mask', 'type'], 'network': ['subnet-mask'], 'threat-rule': ['exceptions', 'exceptions-layer'], 'simple-gateway': ['forward-logs-to-log-server-schedule-name', 'hardware', 'dynamic-ip', 'sic-name', 'sic-state', 'send-alerts-to-server', 'send-logs-to-backup-server', 'send-logs-to-server', 'interfaces'], 'application-site': ['application-id', 'risk', 'user-defined'], 'application-site-category': ['user-defined'], 'data-center-object': ['name-in-data-center', 'data-center', 'data-center-object-meta-info', 'deleted', 'type-in-data-center', 'additional-properties']}
fields_to_change = {'alert-when-free-disk-space-below-metrics': 'free-disk-space-metrics', 'delete-index-files-when-index-size-above-metrics': 'free-disk-space-metrics', 'delete-when-free-disk-space-below-metrics': 'free-disk-space-metrics', 'stop-logging-when-free-disk-space-below-metrics': 'free-disk-space-metrics'}
fields_to_exclude_in_the_presence_of_other_fields = {'maximum-limit-for-concurrent-connections': 'auto-maximum-limit-for-concurrent-connections', 'maximum-memory-pool-size': 'auto-calculate-connections-hash-table-size-and-memory-pool', 'memory-pool-size': 'auto-calculate-connections-hash-table-size-and-memory-pool'}
fields_to_exclude_from_import_by_api_type_and_versions = {'network': {'broadcast': ['1']}}
partially_exportable_types = ['simple-gateway']
special_treatment_types = ['threat-profile']
https_blades_names_map = {'Anti-Virus': 'Anti Virus', 'Anti-Bot': 'Anti Bot', 'URL Filtering': 'Url Filtering', 'Data Loss Prevention': 'DLP', 'Content Awareness': 'Data Awareness'}
commands_support_batch = ['access-role', 'address-range', 'application-site-category', 'application-site-group', 'dns-domain', 'dynamic-object', 'group-with-exclusion', 'host', 'lsv-profile', 'multicast-address-range', 'network', 'package', 'security-zone', 'service-dce-rpc', 'service-group', 'service-icmp', 'service-other', 'service-sctp', 'service-tcp', 'service-udp', 'tacacs-server', 'tacacs-group', 'tag', 'time', 'time-group', 'vpn-community-meshed', 'vpn-community-star', 'wildcard']
rule_support_batch = ['access-rule', 'https-rule', 'nat-rule', 'threat-exception']
not_unique_name_with_dedicated_api = {'Unknown Traffic': 'show-application-site-category'}
types_not_support_tagging = ['rule', 'section', 'threat-exception'] |
class Node:
def __init__(self, node_id, lon, lat, cluster_id_belongto: int):
self.node_id = int(node_id)
self.lon = lon
self.lat = lat
self.cluster_id_belongto = cluster_id_belongto | class Node:
def __init__(self, node_id, lon, lat, cluster_id_belongto: int):
self.node_id = int(node_id)
self.lon = lon
self.lat = lat
self.cluster_id_belongto = cluster_id_belongto |
# cook your dish here
t = int(input()) # Taking the Number of Test Cases
for i in range(t): # Looping over test cases
n = int(input()) # Taking the length of songs input
p = [int(i) for i in input().split()] # Taking the list of song length as input
k = int(input()) # Taking the position of the uncle jhony song(taking indexing from 1)
ele = p[k-1] # Storing that element in a variable (position was taken -1 as indexing of our list is from 0 and user entered according to indexing starting from 1)
for i in range(n): # Here for sorting the list we use bubble sort algorithm
j = 0 # bubble sorting program - line 10 to 14
for j in range(0, n-i-1):
if p[j] > p[j+1]:
p[j], p[j+1] = p[j+1], p[j]
ls = (p.index(ele)) # Now geeting the position of uncle jhony song in sorted list.
print(ls+1) # Printing the position + 1 as the indexing started from 0.
| t = int(input())
for i in range(t):
n = int(input())
p = [int(i) for i in input().split()]
k = int(input())
ele = p[k - 1]
for i in range(n):
j = 0
for j in range(0, n - i - 1):
if p[j] > p[j + 1]:
(p[j], p[j + 1]) = (p[j + 1], p[j])
ls = p.index(ele)
print(ls + 1) |
print("Insert a string")
s = input()
print("Insert the number of times it will be repeated")
n = int(input())
res = ""
for i in range(n):
res = res + s
print(res)
| print('Insert a string')
s = input()
print('Insert the number of times it will be repeated')
n = int(input())
res = ''
for i in range(n):
res = res + s
print(res) |
#Twitter API Credentials
consumer_key = 'consumerkey'
consumer_secret = 'consumersecret'
access_token = 'accesstoken'
access_secret = 'accesssecret'
| consumer_key = 'consumerkey'
consumer_secret = 'consumersecret'
access_token = 'accesstoken'
access_secret = 'accesssecret' |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
class BerkeleyDb(AutotoolsPackage):
"""Oracle Berkeley DB"""
homepage = "https://www.oracle.com/database/technologies/related/berkeleydb.html"
# URL must remain http:// so Spack can bootstrap curl
url = "http://download.oracle.com/berkeley-db/db-18.1.40.tar.gz"
version("18.1.40", sha256="0cecb2ef0c67b166de93732769abdeba0555086d51de1090df325e18ee8da9c8")
version('18.1.32', sha256='fa1fe7de9ba91ad472c25d026f931802597c29f28ae951960685cde487c8d654', deprecated=True)
version('6.2.32', sha256='a9c5e2b004a5777aa03510cfe5cd766a4a3b777713406b02809c17c8e0e7a8fb')
version('6.1.29', sha256='b3c18180e4160d97dd197ba1d37c19f6ea2ec91d31bbfaf8972d99ba097af17d')
version('6.0.35', sha256='24421affa8ae436fe427ae4f5f2d1634da83d3d55a5ad6354a98eeedb825de55', deprecated=True)
version('5.3.28', sha256='e0a992d740709892e81f9d93f06daf305cf73fb81b545afe72478043172c3628')
variant('docs', default=False)
variant('cxx', default=False, description='Build with C++ API')
variant('stl', default=False, description='Build with C++ STL API')
configure_directory = 'dist'
build_directory = 'build_unix'
patch("drop-docs.patch", when='~docs')
conflicts('%clang@7:', when='@5.3.28')
conflicts('%gcc@8:', when='@5.3.28')
conflicts('+stl', when='~cxx', msg='+stl implies +cxx')
def patch(self):
# some of the docs are missing in 18.1.40
if self.spec.satisfies("@18.1.40"):
filter_file(r'bdb-sql', '', 'dist/Makefile.in')
filter_file(r'gsg_db_server', '', 'dist/Makefile.in')
def configure_args(self):
spec = self.spec
config_args = [
'--disable-static',
'--enable-dbm',
# compat with system berkeley-db on darwin
"--enable-compat185",
# SSL support requires OpenSSL, but OpenSSL depends on Perl, which
# depends on Berkey DB, creating a circular dependency
'--with-repmgr-ssl=no',
]
config_args += self.enable_or_disable('cxx')
config_args += self.enable_or_disable('stl')
# The default glibc provided by CentOS 7 and Red Hat 8 does not provide
# proper atomic support when using the NVIDIA compilers
if (spec.satisfies('%nvhpc')
and (spec.satisfies('os=centos7') or spec.satisfies('os=rhel8'))):
config_args.append('--disable-atomicsupport')
return config_args
def test(self):
"""Perform smoke tests on the installed package binaries."""
exes = [
'db_checkpoint', 'db_deadlock', 'db_dump', 'db_load',
'db_printlog', 'db_stat', 'db_upgrade', 'db_verify'
]
for exe in exes:
reason = 'test version of {0} is {1}'.format(exe,
self.spec.version)
self.run_test(exe, ['-V'], [self.spec.version.string],
installed=True, purpose=reason, skip_missing=True)
| class Berkeleydb(AutotoolsPackage):
"""Oracle Berkeley DB"""
homepage = 'https://www.oracle.com/database/technologies/related/berkeleydb.html'
url = 'http://download.oracle.com/berkeley-db/db-18.1.40.tar.gz'
version('18.1.40', sha256='0cecb2ef0c67b166de93732769abdeba0555086d51de1090df325e18ee8da9c8')
version('18.1.32', sha256='fa1fe7de9ba91ad472c25d026f931802597c29f28ae951960685cde487c8d654', deprecated=True)
version('6.2.32', sha256='a9c5e2b004a5777aa03510cfe5cd766a4a3b777713406b02809c17c8e0e7a8fb')
version('6.1.29', sha256='b3c18180e4160d97dd197ba1d37c19f6ea2ec91d31bbfaf8972d99ba097af17d')
version('6.0.35', sha256='24421affa8ae436fe427ae4f5f2d1634da83d3d55a5ad6354a98eeedb825de55', deprecated=True)
version('5.3.28', sha256='e0a992d740709892e81f9d93f06daf305cf73fb81b545afe72478043172c3628')
variant('docs', default=False)
variant('cxx', default=False, description='Build with C++ API')
variant('stl', default=False, description='Build with C++ STL API')
configure_directory = 'dist'
build_directory = 'build_unix'
patch('drop-docs.patch', when='~docs')
conflicts('%clang@7:', when='@5.3.28')
conflicts('%gcc@8:', when='@5.3.28')
conflicts('+stl', when='~cxx', msg='+stl implies +cxx')
def patch(self):
if self.spec.satisfies('@18.1.40'):
filter_file('bdb-sql', '', 'dist/Makefile.in')
filter_file('gsg_db_server', '', 'dist/Makefile.in')
def configure_args(self):
spec = self.spec
config_args = ['--disable-static', '--enable-dbm', '--enable-compat185', '--with-repmgr-ssl=no']
config_args += self.enable_or_disable('cxx')
config_args += self.enable_or_disable('stl')
if spec.satisfies('%nvhpc') and (spec.satisfies('os=centos7') or spec.satisfies('os=rhel8')):
config_args.append('--disable-atomicsupport')
return config_args
def test(self):
"""Perform smoke tests on the installed package binaries."""
exes = ['db_checkpoint', 'db_deadlock', 'db_dump', 'db_load', 'db_printlog', 'db_stat', 'db_upgrade', 'db_verify']
for exe in exes:
reason = 'test version of {0} is {1}'.format(exe, self.spec.version)
self.run_test(exe, ['-V'], [self.spec.version.string], installed=True, purpose=reason, skip_missing=True) |
def findXorSum(arr, n):
Sum = 0
mul = 1
for i in range(30):
c_odd = 0
odd = 0
for j in range(n):
if ((arr[j] & (1 << i)) > 0):
odd = (~odd)
if (odd):
c_odd += 1
for j in range(n):
Sum += (mul * c_odd)%(10**9+7)
if ((arr[j] & (1 << i)) > 0):
c_odd = (n - j - c_odd)
mul *= 2
return Sum%(10**9+7) | def find_xor_sum(arr, n):
sum = 0
mul = 1
for i in range(30):
c_odd = 0
odd = 0
for j in range(n):
if arr[j] & 1 << i > 0:
odd = ~odd
if odd:
c_odd += 1
for j in range(n):
sum += mul * c_odd % (10 ** 9 + 7)
if arr[j] & 1 << i > 0:
c_odd = n - j - c_odd
mul *= 2
return Sum % (10 ** 9 + 7) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class APIException(Exception):
"""
Base class for all API exceptions.
"""
pass
class APIError(APIException):
"""
An API error signifies a problem with the server, a temporary issue or some other easily-repairable
problem.
"""
pass
class APIFailure(APIException):
"""
An API failure signifies a problem with your request (e.g.: invalid API), a problem with your data,
or any error that resulted from improper use.
"""
pass
class APIBadCall(APIFailure):
"""
Your API call doesn't match the API's specification. Check your arguments, service name, command &
version.
"""
pass
class APINotFound(APIFailure):
"""
The API you tried to call does not exist. (404)
"""
pass
class APIUnauthorized(APIFailure):
"""
The API you've attempted to call either requires a key, or your key has insufficient permissions.
If you're requesting user details, make sure their privacy level permits you to do so, or that you've
properly authorised said user. (401)
"""
pass
class APITooManyRequests(APIFailure):
"""
Too many requests has been made for your actual plan. (429)
"""
pass
def check(response):
"""
:type response: requests.Response
"""
if response.status_code // 100 == 4:
if response.status_code == 404:
raise APINotFound("The function or service you tried to call does not exist.")
elif response.status_code == 401:
raise APIUnauthorized("This API is not accessible to you.")
elif response.status_code == 429:
raise APITooManyRequests("Limitations has been reached for you actual plan.")
elif response.status_code == 400:
raise APIBadCall("The parameters you sent didn't match this API's requirements.")
else:
raise APIFailure("Something is wrong with your configuration, parameters or environment.")
elif response.status_code // 100 == 5:
raise APIError("The API server has encountered an unknown error.")
else:
return
| class Apiexception(Exception):
"""
Base class for all API exceptions.
"""
pass
class Apierror(APIException):
"""
An API error signifies a problem with the server, a temporary issue or some other easily-repairable
problem.
"""
pass
class Apifailure(APIException):
"""
An API failure signifies a problem with your request (e.g.: invalid API), a problem with your data,
or any error that resulted from improper use.
"""
pass
class Apibadcall(APIFailure):
"""
Your API call doesn't match the API's specification. Check your arguments, service name, command &
version.
"""
pass
class Apinotfound(APIFailure):
"""
The API you tried to call does not exist. (404)
"""
pass
class Apiunauthorized(APIFailure):
"""
The API you've attempted to call either requires a key, or your key has insufficient permissions.
If you're requesting user details, make sure their privacy level permits you to do so, or that you've
properly authorised said user. (401)
"""
pass
class Apitoomanyrequests(APIFailure):
"""
Too many requests has been made for your actual plan. (429)
"""
pass
def check(response):
"""
:type response: requests.Response
"""
if response.status_code // 100 == 4:
if response.status_code == 404:
raise api_not_found('The function or service you tried to call does not exist.')
elif response.status_code == 401:
raise api_unauthorized('This API is not accessible to you.')
elif response.status_code == 429:
raise api_too_many_requests('Limitations has been reached for you actual plan.')
elif response.status_code == 400:
raise api_bad_call("The parameters you sent didn't match this API's requirements.")
else:
raise api_failure('Something is wrong with your configuration, parameters or environment.')
elif response.status_code // 100 == 5:
raise api_error('The API server has encountered an unknown error.')
else:
return |
#
# PySNMP MIB module CISCOSB-TBI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-TBI-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:23:42 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")
ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint")
switch001, = mibBuilder.importSymbols("CISCOSB-MIB", "switch001")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
NotificationType, TimeTicks, MibIdentifier, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, ModuleIdentity, Gauge32, Bits, iso, Counter32, Unsigned32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "TimeTicks", "MibIdentifier", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "ModuleIdentity", "Gauge32", "Bits", "iso", "Counter32", "Unsigned32", "Counter64")
RowStatus, DisplayString, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention", "TruthValue")
rlTBIMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145))
rlTBIMib.setRevisions(('2006-02-12 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: rlTBIMib.setRevisionsDescriptions(('Time Range Infrastructure MIBs initial version. ',))
if mibBuilder.loadTexts: rlTBIMib.setLastUpdated('200604040000Z')
if mibBuilder.loadTexts: rlTBIMib.setOrganization('Cisco Small Business')
if mibBuilder.loadTexts: rlTBIMib.setContactInfo('Postal: 170 West Tasman Drive San Jose , CA 95134-1706 USA Website: Cisco Small Business Home http://www.cisco.com/smb>;, Cisco Small Business Support Community <http://www.cisco.com/go/smallbizsupport>')
if mibBuilder.loadTexts: rlTBIMib.setDescription('Time Range Infrastructure MIBs initial version. ')
rlTBITimeRangeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1), )
if mibBuilder.loadTexts: rlTBITimeRangeTable.setStatus('current')
if mibBuilder.loadTexts: rlTBITimeRangeTable.setDescription('This table specifies Time Based Infra table')
rlTBITimeRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1), ).setIndexNames((1, "CISCOSB-TBI-MIB", "rlTBITimeRangeName"))
if mibBuilder.loadTexts: rlTBITimeRangeEntry.setStatus('current')
if mibBuilder.loadTexts: rlTBITimeRangeEntry.setDescription('Each entry in this table describes the new time range for ACE. The index is time range name')
rlTBITimeRangeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: rlTBITimeRangeName.setStatus('current')
if mibBuilder.loadTexts: rlTBITimeRangeName.setDescription('Name of time range.')
rlTBITimeRangeAbsoluteStart = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 14))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteStart.setStatus('current')
if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteStart.setDescription('Time of start of absolute time range in following format: month day year hh:mm month: 01-12 (January-December) day: 01-31 year: 0-99 (2000-2099) hh: 0-23 (hours) mm: 0-59 (minutes)')
rlTBITimeRangeAbsoluteEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 14))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteEnd.setStatus('current')
if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteEnd.setDescription('Time of end of absolute time range in following format: month day year hh:mm month: 01-12 (January-December) day: 01-31 year: 0-99 (2000-2099) hh: 0-23 (hours) mm: 0-59 (minutes)')
rlTBITimeRangeActiveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 4), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: rlTBITimeRangeActiveStatus.setStatus('current')
if mibBuilder.loadTexts: rlTBITimeRangeActiveStatus.setDescription('Shows whether the current time range is active according to the current clock.')
rlTBITimeRangeRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlTBITimeRangeRowStatus.setStatus('current')
if mibBuilder.loadTexts: rlTBITimeRangeRowStatus.setDescription('Row Status. It is used for adding/deleting entries of this table.')
class RlTBIWeekDayList(TextualConvention, Bits):
description = 'Bitmap that includes days of week. Each bit in the bitmap associated with corresponding day of the week.'
status = 'current'
namedValues = NamedValues(("monday", 0), ("tuesday", 1), ("wednesday", 2), ("thursday", 3), ("friday", 4), ("saturday", 5), ("sunday", 6))
rlTBIPeriodicTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2), )
if mibBuilder.loadTexts: rlTBIPeriodicTable.setStatus('current')
if mibBuilder.loadTexts: rlTBIPeriodicTable.setDescription('This table specifies Time Based Infra Periodic table')
rlTBIPeriodicEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1), ).setIndexNames((0, "CISCOSB-TBI-MIB", "rlTBIPeriodicTimeRangeName"), (0, "CISCOSB-TBI-MIB", "rlTBIPeriodicWeekDayList"), (0, "CISCOSB-TBI-MIB", "rlTBIPeriodicStart"), (0, "CISCOSB-TBI-MIB", "rlTBIPeriodicEnd"))
if mibBuilder.loadTexts: rlTBIPeriodicEntry.setStatus('current')
if mibBuilder.loadTexts: rlTBIPeriodicEntry.setDescription('Each entry in this table describes periodic time range.')
rlTBIPeriodicTimeRangeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)))
if mibBuilder.loadTexts: rlTBIPeriodicTimeRangeName.setStatus('current')
if mibBuilder.loadTexts: rlTBIPeriodicTimeRangeName.setDescription('Time Range Name the periodic is defined on. ')
rlTBIPeriodicWeekDayList = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 2), RlTBIWeekDayList()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlTBIPeriodicWeekDayList.setStatus('current')
if mibBuilder.loadTexts: rlTBIPeriodicWeekDayList.setDescription('The bitmap allows to user to select periodic time range for several days at once. The periodic range will be associated with specific days when corresponding bits will be set. If at least one bit has been set in the rlTBIPeriodicWeekDayList, the weekday in rlTBIPeriodicStart and rlTBIPeriodicEnd is not relevant and should be set to zero.')
rlTBIPeriodicStart = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 7))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlTBIPeriodicStart.setStatus('current')
if mibBuilder.loadTexts: rlTBIPeriodicStart.setDescription('Time of start of periodic time range in following format: weekday hh:mm weekday: 0-7 (0 means the weekday is not specified, 1-7 are weekdays from Monday to Sunday) hh: 0-23 (hours) mm: 0-59 (minutes) Weekday may be 0 only if periodic time range weekdays were specified in rlTBIPeriodicWeekDayList.')
rlTBIPeriodicEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 7))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: rlTBIPeriodicEnd.setStatus('current')
if mibBuilder.loadTexts: rlTBIPeriodicEnd.setDescription('Time of end of periodic time range in following format: weekday hh:mm weekday: 0-7 (0 means the weekday is not specified, 1-7 are weekdays from Monday to Sunday) hh: 0-23 (hours) mm: 0-59 (minutes) Weekday may be 0 only if periodic time range weekdays were specified in rlTBIPeriodicWeekDayList.')
rlTBIPeriodicRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: rlTBIPeriodicRowStatus.setStatus('current')
if mibBuilder.loadTexts: rlTBIPeriodicRowStatus.setDescription('Row Status. It is used for adding/deleting entries of this table.')
mibBuilder.exportSymbols("CISCOSB-TBI-MIB", rlTBIPeriodicEnd=rlTBIPeriodicEnd, PYSNMP_MODULE_ID=rlTBIMib, rlTBIPeriodicRowStatus=rlTBIPeriodicRowStatus, rlTBIPeriodicEntry=rlTBIPeriodicEntry, rlTBITimeRangeName=rlTBITimeRangeName, rlTBIPeriodicTimeRangeName=rlTBIPeriodicTimeRangeName, rlTBITimeRangeAbsoluteStart=rlTBITimeRangeAbsoluteStart, rlTBITimeRangeActiveStatus=rlTBITimeRangeActiveStatus, RlTBIWeekDayList=RlTBIWeekDayList, rlTBIPeriodicWeekDayList=rlTBIPeriodicWeekDayList, rlTBIMib=rlTBIMib, rlTBIPeriodicStart=rlTBIPeriodicStart, rlTBITimeRangeAbsoluteEnd=rlTBITimeRangeAbsoluteEnd, rlTBITimeRangeEntry=rlTBITimeRangeEntry, rlTBITimeRangeTable=rlTBITimeRangeTable, rlTBIPeriodicTable=rlTBIPeriodicTable, rlTBITimeRangeRowStatus=rlTBITimeRangeRowStatus)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint')
(switch001,) = mibBuilder.importSymbols('CISCOSB-MIB', 'switch001')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(notification_type, time_ticks, mib_identifier, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, ip_address, module_identity, gauge32, bits, iso, counter32, unsigned32, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'TimeTicks', 'MibIdentifier', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'IpAddress', 'ModuleIdentity', 'Gauge32', 'Bits', 'iso', 'Counter32', 'Unsigned32', 'Counter64')
(row_status, display_string, textual_convention, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TextualConvention', 'TruthValue')
rl_tbi_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145))
rlTBIMib.setRevisions(('2006-02-12 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
rlTBIMib.setRevisionsDescriptions(('Time Range Infrastructure MIBs initial version. ',))
if mibBuilder.loadTexts:
rlTBIMib.setLastUpdated('200604040000Z')
if mibBuilder.loadTexts:
rlTBIMib.setOrganization('Cisco Small Business')
if mibBuilder.loadTexts:
rlTBIMib.setContactInfo('Postal: 170 West Tasman Drive San Jose , CA 95134-1706 USA Website: Cisco Small Business Home http://www.cisco.com/smb>;, Cisco Small Business Support Community <http://www.cisco.com/go/smallbizsupport>')
if mibBuilder.loadTexts:
rlTBIMib.setDescription('Time Range Infrastructure MIBs initial version. ')
rl_tbi_time_range_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1))
if mibBuilder.loadTexts:
rlTBITimeRangeTable.setStatus('current')
if mibBuilder.loadTexts:
rlTBITimeRangeTable.setDescription('This table specifies Time Based Infra table')
rl_tbi_time_range_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1)).setIndexNames((1, 'CISCOSB-TBI-MIB', 'rlTBITimeRangeName'))
if mibBuilder.loadTexts:
rlTBITimeRangeEntry.setStatus('current')
if mibBuilder.loadTexts:
rlTBITimeRangeEntry.setDescription('Each entry in this table describes the new time range for ACE. The index is time range name')
rl_tbi_time_range_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 32)))
if mibBuilder.loadTexts:
rlTBITimeRangeName.setStatus('current')
if mibBuilder.loadTexts:
rlTBITimeRangeName.setDescription('Name of time range.')
rl_tbi_time_range_absolute_start = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 14))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlTBITimeRangeAbsoluteStart.setStatus('current')
if mibBuilder.loadTexts:
rlTBITimeRangeAbsoluteStart.setDescription('Time of start of absolute time range in following format: month day year hh:mm month: 01-12 (January-December) day: 01-31 year: 0-99 (2000-2099) hh: 0-23 (hours) mm: 0-59 (minutes)')
rl_tbi_time_range_absolute_end = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 14))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlTBITimeRangeAbsoluteEnd.setStatus('current')
if mibBuilder.loadTexts:
rlTBITimeRangeAbsoluteEnd.setDescription('Time of end of absolute time range in following format: month day year hh:mm month: 01-12 (January-December) day: 01-31 year: 0-99 (2000-2099) hh: 0-23 (hours) mm: 0-59 (minutes)')
rl_tbi_time_range_active_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 4), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
rlTBITimeRangeActiveStatus.setStatus('current')
if mibBuilder.loadTexts:
rlTBITimeRangeActiveStatus.setDescription('Shows whether the current time range is active according to the current clock.')
rl_tbi_time_range_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
rlTBITimeRangeRowStatus.setStatus('current')
if mibBuilder.loadTexts:
rlTBITimeRangeRowStatus.setDescription('Row Status. It is used for adding/deleting entries of this table.')
class Rltbiweekdaylist(TextualConvention, Bits):
description = 'Bitmap that includes days of week. Each bit in the bitmap associated with corresponding day of the week.'
status = 'current'
named_values = named_values(('monday', 0), ('tuesday', 1), ('wednesday', 2), ('thursday', 3), ('friday', 4), ('saturday', 5), ('sunday', 6))
rl_tbi_periodic_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2))
if mibBuilder.loadTexts:
rlTBIPeriodicTable.setStatus('current')
if mibBuilder.loadTexts:
rlTBIPeriodicTable.setDescription('This table specifies Time Based Infra Periodic table')
rl_tbi_periodic_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1)).setIndexNames((0, 'CISCOSB-TBI-MIB', 'rlTBIPeriodicTimeRangeName'), (0, 'CISCOSB-TBI-MIB', 'rlTBIPeriodicWeekDayList'), (0, 'CISCOSB-TBI-MIB', 'rlTBIPeriodicStart'), (0, 'CISCOSB-TBI-MIB', 'rlTBIPeriodicEnd'))
if mibBuilder.loadTexts:
rlTBIPeriodicEntry.setStatus('current')
if mibBuilder.loadTexts:
rlTBIPeriodicEntry.setDescription('Each entry in this table describes periodic time range.')
rl_tbi_periodic_time_range_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 32)))
if mibBuilder.loadTexts:
rlTBIPeriodicTimeRangeName.setStatus('current')
if mibBuilder.loadTexts:
rlTBIPeriodicTimeRangeName.setDescription('Time Range Name the periodic is defined on. ')
rl_tbi_periodic_week_day_list = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 2), rl_tbi_week_day_list()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlTBIPeriodicWeekDayList.setStatus('current')
if mibBuilder.loadTexts:
rlTBIPeriodicWeekDayList.setDescription('The bitmap allows to user to select periodic time range for several days at once. The periodic range will be associated with specific days when corresponding bits will be set. If at least one bit has been set in the rlTBIPeriodicWeekDayList, the weekday in rlTBIPeriodicStart and rlTBIPeriodicEnd is not relevant and should be set to zero.')
rl_tbi_periodic_start = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 7))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlTBIPeriodicStart.setStatus('current')
if mibBuilder.loadTexts:
rlTBIPeriodicStart.setDescription('Time of start of periodic time range in following format: weekday hh:mm weekday: 0-7 (0 means the weekday is not specified, 1-7 are weekdays from Monday to Sunday) hh: 0-23 (hours) mm: 0-59 (minutes) Weekday may be 0 only if periodic time range weekdays were specified in rlTBIPeriodicWeekDayList.')
rl_tbi_periodic_end = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 4), display_string().subtype(subtypeSpec=value_size_constraint(0, 7))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
rlTBIPeriodicEnd.setStatus('current')
if mibBuilder.loadTexts:
rlTBIPeriodicEnd.setDescription('Time of end of periodic time range in following format: weekday hh:mm weekday: 0-7 (0 means the weekday is not specified, 1-7 are weekdays from Monday to Sunday) hh: 0-23 (hours) mm: 0-59 (minutes) Weekday may be 0 only if periodic time range weekdays were specified in rlTBIPeriodicWeekDayList.')
rl_tbi_periodic_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 5), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
rlTBIPeriodicRowStatus.setStatus('current')
if mibBuilder.loadTexts:
rlTBIPeriodicRowStatus.setDescription('Row Status. It is used for adding/deleting entries of this table.')
mibBuilder.exportSymbols('CISCOSB-TBI-MIB', rlTBIPeriodicEnd=rlTBIPeriodicEnd, PYSNMP_MODULE_ID=rlTBIMib, rlTBIPeriodicRowStatus=rlTBIPeriodicRowStatus, rlTBIPeriodicEntry=rlTBIPeriodicEntry, rlTBITimeRangeName=rlTBITimeRangeName, rlTBIPeriodicTimeRangeName=rlTBIPeriodicTimeRangeName, rlTBITimeRangeAbsoluteStart=rlTBITimeRangeAbsoluteStart, rlTBITimeRangeActiveStatus=rlTBITimeRangeActiveStatus, RlTBIWeekDayList=RlTBIWeekDayList, rlTBIPeriodicWeekDayList=rlTBIPeriodicWeekDayList, rlTBIMib=rlTBIMib, rlTBIPeriodicStart=rlTBIPeriodicStart, rlTBITimeRangeAbsoluteEnd=rlTBITimeRangeAbsoluteEnd, rlTBITimeRangeEntry=rlTBITimeRangeEntry, rlTBITimeRangeTable=rlTBITimeRangeTable, rlTBIPeriodicTable=rlTBIPeriodicTable, rlTBITimeRangeRowStatus=rlTBITimeRangeRowStatus) |
def pation(nums):
tmp = nums[0]
nums[0] = nums[1]
nums[1] = tmp
return 1
def main():
nums = [3,2,1]
p = pation(nums)
for n in nums:
print(n)
if __name__ == "__main__":
main()
| def pation(nums):
tmp = nums[0]
nums[0] = nums[1]
nums[1] = tmp
return 1
def main():
nums = [3, 2, 1]
p = pation(nums)
for n in nums:
print(n)
if __name__ == '__main__':
main() |
def create_grades_dict(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
no_return_list = []
for item in data:
no_return_list.append(item.strip('\n'))
no_spaces_list =[]
for item in no_return_list:
no_spaces_list.append(item.replace(' ',''))
list_of_lists = []
for x in no_spaces_list:
list_of_lists.append(x.split(','))
tests_list=['Test_1', 'Test_2', 'Test_3', 'Test_4']
dictionary = {}
#making the structure of the dictionary
for student_id in list_of_lists:
dictionary[student_id[0]] = [student_id[1], 0, 0, 0, 0, 0]
#average calculated and saved to dictionary position
for lists in list_of_lists:
average = 0
for x in range(2, len(lists)):
if lists[x] in tests_list:
position_number = tests_list.index(lists[x])+1
dictionary[lists[0]][position_number] = int(lists[x+1])
average += int(lists[lists.index(lists[x])+1])
dictionary[lists[0]][5] = average/4
return dictionary
# Your main program starts below this line
def print_grades(file_name):
# Call your create_grades_dict() function to create the dictionary
grades_dict=create_grades_dict(file_name)
#formatting and printing header
header_list = ["ID", "Name", "Test_1", "Test_2", "Test_3", "Test_4", "Avg."]
print("{0: ^10} | {1: ^16} | {2: ^6} | {3: ^6} | {4: ^6} | {5: ^6} | {6: ^6} |".format(header_list[0], header_list[1], header_list[2],
header_list[3], header_list[4], header_list[5], header_list[6]))
#converting tuple in list
keys_order_list = list(grades_dict.keys())
keys_order_list.sort()
ordered_list = []
for key in keys_order_list:
aux_list = [key]
for item in grades_dict[key]:
aux_list.append(item)
ordered_list.append(aux_list)
#formatting and printing body
for listed in ordered_list:
print("{0:10s} | {1:16s} | {2:6d} | {3:6d} | {4:6d} | {5:6d} | {6:6.2f} |".format(listed[0], listed[1], listed[2],
listed[3], listed[4], listed[5], listed[6]))
print(print_grades('archivo.txt')) | def create_grades_dict(file_name):
file_pointer = open(file_name, 'r')
data = file_pointer.readlines()
no_return_list = []
for item in data:
no_return_list.append(item.strip('\n'))
no_spaces_list = []
for item in no_return_list:
no_spaces_list.append(item.replace(' ', ''))
list_of_lists = []
for x in no_spaces_list:
list_of_lists.append(x.split(','))
tests_list = ['Test_1', 'Test_2', 'Test_3', 'Test_4']
dictionary = {}
for student_id in list_of_lists:
dictionary[student_id[0]] = [student_id[1], 0, 0, 0, 0, 0]
for lists in list_of_lists:
average = 0
for x in range(2, len(lists)):
if lists[x] in tests_list:
position_number = tests_list.index(lists[x]) + 1
dictionary[lists[0]][position_number] = int(lists[x + 1])
average += int(lists[lists.index(lists[x]) + 1])
dictionary[lists[0]][5] = average / 4
return dictionary
def print_grades(file_name):
grades_dict = create_grades_dict(file_name)
header_list = ['ID', 'Name', 'Test_1', 'Test_2', 'Test_3', 'Test_4', 'Avg.']
print('{0: ^10} | {1: ^16} | {2: ^6} | {3: ^6} | {4: ^6} | {5: ^6} | {6: ^6} |'.format(header_list[0], header_list[1], header_list[2], header_list[3], header_list[4], header_list[5], header_list[6]))
keys_order_list = list(grades_dict.keys())
keys_order_list.sort()
ordered_list = []
for key in keys_order_list:
aux_list = [key]
for item in grades_dict[key]:
aux_list.append(item)
ordered_list.append(aux_list)
for listed in ordered_list:
print('{0:10s} | {1:16s} | {2:6d} | {3:6d} | {4:6d} | {5:6d} | {6:6.2f} |'.format(listed[0], listed[1], listed[2], listed[3], listed[4], listed[5], listed[6]))
print(print_grades('archivo.txt')) |
#: docstring for CONSTANT1
CONSTANT1 = ""
CONSTANT2 = ""
| constant1 = ''
constant2 = '' |
l, r = map(int, input().split(" "))
if l == r:
print(l)
else:
print(2)
| (l, r) = map(int, input().split(' '))
if l == r:
print(l)
else:
print(2) |
class Session:
pass
class DB:
@staticmethod
def get_rds_host():
return '127.0.0.1'
def __init__(self, user, password, host, database) -> None:
pass
def getSession(self):
return Session
| class Session:
pass
class Db:
@staticmethod
def get_rds_host():
return '127.0.0.1'
def __init__(self, user, password, host, database) -> None:
pass
def get_session(self):
return Session |
CHAR_PLUS = ord(b'+')
CHAR_NEWLINE = ord(b'\n')
def buffered_blob(handle, bufsize):
backlog = b''
blob = b''
while True:
blob = handle.read(bufsize)
if blob == b'':
# Could be end of files
yield backlog
break
if backlog != b'':
blob = backlog + blob
i = blob.rfind(b'\n@', 0)
# Make sure no quality line was found
if (blob[i-1] == CHAR_PLUS) and (blob[i-2] == CHAR_NEWLINE):
i = blob.rfind(b'\n@', 0, i-2)
backlog = blob[i+1:len(blob)]
yield blob[0:i]
| char_plus = ord(b'+')
char_newline = ord(b'\n')
def buffered_blob(handle, bufsize):
backlog = b''
blob = b''
while True:
blob = handle.read(bufsize)
if blob == b'':
yield backlog
break
if backlog != b'':
blob = backlog + blob
i = blob.rfind(b'\n@', 0)
if blob[i - 1] == CHAR_PLUS and blob[i - 2] == CHAR_NEWLINE:
i = blob.rfind(b'\n@', 0, i - 2)
backlog = blob[i + 1:len(blob)]
yield blob[0:i] |
"""
Mock unicornhathd module.
The intention is to use this module when developing on a different computer than a Raspberry PI with the UnicornHAT
attached, e.g. on a Mac laptop. In such case, this module will simply provide the same functions as the original
uncornhathd module, however most of them will do absolutely nothing.
"""
def clear():
pass
def off():
pass
def show():
pass
def set_pixel(x, y, r, g, b):
print('UnicornHAT HD: setting pixel ({}, {}, {}, {}, {})'.format(x, y, r, g, b))
def brightness(b):
print('UnicornHAT HD: setting brightness to: {}'.format(b))
pass
def rotation(r):
print('UnicornHAT HD: setting rotation to: {}'.format(r))
pass
def get_shape():
return 16, 16
| """
Mock unicornhathd module.
The intention is to use this module when developing on a different computer than a Raspberry PI with the UnicornHAT
attached, e.g. on a Mac laptop. In such case, this module will simply provide the same functions as the original
uncornhathd module, however most of them will do absolutely nothing.
"""
def clear():
pass
def off():
pass
def show():
pass
def set_pixel(x, y, r, g, b):
print('UnicornHAT HD: setting pixel ({}, {}, {}, {}, {})'.format(x, y, r, g, b))
def brightness(b):
print('UnicornHAT HD: setting brightness to: {}'.format(b))
pass
def rotation(r):
print('UnicornHAT HD: setting rotation to: {}'.format(r))
pass
def get_shape():
return (16, 16) |
# general I/O parameters
OUTPUT_TYPE = "images"
LABEL_MAPPING = "pascal"
VIDEO_FILE = "data/videos/Ylojarvi-gridiajo-two-guys-moving.mov"
OUT_RESOLUTION = None # (3840, 2024)
OUTPUT_PATH = "data/predictions/Ylojarvi-gridiajo-two-guys-moving-air-output"
FRAME_OFFSET = 600 # 1560
PROCESS_NUM_FRAMES = 300
COMPRESS_VIDEO = True
# detection algorithm parameters
MODEL = "dauntless-sweep-2_resnet152_pascal-mob-inference.h5"
BACKBONE = "resnet152"
DETECT_EVERY_NTH_FRAME = 60
USE_TRACKING = True
PLOT_OBJECT_SPEED = False
SHOW_DETECTION_N_FRAMES = 30
USE_GPU = False
PROFILE = False
IMAGE_TILING_DIM = 2
IMAGE_MIN_SIDE = 1525
IMAGE_MAX_SIDE = 2025
# Results filtering settings
CONFIDENCE_THRES = 0.1
MAX_DETECTIONS_PER_FRAME = 10000
# Bounding box aggregation settings
MERGE_MODE = "enclose"
MOB_ITERS = 3
BBA_IOU_THRES = 0.001
TOP_K=25
| output_type = 'images'
label_mapping = 'pascal'
video_file = 'data/videos/Ylojarvi-gridiajo-two-guys-moving.mov'
out_resolution = None
output_path = 'data/predictions/Ylojarvi-gridiajo-two-guys-moving-air-output'
frame_offset = 600
process_num_frames = 300
compress_video = True
model = 'dauntless-sweep-2_resnet152_pascal-mob-inference.h5'
backbone = 'resnet152'
detect_every_nth_frame = 60
use_tracking = True
plot_object_speed = False
show_detection_n_frames = 30
use_gpu = False
profile = False
image_tiling_dim = 2
image_min_side = 1525
image_max_side = 2025
confidence_thres = 0.1
max_detections_per_frame = 10000
merge_mode = 'enclose'
mob_iters = 3
bba_iou_thres = 0.001
top_k = 25 |
class Coord(object):
"""
Represent Cartesian coordinates.
"""
def __init__(self, x=0, y=0):
self._x = x
self._y = y
class Data(object):
"""
Represent list of coordinates.
"""
def __init__(self):
self._data = []
| class Coord(object):
"""
Represent Cartesian coordinates.
"""
def __init__(self, x=0, y=0):
self._x = x
self._y = y
class Data(object):
"""
Represent list of coordinates.
"""
def __init__(self):
self._data = [] |
#!/usr/bin/env python
globaldecls = []
globalvars = {}
def add_new(decl):
if decl:
globaldecls.append(decl)
globalvars[decl.name] = decl
| globaldecls = []
globalvars = {}
def add_new(decl):
if decl:
globaldecls.append(decl)
globalvars[decl.name] = decl |
class BaseClass:
def __str__(self):
return self.__class__.__name__
def get_params(self, deep=True):
pass
def set_params(self, **params):
pass
class BaseTFWrapperSklearn(BaseClass):
def compile_graph(self, input_shapes):
pass
def get_tf_values(self, fetches, feed_dict):
pass
def save(self):
pass
def load(self):
pass
class tf_GAN(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def generate(self, zs):
pass
class tf_C_GAN(BaseTFWrapperSklearn):
def fit(self, Xs, Ys):
pass
def generate(self, zs, Ys):
pass
class tf_info_GAN(BaseTFWrapperSklearn):
def fit(self, Xs, Ys):
pass
def generate(self, zs, Ys):
pass
class tf_AE(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def code(self, Xs):
pass
def recon(self, zs):
pass
class tf_VAE(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def encode(self, Xs):
pass
def decode(self, zs):
pass
class tf_AAE(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def code(self, Xs):
pass
def recon(self, Xs, zs):
pass
class tf_AAEClassifier(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def code(self, Xs):
pass
def recon(self, Xs):
pass
def predict(self, Xs):
pass
def score(self, Xs, Ys):
pass
def proba(self, Xs):
pass
class tf_MLPClassifier(BaseTFWrapperSklearn):
def fit(self, Xs, Ys):
pass
def predict(self, Xs):
pass
def score(self, Xs, Ys):
pass
def proba(self, Xs):
pass
| class Baseclass:
def __str__(self):
return self.__class__.__name__
def get_params(self, deep=True):
pass
def set_params(self, **params):
pass
class Basetfwrappersklearn(BaseClass):
def compile_graph(self, input_shapes):
pass
def get_tf_values(self, fetches, feed_dict):
pass
def save(self):
pass
def load(self):
pass
class Tf_Gan(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def generate(self, zs):
pass
class Tf_C_Gan(BaseTFWrapperSklearn):
def fit(self, Xs, Ys):
pass
def generate(self, zs, Ys):
pass
class Tf_Info_Gan(BaseTFWrapperSklearn):
def fit(self, Xs, Ys):
pass
def generate(self, zs, Ys):
pass
class Tf_Ae(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def code(self, Xs):
pass
def recon(self, zs):
pass
class Tf_Vae(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def encode(self, Xs):
pass
def decode(self, zs):
pass
class Tf_Aae(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def code(self, Xs):
pass
def recon(self, Xs, zs):
pass
class Tf_Aaeclassifier(BaseTFWrapperSklearn):
def fit(self, Xs):
pass
def code(self, Xs):
pass
def recon(self, Xs):
pass
def predict(self, Xs):
pass
def score(self, Xs, Ys):
pass
def proba(self, Xs):
pass
class Tf_Mlpclassifier(BaseTFWrapperSklearn):
def fit(self, Xs, Ys):
pass
def predict(self, Xs):
pass
def score(self, Xs, Ys):
pass
def proba(self, Xs):
pass |
"""Utils for time travel testings."""
def _t(rel=0.0):
"""Return an absolute time from the relative time given.
The minimal allowed time in windows is 86400 seconds, for some reason. In
stead of doing the arithmetic in the tests themselves, this function should
be used.
The value `86400` is exported in `time_travel.MIN_START_TIME`, but I shant
use it for it is forbidden to test the code using the code that is being
tested.
"""
return 86400.0 + rel
| """Utils for time travel testings."""
def _t(rel=0.0):
"""Return an absolute time from the relative time given.
The minimal allowed time in windows is 86400 seconds, for some reason. In
stead of doing the arithmetic in the tests themselves, this function should
be used.
The value `86400` is exported in `time_travel.MIN_START_TIME`, but I shant
use it for it is forbidden to test the code using the code that is being
tested.
"""
return 86400.0 + rel |
# 289. Game of Life
class Solution:
def gameOfLife2(self, board) -> None:
rows, cols = len(board), len(board[0])
nextState = [row[:] for row in board]
dirs = ((0,1), (1,0), (-1,0), (0,-1), (-1,-1), (-1,1), (1,-1), (1,1))
for i in range(rows):
for j in range(cols):
nbrs = 0
for di, dj in dirs:
if 0 <= i+di < rows and 0 <= j+dj < cols:
nbrs += nextState[i+di][j+dj]
if nextState[i][j] == 1 and (nbrs < 2 or nbrs > 3):
board[i][j] = 0
elif nextState[i][j] == 0 and nbrs == 3:
board[i][j] = 1
return board
def gameOfLife(self, board) -> None:
rows, cols = len(board), len(board[0])
dirs = ((0,1), (1,0), (-1,0), (0,-1), (-1,-1), (-1,1), (1,-1), (1,1))
for i in range(rows):
for j in range(cols):
nbrs = 0
for di, dj in dirs:
if 0 <= i+di < rows and 0 <= j+dj < cols and board[i+di][j+dj] > 0:
nbrs += 1
board[i][j] = nbrs+10 if board[i][j] == 1 else -nbrs
for i in range(rows):
for j in range(cols):
if board[i][j] > 0:
if 12 <= board[i][j] <= 13:
board[i][j] = 1
else:
board[i][j] = 0
elif board[i][j] <= 0:
if board[i][j] == -3:
board[i][j] = 1
else:
board[i][j] = 0
return board
print(Solution().gameOfLife([[1,0,0,0,0,1],[0,0,0,1,1,0],[1,0,1,0,1,0],[1,0,0,0,1,0],[1,1,1,1,0,1],[0,1,1,0,1,0],[1,0,1,0,1,1],[1,0,0,1,1,1],[1,1,0,0,0,0]])) | class Solution:
def game_of_life2(self, board) -> None:
(rows, cols) = (len(board), len(board[0]))
next_state = [row[:] for row in board]
dirs = ((0, 1), (1, 0), (-1, 0), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1))
for i in range(rows):
for j in range(cols):
nbrs = 0
for (di, dj) in dirs:
if 0 <= i + di < rows and 0 <= j + dj < cols:
nbrs += nextState[i + di][j + dj]
if nextState[i][j] == 1 and (nbrs < 2 or nbrs > 3):
board[i][j] = 0
elif nextState[i][j] == 0 and nbrs == 3:
board[i][j] = 1
return board
def game_of_life(self, board) -> None:
(rows, cols) = (len(board), len(board[0]))
dirs = ((0, 1), (1, 0), (-1, 0), (0, -1), (-1, -1), (-1, 1), (1, -1), (1, 1))
for i in range(rows):
for j in range(cols):
nbrs = 0
for (di, dj) in dirs:
if 0 <= i + di < rows and 0 <= j + dj < cols and (board[i + di][j + dj] > 0):
nbrs += 1
board[i][j] = nbrs + 10 if board[i][j] == 1 else -nbrs
for i in range(rows):
for j in range(cols):
if board[i][j] > 0:
if 12 <= board[i][j] <= 13:
board[i][j] = 1
else:
board[i][j] = 0
elif board[i][j] <= 0:
if board[i][j] == -3:
board[i][j] = 1
else:
board[i][j] = 0
return board
print(solution().gameOfLife([[1, 0, 0, 0, 0, 1], [0, 0, 0, 1, 1, 0], [1, 0, 1, 0, 1, 0], [1, 0, 0, 0, 1, 0], [1, 1, 1, 1, 0, 1], [0, 1, 1, 0, 1, 0], [1, 0, 1, 0, 1, 1], [1, 0, 0, 1, 1, 1], [1, 1, 0, 0, 0, 0]])) |
cache = {}
def binomial_coeff(n, k):
"""Compute the binomial coefficient 'n choose k'.
n: number of trials
k: number of successes
returns: int
"""
if k == 0:
return 1
if n == 0:
return 0
try:
return cache[n,k]
except KeyError:
cache[n,k] = binomial_coeff(n-1, k-1) + binomial_coeff(n-1, k)
return cache[n,k]
def binomial_coeff(n, k=0):
if k == 0:
return 1
return 0 if n == 0 else binomial_coeff(n-1, k-1) + binomial_coeff(n-1, k)
if __name__ == "__main__":
print(binomial_coeff(4, 2)) | cache = {}
def binomial_coeff(n, k):
"""Compute the binomial coefficient 'n choose k'.
n: number of trials
k: number of successes
returns: int
"""
if k == 0:
return 1
if n == 0:
return 0
try:
return cache[n, k]
except KeyError:
cache[n, k] = binomial_coeff(n - 1, k - 1) + binomial_coeff(n - 1, k)
return cache[n, k]
def binomial_coeff(n, k=0):
if k == 0:
return 1
return 0 if n == 0 else binomial_coeff(n - 1, k - 1) + binomial_coeff(n - 1, k)
if __name__ == '__main__':
print(binomial_coeff(4, 2)) |
'''https://leetcode.com/problems/merge-two-sorted-lists/'''
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
# Iterative Solution
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = l3 = ListNode(0)
while(l1 is not None and l2 is not None):
if l1.val <=l2.val:
l3.next = ListNode(l1.val)
l3 = l3.next
l1 = l1.next
else:
l3.next = ListNode(l2.val)
l3 = l3.next
l2 = l2.next
while l1:
l3.next = ListNode(l1.val)
l3 = l3.next
l1 = l1.next
while l2:
l3.next = ListNode(l2.val)
l3 = l3.next
l2 = l2.next
return head.next
# Recursive Solution
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 or not l2:
return l1 or l2
if l1.val<l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2 | """https://leetcode.com/problems/merge-two-sorted-lists/"""
class Listnode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
head = l3 = list_node(0)
while l1 is not None and l2 is not None:
if l1.val <= l2.val:
l3.next = list_node(l1.val)
l3 = l3.next
l1 = l1.next
else:
l3.next = list_node(l2.val)
l3 = l3.next
l2 = l2.next
while l1:
l3.next = list_node(l1.val)
l3 = l3.next
l1 = l1.next
while l2:
l3.next = list_node(l2.val)
l3 = l3.next
l2 = l2.next
return head.next
class Solution:
def merge_two_lists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 or not l2:
return l1 or l2
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2 |
q = {
'get_page_id_from_frontier': "UPDATE crawldb.frontier \
SET occupied=True \
WHERE page_id=( \
SELECT page_id \
FROM crawldb.frontier as f \
LEFT JOIN crawldb.page as p \
ON f.page_id=p.id \
WHERE f.occupied=False AND p.site_id IN (\
SELECT id FROM crawldb.site WHERE next_acces<=NOW() OR next_acces IS NULL) \
ORDER BY time_added \
LIMIT 1) \
RETURNING page_id",
'get_link': "SELECT * FROM crawldb.link WHERE from_page=%s AND to_page=%s",
'get_page_by_id': "SELECT * FROM crawldb.page WHERE id=%s",
'get_site_by_domain': "SELECT * FROM crawldb.site WHERE domain=%s",
'add_to_frontier': "INSERT INTO crawldb.frontier (page_id) VALUES(%s)",
'add_new_page': "INSERT INTO crawldb.page (site_id, page_type_code, url) VALUES (%s, %s, %s) RETURNING id",
'add_pages_to_link': "INSERT INTO crawldb.link (from_page, to_page) VALUES (%s, %s)",
'remove_from_frontier': "DELETE FROM crawldb.frontier WHERE page_id=%s",
'update_page_codes': "UPDATE crawldb.page \
SET page_type_code=%s, http_status_code=%s, accessed_time=NOW() \
WHERE id=%s",
'update_frontier_page_occ&time': "UPDATE crawldb.frontier SET occupied=%s WHERE page_id=%s"
}
| q = {'get_page_id_from_frontier': 'UPDATE crawldb.frontier SET occupied=True WHERE page_id=( SELECT page_id FROM crawldb.frontier as f LEFT JOIN crawldb.page as p ON f.page_id=p.id WHERE f.occupied=False AND p.site_id IN ( SELECT id FROM crawldb.site WHERE next_acces<=NOW() OR next_acces IS NULL) ORDER BY time_added LIMIT 1) RETURNING page_id', 'get_link': 'SELECT * FROM crawldb.link WHERE from_page=%s AND to_page=%s', 'get_page_by_id': 'SELECT * FROM crawldb.page WHERE id=%s', 'get_site_by_domain': 'SELECT * FROM crawldb.site WHERE domain=%s', 'add_to_frontier': 'INSERT INTO crawldb.frontier (page_id) VALUES(%s)', 'add_new_page': 'INSERT INTO crawldb.page (site_id, page_type_code, url) VALUES (%s, %s, %s) RETURNING id', 'add_pages_to_link': 'INSERT INTO crawldb.link (from_page, to_page) VALUES (%s, %s)', 'remove_from_frontier': 'DELETE FROM crawldb.frontier WHERE page_id=%s', 'update_page_codes': 'UPDATE crawldb.page SET page_type_code=%s, http_status_code=%s, accessed_time=NOW() WHERE id=%s', 'update_frontier_page_occ&time': 'UPDATE crawldb.frontier SET occupied=%s WHERE page_id=%s'} |
class NotarizerException(Exception):
def __init__(self, error_code, error_message):
super().__init__(error_message)
self.error_code = error_code
class NoSignatureFound(NotarizerException):
def __init__(self, error_message):
super().__init__(10, error_message)
class InvalidLabelSignature(NotarizerException):
def __init__(self, error_message):
super().__init__(11, error_message)
class VerificationFailure(NotarizerException):
def __init__(self, error_message):
super().__init__(12, error_message)
class ImageNotFound(NotarizerException):
def __init__(self, error_message):
super().__init__(14, error_message)
class SigningError(NotarizerException):
def __init__(self, reason):
super().__init__(16, "Error Creating Signed Docker Image")
self.reason = reason
class PublicKeyNotFound(NotarizerException):
def __init__(self):
super().__init__(13, "No Public Key Provided")
class PrivateKeyNotFound(NotarizerException):
def __init__(self):
super().__init__(15, "No Private Key Provided")
| class Notarizerexception(Exception):
def __init__(self, error_code, error_message):
super().__init__(error_message)
self.error_code = error_code
class Nosignaturefound(NotarizerException):
def __init__(self, error_message):
super().__init__(10, error_message)
class Invalidlabelsignature(NotarizerException):
def __init__(self, error_message):
super().__init__(11, error_message)
class Verificationfailure(NotarizerException):
def __init__(self, error_message):
super().__init__(12, error_message)
class Imagenotfound(NotarizerException):
def __init__(self, error_message):
super().__init__(14, error_message)
class Signingerror(NotarizerException):
def __init__(self, reason):
super().__init__(16, 'Error Creating Signed Docker Image')
self.reason = reason
class Publickeynotfound(NotarizerException):
def __init__(self):
super().__init__(13, 'No Public Key Provided')
class Privatekeynotfound(NotarizerException):
def __init__(self):
super().__init__(15, 'No Private Key Provided') |
#!/usr/bin/env python
"""
__init__
Module containing common components for creating
components.
"""
| """
__init__
Module containing common components for creating
components.
""" |
with open("input.txt", "r") as file:
numbers = list(map(int, file.readline().split(",")))
boards = []
line = file.readline() # throw away
while line:
board = []
for i in range(5):
line = file.readline()
board.append(list(map(int, filter(lambda x: len(x) > 0, line.strip().split(" ")))))
boards.append(board)
line = file.readline()
board_masks = [([([False for j in range(5)]) for i in range(5)]) for b in range(len(boards))]
bingo_board = 0
numbers_until_bingo = len(numbers)
for k in range(len(boards)):
board = boards[k]
matches = 0
for l in range(numbers_until_bingo):
number = numbers[l]
for i in range(5):
row = board[i]
for j in range(5):
if row[j] == number:
matches += 1
board_masks[k][i][j] = True
if matches >= 5: # can't get a bingo with 4 numbers or less.
current_board_bingo = False
# check rows
for i in range(5):
row = board_masks[k][i]
if sum(row) == 5:
current_board_bingo = True
# check columns
if not current_board_bingo:
for i in range(5):
mask = board_masks[k]
if sum([mask[0][i], mask[1][i], mask[2][i], mask[3][i], mask[4][i]]) == 5:
current_board_bingo = True
if current_board_bingo:
if l < numbers_until_bingo:
numbers_until_bingo = l
bingo_board = k
break
last_number_called = numbers[numbers_until_bingo]
sum_of_umasked_numbers = 0
for i in range(5):
for j in range(5):
if not board_masks[bingo_board][i][j]:
sum_of_umasked_numbers += boards[bingo_board][i][j]
print(sum_of_umasked_numbers * last_number_called) | with open('input.txt', 'r') as file:
numbers = list(map(int, file.readline().split(',')))
boards = []
line = file.readline()
while line:
board = []
for i in range(5):
line = file.readline()
board.append(list(map(int, filter(lambda x: len(x) > 0, line.strip().split(' ')))))
boards.append(board)
line = file.readline()
board_masks = [[[False for j in range(5)] for i in range(5)] for b in range(len(boards))]
bingo_board = 0
numbers_until_bingo = len(numbers)
for k in range(len(boards)):
board = boards[k]
matches = 0
for l in range(numbers_until_bingo):
number = numbers[l]
for i in range(5):
row = board[i]
for j in range(5):
if row[j] == number:
matches += 1
board_masks[k][i][j] = True
if matches >= 5:
current_board_bingo = False
for i in range(5):
row = board_masks[k][i]
if sum(row) == 5:
current_board_bingo = True
if not current_board_bingo:
for i in range(5):
mask = board_masks[k]
if sum([mask[0][i], mask[1][i], mask[2][i], mask[3][i], mask[4][i]]) == 5:
current_board_bingo = True
if current_board_bingo:
if l < numbers_until_bingo:
numbers_until_bingo = l
bingo_board = k
break
last_number_called = numbers[numbers_until_bingo]
sum_of_umasked_numbers = 0
for i in range(5):
for j in range(5):
if not board_masks[bingo_board][i][j]:
sum_of_umasked_numbers += boards[bingo_board][i][j]
print(sum_of_umasked_numbers * last_number_called) |
#
# PySNMP MIB module ELTEX-DOT3-OAM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-DOT3-OAM-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:45:44 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)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint")
eltexLtd, = mibBuilder.importSymbols("ELTEX-SMI-ACTUAL", "eltexLtd")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList")
NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance")
Gauge32, Unsigned32, Integer32, Counter32, Bits, ModuleIdentity, MibIdentifier, IpAddress, TimeTicks, Counter64, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "Integer32", "Counter32", "Bits", "ModuleIdentity", "MibIdentifier", "IpAddress", "TimeTicks", "Counter64", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType")
DisplayString, MacAddress, TruthValue, TextualConvention, TimeStamp = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "MacAddress", "TruthValue", "TextualConvention", "TimeStamp")
eltexDot3OamMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 35265, 30))
eltexDot3OamMIB.setRevisions(('2013-02-22 00:00',))
if mibBuilder.loadTexts: eltexDot3OamMIB.setLastUpdated('201302220000Z')
if mibBuilder.loadTexts: eltexDot3OamMIB.setOrganization('Eltex Ent')
eltexDot3OamObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 35265, 30, 1))
eltexDot3OamClearStatistic = MibScalar((1, 3, 6, 1, 4, 1, 35265, 30, 1, 7), PortList()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: eltexDot3OamClearStatistic.setStatus('current')
mibBuilder.exportSymbols("ELTEX-DOT3-OAM-MIB", eltexDot3OamMIB=eltexDot3OamMIB, eltexDot3OamClearStatistic=eltexDot3OamClearStatistic, eltexDot3OamObjects=eltexDot3OamObjects, PYSNMP_MODULE_ID=eltexDot3OamMIB)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, value_range_constraint, constraints_intersection, single_value_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueSizeConstraint')
(eltex_ltd,) = mibBuilder.importSymbols('ELTEX-SMI-ACTUAL', 'eltexLtd')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(port_list,) = mibBuilder.importSymbols('Q-BRIDGE-MIB', 'PortList')
(notification_group, object_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ObjectGroup', 'ModuleCompliance')
(gauge32, unsigned32, integer32, counter32, bits, module_identity, mib_identifier, ip_address, time_ticks, counter64, iso, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Unsigned32', 'Integer32', 'Counter32', 'Bits', 'ModuleIdentity', 'MibIdentifier', 'IpAddress', 'TimeTicks', 'Counter64', 'iso', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType')
(display_string, mac_address, truth_value, textual_convention, time_stamp) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'MacAddress', 'TruthValue', 'TextualConvention', 'TimeStamp')
eltex_dot3_oam_mib = module_identity((1, 3, 6, 1, 4, 1, 35265, 30))
eltexDot3OamMIB.setRevisions(('2013-02-22 00:00',))
if mibBuilder.loadTexts:
eltexDot3OamMIB.setLastUpdated('201302220000Z')
if mibBuilder.loadTexts:
eltexDot3OamMIB.setOrganization('Eltex Ent')
eltex_dot3_oam_objects = mib_identifier((1, 3, 6, 1, 4, 1, 35265, 30, 1))
eltex_dot3_oam_clear_statistic = mib_scalar((1, 3, 6, 1, 4, 1, 35265, 30, 1, 7), port_list()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
eltexDot3OamClearStatistic.setStatus('current')
mibBuilder.exportSymbols('ELTEX-DOT3-OAM-MIB', eltexDot3OamMIB=eltexDot3OamMIB, eltexDot3OamClearStatistic=eltexDot3OamClearStatistic, eltexDot3OamObjects=eltexDot3OamObjects, PYSNMP_MODULE_ID=eltexDot3OamMIB) |
# operacoes matematica
x = 53
y = 42
# operacoes comuns
soma = x + y
mult = x * y
div = x / y
sub = x - y
# divisao inteira
div_int = x // y
# resto de Divisao
rest_div = x % y
# potencia
potencia = x ** y
print (soma)
print (mult)
print (div)
print (sub)
print ("Divisao inteira")
print (div_int)
print ("resto divisao")
print (rest_div)
print ("potencia")
print (potencia)
| x = 53
y = 42
soma = x + y
mult = x * y
div = x / y
sub = x - y
div_int = x // y
rest_div = x % y
potencia = x ** y
print(soma)
print(mult)
print(div)
print(sub)
print('Divisao inteira')
print(div_int)
print('resto divisao')
print(rest_div)
print('potencia')
print(potencia) |
class Secret:
def __init__(self):
self._secret=99
self.__top_secret=100
x=Secret()
x._secret
x.__top_secret
x._Secret__top_secret | class Secret:
def __init__(self):
self._secret = 99
self.__top_secret = 100
x = secret()
x._secret
x.__top_secret
x._Secret__top_secret |
### ML SPECIFIC FUNCTIONS
### FOR FEATURE ENGINEERING
# ENCODE EVENT -- 1--event, 0--no event
def bin_event(x):
x=int(x)
if(x!=0):
return 1
else:
return 0
# YES OR NO
def bin_weather(x):
x=float(x)
if(x>0):
return 1
else:
return 0
# BIN PRECIPITATION TYPE
def bin_ptype(x):
if(x==1): # None
return 0
else: # rain, snow or sleet
return 0
# BIN IN d_bin SECONDS
d_bin=10
def bin_delay(x):
x=float(x)
if(x<=0):
return 0
else:
return int(x/d_bin)
#BIN IN t_bin DEGREES
t_bin=10
def bin_temp(x):
x=float(x)
if(x<=0):
return 0
else:
return int(x/t_bin)
# PEAK HOUR BIN
def bin_peak(x):
x=float(x)
if(6<=x<=10 or 4<=x<=7):
return 1
else:
return 0
# WEEKDAY BIN
def bin_weekday(x):
x=float(x)
if(x<5):
return 1 # WEEKDAY
else:
return 0 # WEEKEND
# SEASON
def bin_season(x):
x=float(x)
if(x in {1,2,12}):
return 0 # WINTER
elif(x in {3,4,5}):
return 1 # SPRING
elif(x in {9,10,11}):
return 2 # FALL
elif(x in {6,7,8}):
return 3 # SUMMER
else:
print("NOT A VALID MONTH")
return -1 # WRONG
| def bin_event(x):
x = int(x)
if x != 0:
return 1
else:
return 0
def bin_weather(x):
x = float(x)
if x > 0:
return 1
else:
return 0
def bin_ptype(x):
if x == 1:
return 0
else:
return 0
d_bin = 10
def bin_delay(x):
x = float(x)
if x <= 0:
return 0
else:
return int(x / d_bin)
t_bin = 10
def bin_temp(x):
x = float(x)
if x <= 0:
return 0
else:
return int(x / t_bin)
def bin_peak(x):
x = float(x)
if 6 <= x <= 10 or 4 <= x <= 7:
return 1
else:
return 0
def bin_weekday(x):
x = float(x)
if x < 5:
return 1
else:
return 0
def bin_season(x):
x = float(x)
if x in {1, 2, 12}:
return 0
elif x in {3, 4, 5}:
return 1
elif x in {9, 10, 11}:
return 2
elif x in {6, 7, 8}:
return 3
else:
print('NOT A VALID MONTH')
return -1 |
class DependencyException(Exception):
def __init__(self, message, product):
super(Exception, self).__init__(message)
self.message = message
self.product = product
self.do_not_print = True
class SelfUpgradeException(Exception):
def __init__(self, message, parent_pid):
super(Exception, self).__init__(message)
self.message = message
self.parent_pid = parent_pid
class TaskException(Exception):
def __init__(self, message, product, tb):
super(Exception, self).__init__(message)
self.message = message
self.product = product
self.traceback = tb
class ProductNotFoundError(Exception):
pass
class FeedLoaderDownload(Exception):
pass
class ProductError(Exception):
pass | class Dependencyexception(Exception):
def __init__(self, message, product):
super(Exception, self).__init__(message)
self.message = message
self.product = product
self.do_not_print = True
class Selfupgradeexception(Exception):
def __init__(self, message, parent_pid):
super(Exception, self).__init__(message)
self.message = message
self.parent_pid = parent_pid
class Taskexception(Exception):
def __init__(self, message, product, tb):
super(Exception, self).__init__(message)
self.message = message
self.product = product
self.traceback = tb
class Productnotfounderror(Exception):
pass
class Feedloaderdownload(Exception):
pass
class Producterror(Exception):
pass |
for i in incorrect_idx:
print('%d: Predicted %d True label %d' % (i, pred_y[i], test_y[i]))
# Plot two dimensions
_, ax = plt.subplots()
for n in np.unique(test_y):
idx = np.where(test_y == n)[0]
ax.scatter(test_X[idx, 1], test_X[idx, 2], color=f"C{n}", label=f"Class {str(n)}")
for i, marker in zip(incorrect_idx, ['x', 's', 'v']):
ax.scatter(test_X[i, 1], test_X[i, 2], color="darkred", marker=marker, s=40, label=i)
ax.set(xlabel='sepal width [cm]', ylabel='petal length [cm]', title="Iris Classification results")
plt.legend(loc=1, scatterpoints=1); | for i in incorrect_idx:
print('%d: Predicted %d True label %d' % (i, pred_y[i], test_y[i]))
(_, ax) = plt.subplots()
for n in np.unique(test_y):
idx = np.where(test_y == n)[0]
ax.scatter(test_X[idx, 1], test_X[idx, 2], color=f'C{n}', label=f'Class {str(n)}')
for (i, marker) in zip(incorrect_idx, ['x', 's', 'v']):
ax.scatter(test_X[i, 1], test_X[i, 2], color='darkred', marker=marker, s=40, label=i)
ax.set(xlabel='sepal width [cm]', ylabel='petal length [cm]', title='Iris Classification results')
plt.legend(loc=1, scatterpoints=1) |
# -*- coding: UTF-8 -*-
# Given two binary strings, return their sum (also a binary string).
#
# For example,
# a = "11"
# b = "1"
# Return "100".
#
# Python, Python 3 all accepted.
# Maybe the ugliest code I have ever written since I learned Python.
class AddBinary(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if a is None or b is None:
return ""
if len(a) == 0:
return b
if len(b) == 0:
return a
# if it needs to plus one
flag = False
if len(a) >= len(b):
longer = a
shorter = b
else:
longer = b
shorter = a
result = ""
i = len(longer) - 1
j = len(shorter) - 1
while i >= 0:
if j < 0:
if longer[i] == '1':
if flag:
result += '0'
else:
result += '1'
else:
if flag:
result += '1'
flag = False
else:
result += '0'
else:
if longer[i] == '1' and shorter[j] == '1':
if flag:
result += '1'
else:
result += '0'
flag = True
elif longer[i] == '0' and shorter[j] == '0':
if flag:
result += '1'
else:
result += '0'
flag = False
# (l == '1' && s == '0') || (l == '0' && s == '1')
else:
if flag:
result += '0'
flag = True
else:
result += '1'
i -= 1
j -= 1
if flag:
result += '1'
return result[::-1]
| class Addbinary(object):
def add_binary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
if a is None or b is None:
return ''
if len(a) == 0:
return b
if len(b) == 0:
return a
flag = False
if len(a) >= len(b):
longer = a
shorter = b
else:
longer = b
shorter = a
result = ''
i = len(longer) - 1
j = len(shorter) - 1
while i >= 0:
if j < 0:
if longer[i] == '1':
if flag:
result += '0'
else:
result += '1'
elif flag:
result += '1'
flag = False
else:
result += '0'
elif longer[i] == '1' and shorter[j] == '1':
if flag:
result += '1'
else:
result += '0'
flag = True
elif longer[i] == '0' and shorter[j] == '0':
if flag:
result += '1'
else:
result += '0'
flag = False
elif flag:
result += '0'
flag = True
else:
result += '1'
i -= 1
j -= 1
if flag:
result += '1'
return result[::-1] |
# Copyright (c) 2012-2022, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
def validate_runtime_environment(runtime_environment):
"""
Validate RuntimeEnvironment for Application
Property: Application.RuntimeEnvironment
"""
VALID_RUNTIME_ENVIRONMENTS = ("SQL-1_0", "FLINK-1_6", "FLINK-1_8", "FLINK-1_11")
if runtime_environment not in VALID_RUNTIME_ENVIRONMENTS:
raise ValueError(
"Application RuntimeEnvironment must be one of: %s"
% ", ".join(VALID_RUNTIME_ENVIRONMENTS)
)
return runtime_environment
| def validate_runtime_environment(runtime_environment):
"""
Validate RuntimeEnvironment for Application
Property: Application.RuntimeEnvironment
"""
valid_runtime_environments = ('SQL-1_0', 'FLINK-1_6', 'FLINK-1_8', 'FLINK-1_11')
if runtime_environment not in VALID_RUNTIME_ENVIRONMENTS:
raise value_error('Application RuntimeEnvironment must be one of: %s' % ', '.join(VALID_RUNTIME_ENVIRONMENTS))
return runtime_environment |
y_a = [2, 2, -2, -2, -1, -1, 1, 1]
x_a = [1, -1, 1, -1, 2, -2, 2, -2]
s = []
start = list(map(int, input().split()))
stop = list(map(int, input().split()))
q = [start, None]
c = 0
def add_8_paths(p):
for a in range(8):
np = [p[0] + x_a[a], p[1] + y_a[a]]
if np not in q and np not in s and np[0] > 0 and np[1] > 0:
q.append(np)
while 1:
on = q.pop(0)
s.append(on)
if on == stop:
break
elif on == None:
c += 1
q.append(None)
else:
add_8_paths(on)
print(c) | y_a = [2, 2, -2, -2, -1, -1, 1, 1]
x_a = [1, -1, 1, -1, 2, -2, 2, -2]
s = []
start = list(map(int, input().split()))
stop = list(map(int, input().split()))
q = [start, None]
c = 0
def add_8_paths(p):
for a in range(8):
np = [p[0] + x_a[a], p[1] + y_a[a]]
if np not in q and np not in s and (np[0] > 0) and (np[1] > 0):
q.append(np)
while 1:
on = q.pop(0)
s.append(on)
if on == stop:
break
elif on == None:
c += 1
q.append(None)
else:
add_8_paths(on)
print(c) |
# Software released under the MIT license (see project root for license file)
class Header():
def __init__(self):
self.version = 1
self.test_name = "not set"
# ------------------------------------------------------------------------------
class Base:
def __init__(self):
pass
class Derived1(Base):
def __init__(self, i1 = 7, s2 = "Derived2"):
self.i1 = i1
self.s1 = s2
class Derived2(Base):
def __init__(self, i1 = 9, s2 = "Derived2"):
self.i1 = i1
self.s1 = s2
class OuterG:
def __init__(self):
self.v = []
# ------------------------------------------------------------------------------
class A:
def __init__(self, i = 0, s = ""):
self.i1 = i
self.s1 = s
class OuterA:
def __init__(self):
self.v = []
class OuterB:
def __init__(self):
self.v = []
class OuterC:
def __init__(self):
self.v = []
class OuterD:
def __init__(self):
self.v = []
class OuterE:
def __init__(self):
self.v = []
class OuterF:
def __init__(self):
self.v = []
# ------------------------------------------------------------------------------
class IdentityScrambler:
def __init__(self, base_arr = [], seed = 1):
self.base_arr = base_arr
def __call__(self):
return self.base_arr
# ------------------------------------------------------------------------------
| class Header:
def __init__(self):
self.version = 1
self.test_name = 'not set'
class Base:
def __init__(self):
pass
class Derived1(Base):
def __init__(self, i1=7, s2='Derived2'):
self.i1 = i1
self.s1 = s2
class Derived2(Base):
def __init__(self, i1=9, s2='Derived2'):
self.i1 = i1
self.s1 = s2
class Outerg:
def __init__(self):
self.v = []
class A:
def __init__(self, i=0, s=''):
self.i1 = i
self.s1 = s
class Outera:
def __init__(self):
self.v = []
class Outerb:
def __init__(self):
self.v = []
class Outerc:
def __init__(self):
self.v = []
class Outerd:
def __init__(self):
self.v = []
class Outere:
def __init__(self):
self.v = []
class Outerf:
def __init__(self):
self.v = []
class Identityscrambler:
def __init__(self, base_arr=[], seed=1):
self.base_arr = base_arr
def __call__(self):
return self.base_arr |
# This is an example of staring two servo services
# and showing each servo in a separate tab in the browsee
# Start the servo services
s1 = Runtime.createAndStart("Servo1","Servo")
s2 = Runtime.createAndStart("Servo2","Servo")
# Start the webgui service without starting the browser
webgui = Runtime.create("WebGui","WebGui")
webgui.autoStartBrowser(False)
webgui.startService()
# Start the browsers and show the first service ( Servo1 )
webgui.startBrowser("http://localhost:8888/#/service/Servo1")
# Wait a little before executing the second startBrowser to allow
# the first browser to start so that the second service will be shown
# in a new tab. Without the sleep(1) you will probably get two browsers.
sleep(1)
webgui.startBrowser("http://localhost:8888/#/service/Servo2")
| s1 = Runtime.createAndStart('Servo1', 'Servo')
s2 = Runtime.createAndStart('Servo2', 'Servo')
webgui = Runtime.create('WebGui', 'WebGui')
webgui.autoStartBrowser(False)
webgui.startService()
webgui.startBrowser('http://localhost:8888/#/service/Servo1')
sleep(1)
webgui.startBrowser('http://localhost:8888/#/service/Servo2') |
load("@halide//:halide_config.bzl", "halide_system_libs")
def halide_language_copts():
_common_opts = [
"-DGOOGLE_PROTOBUF_NO_RTTI",
"-fPIC",
"-fno-rtti",
"-std=c++11",
"-Wno-conversion",
"-Wno-sign-compare",
]
_posix_opts = [
"$(STACK_FRAME_UNLIMITED)",
"-fno-exceptions",
"-funwind-tables",
"-fvisibility-inlines-hidden",
]
_msvc_opts = [
"-D_CRT_SECURE_NO_WARNINGS",
# Linking with LLVM on Windows requires multithread+DLL CRT
"/MD",
]
return _common_opts + select({
"@halide//:halide_platform_config_x64_windows_msvc":
_msvc_opts,
"@halide//:halide_platform_config_x64_windows":
["/error_please_set_cpu_and_host_cpu_x64_windows_msvc"],
"@halide//:halide_platform_config_darwin":
_posix_opts,
"@halide//:halide_platform_config_darwin_x86_64":
_posix_opts,
"//conditions:default":
_posix_opts,
})
def halide_language_linkopts():
_linux_opts = [
"-rdynamic",
"-ldl",
"-lpthread",
"-lz"
]
_osx_opts = [
"-Wl,-stack_size",
"-Wl,1000000"
]
_msvc_opts = []
return select({
"@halide//:halide_platform_config_x64_windows_msvc":
_msvc_opts,
"@halide//:halide_platform_config_x64_windows":
["/error_please_set_cpu_and_host_cpu_x64_windows_msvc"],
"@halide//:halide_platform_config_darwin":
_osx_opts,
"@halide//:halide_platform_config_darwin_x86_64":
_osx_opts,
"//conditions:default":
_linux_opts,
}) + halide_system_libs().split(" ")
def halide_runtime_linkopts():
_posix_opts = [
"-ldl",
"-lpthread",
]
_android_opts = [
"-llog",
"-landroid",
]
_msvc_opts = []
return select({
"@halide//:halide_config_arm_32_android":
_android_opts,
"@halide//:halide_config_arm_64_android":
_android_opts,
"@halide//:halide_config_x86_32_android":
_android_opts,
"@halide//:halide_config_x86_64_android":
_android_opts,
"@halide//:halide_config_x86_64_windows":
_msvc_opts,
"//conditions:default":
_posix_opts,
})
def halide_opengl_linkopts():
_linux_opts = ["-lGL", "-lX11"]
_osx_opts = ["-framework OpenGL"]
_msvc_opts = []
return select({
"@halide//:halide_config_x86_64_windows":
_msvc_opts,
"@halide//:halide_config_x86_32_osx":
_osx_opts,
"@halide//:halide_config_x86_64_osx":
_osx_opts,
"//conditions:default":
_linux_opts,
})
# (halide-target-base, cpus, android-cpu, ios-cpu)
_HALIDE_TARGET_CONFIG_INFO = [
# Android
("arm-32-android", None, "armeabi-v7a", None),
("arm-64-android", None, "arm64-v8a", None),
("x86-32-android", None, "x86", None),
("x86-64-android", None, "x86_64", None),
# iOS
("arm-32-ios", None, None, "armv7"),
("arm-64-ios", None, None, "arm64"),
# OSX
("x86-32-osx", None, None, "i386"),
("x86-64-osx", None, None, "x86_64"),
# Linux
("arm-64-linux", ["arm"], None, None),
("powerpc-64-linux", ["ppc"], None, None),
("x86-64-linux", ["k8"], None, None),
("x86-32-linux", ["piii"], None, None),
# Windows
("x86-64-windows", ["x64_windows_msvc"], None, None),
# Special case: Android-ARMEABI. Note that we are using an illegal Target
# string for Halide; this is intentional. It allows us to add another
# config_setting to match the armeabi-without-v7a required for certain build
# scenarios; we special-case this in _select_multitarget to translate it
# back into a legal Halide target.
#
# Note that this won't produce a build that is useful (it will SIGILL on
# non-v7a hardware), but isn't intended to be useful for anything other
# than allowing certain builds to complete.
("armeabi-32-android", ["armeabi"], "armeabi", None),
]
_HALIDE_TARGET_MAP_DEFAULT = {
"x86-64-osx": [
"x86-64-osx-sse41-avx-avx2-fma",
"x86-64-osx-sse41-avx",
"x86-64-osx-sse41",
"x86-64-osx",
],
"x86-64-windows": [
"x86-64-windows-sse41-avx-avx2-fma",
"x86-64-windows-sse41-avx",
"x86-64-windows-sse41",
"x86-64-windows",
],
"x86-64-linux": [
"x86-64-linux-sse41-avx-avx2-fma",
"x86-64-linux-sse41-avx",
"x86-64-linux-sse41",
"x86-64-linux",
],
"x86-32-linux": [
"x86-32-linux-sse41",
"x86-32-linux",
],
}
def halide_library_default_target_map():
return _HALIDE_TARGET_MAP_DEFAULT
_HALIDE_RUNTIME_OVERRIDES = {
# Empty placeholder for now; we may add target-specific
# overrides here in the future.
}
def halide_config_settings():
"""Define config_settings for halide_library.
These settings are used to distinguish build targets for
halide_library() based on target CPU and configs. This is provided
to allow algorithmic generation of the config_settings based on
internal data structures; it should not be used outside of Halide.
"""
cpus = [
"darwin",
"darwin_x86_64",
"x64_windows_msvc",
"x64_windows",
]
for cpu in cpus:
native.config_setting(
name="halide_platform_config_%s" % cpu,
values={
"cpu": cpu,
},
visibility=["//visibility:public"])
for base_target, _, android_cpu, ios_cpu in _HALIDE_TARGET_CONFIG_INFO:
if android_cpu == None:
# "armeabi" is the default value for --android_cpu and isn't considered legal
# here, so we use the value to assume we aren't building for Android.
android_cpu = "armeabi"
if ios_cpu == None:
# The default value for --ios_cpu is "x86_64", i.e. for the 64b OS X simulator.
# Assuming that the i386 version of the simulator will be used along side
# arm32 apps, we consider this value to mean the flag was unspecified; this
# won't work for 32 bit simulator builds for A6 or older phones.
ios_cpu = "x86_64"
for n, cpu in _config_setting_names_and_cpus(base_target):
if cpu != None:
values = {
"cpu": cpu,
"android_cpu": android_cpu,
"ios_cpu": ios_cpu,
}
else:
values = {
"android_cpu": android_cpu,
"ios_cpu": ios_cpu,
}
native.config_setting(
name=n,
values=values,
visibility=["//visibility:public"])
# Config settings for Sanitizers
native.config_setting(
name="halide_config_asan",
values={"compiler": "asan"},
visibility=["//visibility:public"])
native.config_setting(
name="halide_config_msan",
values={"compiler": "msan"},
visibility=["//visibility:public"])
native.config_setting(
name="halide_config_tsan",
values={"compiler": "tsan"},
visibility=["//visibility:public"])
# Alphabetizes the features part of the target to make sure they always match no
# matter the concatenation order of the target string pieces.
def _canonicalize_target(halide_target):
if halide_target == "host":
return halide_target
if "," in halide_target:
fail("Multitarget may not be specified here")
tokens = halide_target.split("-")
if len(tokens) < 3:
fail("Illegal target: %s" % halide_target)
# rejoin the tokens with the features sorted
return "-".join(tokens[0:3] + sorted(tokens[3:]))
# Converts comma and dash separators to underscore and alphabetizes
# the features part of the target to make sure they always match no
# matter the concatenation order of the target string pieces.
def _halide_target_to_bazel_rule_name(multitarget):
subtargets = multitarget.split(",")
subtargets = [_canonicalize_target(st).replace("-", "_") for st in subtargets]
return "_".join(subtargets)
def _extract_base_target_pieces(halide_target):
if "," in halide_target:
fail("Multitarget may not be specified here: %s" % halide_target)
tokens = halide_target.split("-")
if len(tokens) != 3:
fail("Unexpected halide_target form: %s" % halide_target)
halide_arch = tokens[0]
halide_bits = tokens[1]
halide_os = tokens[2]
return (halide_arch, halide_bits, halide_os)
def _blaze_cpus_for_target(halide_target):
halide_arch, halide_bits, halide_os = _extract_base_target_pieces(halide_target)
key = "%s-%s-%s" % (halide_arch, halide_bits, halide_os)
info = None
for i in _HALIDE_TARGET_CONFIG_INFO:
if i[0] == key:
info = i
break
if info == None:
fail("The target %s is not one we understand (yet)" % key)
return info[1]
def _config_setting_names_and_cpus(halide_target):
"""Take a Halide target string and converts to a unique name suitable for a Bazel config_setting."""
halide_arch, halide_bits, halide_os = _extract_base_target_pieces(halide_target)
cpus = _blaze_cpus_for_target(halide_target)
if cpus == None:
cpus = [ None ]
if len(cpus) > 1:
return [("halide_config_%s_%s_%s_%s" % (halide_arch, halide_bits, halide_os, cpu), cpu) for cpu in cpus]
else:
return [("halide_config_%s_%s_%s" % (halide_arch, halide_bits, halide_os), cpu) for cpu in cpus]
def _config_settings(halide_target):
return ["@halide//:%s" % s for (s, _) in _config_setting_names_and_cpus(halide_target)]
# The second argument is True if there is a separate file generated
# for each subtarget of a multitarget output, False if not.
_output_extensions = {
"static_library": ("a", False),
"o": ("o", False),
"h": ("h", False),
"cpp_stub": ("stub.h", False),
"assembly": ("s.txt", True),
"bitcode": ("bc", True),
"stmt": ("stmt", True),
"schedule": ("schedule", True),
"html": ("html", True),
"cpp": ("generated.cpp", True),
}
def _gengen_outputs(filename, halide_target, outputs):
new_outputs = {}
for o in outputs:
if o not in _output_extensions:
fail("Unknown output: " + o)
ext, is_multiple = _output_extensions[o]
if is_multiple and len(halide_target) > 1:
# Special handling needed for ".s.txt" and similar: the suffix from the
# is_multiple case always goes before the final .
# (i.e. "filename.s_suffix.txt", not "filename_suffix.s.txt")
# -- this is awkward, but is what Halide does, so we must match it.
pieces = ext.rsplit(".", 1)
extra = (".%s" % pieces[0]) if len(pieces) > 1 else ""
ext = pieces[-1]
for h in halide_target:
new_outputs[o + h] = "%s%s_%s.%s" % (
filename, extra, _canonicalize_target(h).replace("-", "_"), ext)
else:
new_outputs[o] = "%s.%s" % (filename, ext)
return new_outputs
def _gengen_impl(ctx):
if _has_dupes(ctx.attr.outputs):
fail("Duplicate values in outputs: " + str(ctx.attr.outputs))
if not ctx.attr.generator_closure.generator_name:
fail("generator_name must be specified")
remaps = [".s=.s.txt,.cpp=.generated.cpp"]
halide_target = ctx.attr.halide_target
if "windows" in halide_target[-1] and not "mingw" in halide_target[-1]:
remaps += [".obj=.o", ".lib=.a"]
if ctx.attr.sanitizer:
halide_target = []
for t in ctx.attr.halide_target:
ct = _canonicalize_target("%s-%s" % (t, ctx.attr.sanitizer))
halide_target += [ct]
remaps += ["%s=%s" % (ct.replace("-", "_"), t.replace("-", "_"))]
outputs = [
ctx.actions.declare_file(f)
for f in _gengen_outputs(
ctx.attr.filename,
ctx.attr.halide_target, # *not* halide_target
ctx.attr.outputs).values()
]
leafname = ctx.attr.filename.split('/')[-1]
arguments = ["-o", outputs[0].dirname]
if ctx.attr.generate_runtime:
arguments += ["-r", leafname]
if len(halide_target) > 1:
fail("Only one halide_target allowed here")
if ctx.attr.halide_function_name:
fail("halide_function_name not allowed here")
else:
arguments += ["-g", ctx.attr.generator_closure.generator_name]
arguments += ["-n", leafname]
if ctx.attr.halide_function_name:
arguments += ["-f", ctx.attr.halide_function_name]
if ctx.attr.outputs:
arguments += ["-e", ",".join(ctx.attr.outputs)]
arguments += ["-x", ",".join(remaps)]
arguments += ["target=%s" % ",".join(halide_target)]
if ctx.attr.halide_generator_args:
arguments += ctx.attr.halide_generator_args.split(" ")
if ctx.executable.hexagon_code_signer:
additional_inputs, _, input_manifests = ctx.resolve_command(
tools=[ctx.attr.hexagon_code_signer])
hexagon_code_signer = ctx.executable.hexagon_code_signer.path
else:
additional_inputs = []
input_manifests = None
hexagon_code_signer = ""
progress_message = "Executing generator %s with target (%s) args (%s)." % (
ctx.attr.generator_closure.generator_name,
",".join(halide_target),
ctx.attr.halide_generator_args)
for o in outputs:
s = o.path
if s.endswith(".h") or s.endswith(".a") or s.endswith(".lib"):
continue
progress_message += "\nEmitting extra Halide output: %s" % s
env = {
"HL_DEBUG_CODEGEN": str(ctx.attr.debug_codegen_level),
"HL_HEXAGON_CODE_SIGNER": hexagon_code_signer,
}
ctx.actions.run(
# If you need to force the tools to run locally (e.g. for experimentation),
# uncomment this line.
# execution_requirements={"local":"1"},
arguments=arguments,
env=env,
executable=ctx.attr.generator_closure.generator_binary.files_to_run.executable,
mnemonic="ExecuteHalideGenerator",
input_manifests=input_manifests,
inputs=additional_inputs,
outputs=outputs,
progress_message=progress_message
)
_gengen = rule(
implementation=_gengen_impl,
attrs={
"debug_codegen_level":
attr.int(),
"filename":
attr.string(),
"generate_runtime":
attr.bool(default=False),
"generator_closure":
attr.label(
cfg="host", providers=["generator_binary", "generator_name"]),
"halide_target":
attr.string_list(),
"halide_function_name":
attr.string(),
"halide_generator_args":
attr.string(),
"hexagon_code_signer":
attr.label(
executable=True, cfg="host"),
"outputs":
attr.string_list(),
"sanitizer":
attr.string(),
},
outputs=_gengen_outputs,
output_to_genfiles=True)
def _add_target_features(target, features):
if "," in target:
fail("Cannot use multitarget here")
new_target = target.split("-")
for f in features:
if f and f not in new_target:
new_target += [f]
return "-".join(new_target)
def _has_dupes(some_list):
clean = depset(some_list).to_list()
return sorted(some_list) != sorted(clean)
def _select_multitarget(base_target,
halide_target_features,
halide_target_map):
if base_target == "armeabi-32-android":
base_target = "arm-32-android"
wildcard_target = halide_target_map.get("*")
if wildcard_target:
expected_base = "*"
targets = wildcard_target
else:
expected_base = base_target
targets = halide_target_map.get(base_target, [base_target])
multitarget = []
for t in targets:
if not t.startswith(expected_base):
fail(
"target %s does not start with expected target %s for halide_target_map"
% (t, expected_base))
t = t[len(expected_base):]
if t.startswith("-"):
t = t[1:]
# Check for a "match all base targets" entry:
multitarget.append(_add_target_features(base_target, t.split("-")))
# Add the extra features (if any).
if halide_target_features:
multitarget = [
_add_target_features(t, halide_target_features) for t in multitarget
]
# Finally, canonicalize all targets
multitarget = [_canonicalize_target(t) for t in multitarget]
return multitarget
def _gengen_closure_impl(ctx):
return struct(
generator_binary=ctx.attr.generator_binary,
generator_name=ctx.attr.halide_generator_name)
_gengen_closure = rule(
implementation=_gengen_closure_impl,
attrs={
"generator_binary":
attr.label(
executable=True, allow_files=True, mandatory=True, cfg="host"),
"halide_generator_name":
attr.string(),
})
def _discard_useless_features(halide_target_features = []):
# Discard target features which do not affect the contents of the runtime.
useless_features = depset(["user_context", "no_asserts", "no_bounds_query", "profile"])
return sorted(depset([f for f in halide_target_features if f not in useless_features.to_list()]).to_list())
def _halide_library_runtime_target_name(halide_target_features = []):
return "_".join(["halide_library_runtime"] + _discard_useless_features(halide_target_features))
def _define_halide_library_runtime(halide_target_features = []):
target_name = _halide_library_runtime_target_name(halide_target_features)
if not native.existing_rule("halide_library_runtime.generator"):
halide_generator(
name="halide_library_runtime.generator",
srcs=[],
deps=[],
visibility=["//visibility:private"])
condition_deps = {}
for base_target, _, _, _ in _HALIDE_TARGET_CONFIG_INFO:
settings = _config_settings(base_target)
# For armeabi-32-android, just generate an arm-32-android runtime
halide_target = "arm-32-android" if base_target == "armeabi-32-android" else base_target
halide_target_name = _halide_target_to_bazel_rule_name(base_target);
_gengen(
name="%s_%s" % (halide_target_name, target_name),
filename="%s/%s" % (halide_target_name, target_name),
generate_runtime=True,
generator_closure="halide_library_runtime.generator_closure",
halide_target=["-".join([halide_target] + _discard_useless_features(halide_target_features))],
sanitizer=select({
"@halide//:halide_config_asan": "asan",
"@halide//:halide_config_msan": "msan",
"@halide//:halide_config_tsan": "tsan",
"//conditions:default": "",
}),
outputs=["o"],
tags=["manual"],
visibility=[
"@halide//:__subpackages__",
]
)
for s in settings:
condition_deps[s] = ["%s/%s.o" % (halide_target_name, target_name)]
native.cc_library(
name=target_name,
linkopts=halide_runtime_linkopts(),
srcs=select(condition_deps),
tags=["manual"],
visibility=["//visibility:public"])
return target_name
def _standard_library_runtime_features():
standard_features = [
[],
["asan"],
["c_plus_plus_name_mangling"],
["cuda"],
["cuda", "matlab"],
["hvx_64"],
["hvx_128"],
["matlab"],
["metal"],
["opengl"],
]
return [f for f in standard_features] + [f + ["debug"] for f in standard_features]
def _standard_library_runtime_names():
return depset([_halide_library_runtime_target_name(f) for f in _standard_library_runtime_features()])
def halide_library_runtimes():
runtime_package = ""
if PACKAGE_NAME != runtime_package:
fail("halide_library_runtimes can only be used from package '%s' (this is %s)" % (runtime_package, PACKAGE_NAME))
unused = [_define_halide_library_runtime(f) for f in _standard_library_runtime_features()]
unused = unused # unused variable
def halide_generator(name,
srcs,
copts=[],
deps=[],
generator_name="",
includes=[],
tags=[],
visibility=None):
if not name.endswith(".generator"):
fail("halide_generator rules must end in .generator")
if not generator_name:
generator_name = name[:-10] # strip ".generator" suffix
native.cc_library(
name="%s_library" % name,
srcs=srcs,
alwayslink=1,
copts=copts + halide_language_copts(),
deps=depset([
"@halide//:language"
] + deps),
tags=["manual"] + tags,
visibility=["//visibility:private"])
native.cc_binary(
name="%s_binary" % name,
copts=copts + halide_language_copts(),
linkopts=halide_language_linkopts(),
deps=[
":%s_library" % name,
"@halide//:gengen",
],
tags=["manual"] + tags,
visibility=["//visibility:private"])
_gengen_closure(
name="%s_closure" % name,
generator_binary="%s_binary" % name,
halide_generator_name=generator_name,
visibility=["//visibility:private"])
# If srcs is empty, we're building the halide-library-runtime,
# which has no stub: just skip it.
stub_gen_hdrs_target = []
if srcs:
# The specific target doesn't matter (much), but we need
# something that is valid, so uniformly choose first entry
# so that build product cannot vary by build host
stub_header_target = _select_multitarget(
base_target=_HALIDE_TARGET_CONFIG_INFO[0][0],
halide_target_features=[],
halide_target_map={})
_gengen(
name="%s_stub_gen" % name,
filename=name[:-10], # strip ".generator" suffix
generator_closure=":%s_closure" % name,
halide_target=stub_header_target,
sanitizer=select({
"@halide//:halide_config_asan": "asan",
"@halide//:halide_config_msan": "msan",
"@halide//:halide_config_tsan": "tsan",
"//conditions:default": "",
}),
outputs=["cpp_stub"],
tags=tags,
visibility=["//visibility:private"])
stub_gen_hdrs_target = [":%s_stub_gen" % name]
native.cc_library(
name=name,
alwayslink=1,
hdrs=stub_gen_hdrs_target,
deps=[
":%s_library" % name,
"@halide//:language"
],
copts=copts + halide_language_copts(),
includes=includes,
visibility=visibility,
tags=["manual"] + tags)
def halide_library_from_generator(name,
generator,
debug_codegen_level=0,
deps=[],
extra_outputs=[],
function_name=None,
generator_args=[],
halide_target_features=[],
halide_target_map=halide_library_default_target_map(),
hexagon_code_signer=None,
includes=[],
namespace=None,
tags=[],
visibility=None):
if not function_name:
function_name = name
if namespace:
function_name = "%s::%s" % (namespace, function_name)
# For generator_args, we support both arrays of strings, and space separated strings
if type(generator_args) != type(""):
generator_args = " ".join(generator_args);
# Escape backslashes and double quotes.
generator_args = generator_args.replace("\\", '\\\\"').replace('"', '\\"')
if _has_dupes(halide_target_features):
fail("Duplicate values in halide_target_features: %s" %
str(halide_target_features))
if _has_dupes(extra_outputs):
fail("Duplicate values in extra_outputs: %s" % str(extra_outputs))
full_halide_target_features = sorted(depset(halide_target_features + ["c_plus_plus_name_mangling", "no_runtime"]).to_list())
user_halide_target_features = sorted(depset(halide_target_features).to_list())
if "cpp" in extra_outputs:
fail("halide_library('%s') doesn't support 'cpp' in extra_outputs; please depend on '%s_cc' instead." % (name, name))
for san in ["asan", "msan", "tsan"]:
if san in halide_target_features:
fail("halide_library('%s') doesn't support '%s' in halide_target_features; please build with --config=%s instead." % (name, san, san))
generator_closure = "%s_closure" % generator
outputs = ["static_library", "h"] + extra_outputs
condition_deps = {}
condition_hdrs = {}
for base_target, _, _, _ in _HALIDE_TARGET_CONFIG_INFO:
multitarget = _select_multitarget(
base_target=base_target,
halide_target_features=full_halide_target_features,
halide_target_map=halide_target_map)
base_target_name = _halide_target_to_bazel_rule_name(base_target)
_gengen(
name="%s_%s" % (base_target_name, name),
filename="%s/%s" % (base_target_name, name),
halide_generator_args=generator_args,
generator_closure=generator_closure,
halide_target=multitarget,
halide_function_name=function_name,
sanitizer=select({
"@halide//:halide_config_asan": "asan",
"@halide//:halide_config_msan": "msan",
"@halide//:halide_config_tsan": "tsan",
"//conditions:default": "",
}),
debug_codegen_level=debug_codegen_level,
hexagon_code_signer=hexagon_code_signer,
tags=["manual"] + tags,
outputs=outputs)
libname = "halide_internal_%s_%s" % (name, base_target_name)
native.cc_library(
name=libname,
srcs=["%s/%s.a" % (base_target_name, name)],
hdrs=["%s/%s.h" % (base_target_name, name)],
tags=["manual"] + tags,
visibility=["//visibility:private"])
for s in _config_settings(base_target):
condition_deps[s] = [":%s" % libname]
condition_hdrs[s] = ["%s/%s.h" % (base_target_name, name)]
# Copy the header file so that include paths are correct
native.genrule(
name="%s_h" % name,
srcs=select(condition_hdrs),
outs=["%s.h" % name],
cmd="for i in $(SRCS); do cp $$i $(@D); done",
tags=tags,
visibility=visibility
)
# Create a _cc target for (unusual) applications that want C++ source output;
# we don't support this via extra_outputs=["cpp"] because it can end up being
# compiled by Bazel, producing duplicate symbols; also, targets that want this
# sometimes want to compile it via a separate tool (e.g., XCode to produce
# certain bitcode variants). Note that this deliberately does not produce
# a cc_library() output.
# Use a canonical target to build CC, regardless of config detected
cc_target = _select_multitarget(
base_target=_HALIDE_TARGET_CONFIG_INFO[0][0],
halide_target_features=full_halide_target_features,
halide_target_map=halide_target_map)
if len(cc_target) > 1:
# This can happen if someone uses halide_target_map
# to force everything to be multitarget. In that
# case, just use the first entry.
cc_target = [cc_target[0]]
_gengen(
name="%s_cc" % name,
filename=name,
halide_generator_args=generator_args,
generator_closure=generator_closure,
halide_target=cc_target,
sanitizer=select({
"@halide//:halide_config_asan": "asan",
"@halide//:halide_config_msan": "msan",
"@halide//:halide_config_tsan": "tsan",
"//conditions:default": "",
}),
halide_function_name=function_name,
outputs=["cpp"],
tags=["manual"] + tags)
runtime_library = _halide_library_runtime_target_name(user_halide_target_features)
if runtime_library in _standard_library_runtime_names().to_list():
runtime_library = "@halide//:%s" % runtime_library
else:
if not native.existing_rule(runtime_library):
_define_halide_library_runtime(user_halide_target_features)
# Note to maintainers: if this message is reported, you probably want to add
# feature combination as an item in _standard_library_runtime_features()
# in this file. (Failing to do so will only cause potentially-redundant
# runtime library building, but no correctness problems.)
print("\nCreating Halide runtime library for feature set combination: " +
str(_discard_useless_features(user_halide_target_features)) + "\n" +
"If you see this message, there is no need to take any action; " +
"however, please forward this message to halide-dev@lists.csail.mit.edu " +
"so that we can include this case to reduce build times.")
runtime_library = ":%s" % runtime_library
native.cc_library(
name=name,
hdrs=[":%s_h" % name],
# Order matters: runtime_library must come *after* condition_deps, so that
# they will be presented to the linker in this order, and we want
# unresolved symbols in the generated code (in condition_deps) to be
# resolved in the runtime library.
deps=select(condition_deps) + deps + ["@halide//:runtime", runtime_library],
includes=includes,
tags=tags,
visibility=visibility)
# Although "#include SOME_MACRO" is legal C/C++, it doesn't work in all environments.
# So, instead, we'll make a local copy of the .cpp file and use sed to
# put the include path in directly.
native.genrule(
name = "%s_RunGenStubs" % name,
srcs = [ "@halide//:tools/RunGenStubs.cpp" ],
cmd = "cat $(location @halide//:tools/RunGenStubs.cpp) | " +
"sed -e 's|HL_RUNGEN_FILTER_HEADER|\"%s%s%s.h\"|g' > $@" % (PACKAGE_NAME, "/" if PACKAGE_NAME else "", name),
outs = [ "%s_RunGenStubs.cpp" % name, ],
tags=["manual", "notap"] + tags,
visibility=["//visibility:private"]
)
# Note that the .rungen targets are tagged as manual+notap, as some
# extant Generators don't (yet) have the proper generator_deps
# or filter_deps configured. ("notap" is used internally by
# certain Google test systems; it is ignored in public Bazel builds.)
#
# (Of course, this requires that we have some explicit build-and-link tests
# elsewhere to verify that at least some expected-to-work Generators
# stay working.)
native.cc_binary(
name="%s.rungen" % name,
srcs=[":%s_RunGenStubs" % name],
deps=[
"@halide//:rungen",
":%s" % name,
],
tags=["manual", "notap"] + tags,
visibility=["//visibility:private"])
# Return the fully-qualified built target name.
return "//%s:%s" % (PACKAGE_NAME, name)
def halide_library(name,
srcs,
copts=[],
debug_codegen_level=0,
extra_outputs=[], # "stmt" and/or "assembly" are useful for debugging
filter_deps=[],
function_name=None,
generator_args=[],
generator_deps=[],
generator_name=None,
halide_target_features=[],
halide_target_map=halide_library_default_target_map(),
hexagon_code_signer=None,
includes=[],
namespace=None,
visibility=None):
halide_generator(
name="%s.generator" % name,
srcs=srcs,
generator_name=generator_name,
deps=generator_deps,
includes=includes,
copts=copts,
visibility=visibility)
return halide_library_from_generator(
name=name,
generator=":%s.generator" % name,
deps=filter_deps,
visibility=visibility,
namespace=namespace,
includes=includes,
function_name=function_name,
generator_args=generator_args,
debug_codegen_level=debug_codegen_level,
halide_target_features=halide_target_features,
halide_target_map=halide_target_map,
hexagon_code_signer=hexagon_code_signer,
extra_outputs=extra_outputs)
| load('@halide//:halide_config.bzl', 'halide_system_libs')
def halide_language_copts():
_common_opts = ['-DGOOGLE_PROTOBUF_NO_RTTI', '-fPIC', '-fno-rtti', '-std=c++11', '-Wno-conversion', '-Wno-sign-compare']
_posix_opts = ['$(STACK_FRAME_UNLIMITED)', '-fno-exceptions', '-funwind-tables', '-fvisibility-inlines-hidden']
_msvc_opts = ['-D_CRT_SECURE_NO_WARNINGS', '/MD']
return _common_opts + select({'@halide//:halide_platform_config_x64_windows_msvc': _msvc_opts, '@halide//:halide_platform_config_x64_windows': ['/error_please_set_cpu_and_host_cpu_x64_windows_msvc'], '@halide//:halide_platform_config_darwin': _posix_opts, '@halide//:halide_platform_config_darwin_x86_64': _posix_opts, '//conditions:default': _posix_opts})
def halide_language_linkopts():
_linux_opts = ['-rdynamic', '-ldl', '-lpthread', '-lz']
_osx_opts = ['-Wl,-stack_size', '-Wl,1000000']
_msvc_opts = []
return select({'@halide//:halide_platform_config_x64_windows_msvc': _msvc_opts, '@halide//:halide_platform_config_x64_windows': ['/error_please_set_cpu_and_host_cpu_x64_windows_msvc'], '@halide//:halide_platform_config_darwin': _osx_opts, '@halide//:halide_platform_config_darwin_x86_64': _osx_opts, '//conditions:default': _linux_opts}) + halide_system_libs().split(' ')
def halide_runtime_linkopts():
_posix_opts = ['-ldl', '-lpthread']
_android_opts = ['-llog', '-landroid']
_msvc_opts = []
return select({'@halide//:halide_config_arm_32_android': _android_opts, '@halide//:halide_config_arm_64_android': _android_opts, '@halide//:halide_config_x86_32_android': _android_opts, '@halide//:halide_config_x86_64_android': _android_opts, '@halide//:halide_config_x86_64_windows': _msvc_opts, '//conditions:default': _posix_opts})
def halide_opengl_linkopts():
_linux_opts = ['-lGL', '-lX11']
_osx_opts = ['-framework OpenGL']
_msvc_opts = []
return select({'@halide//:halide_config_x86_64_windows': _msvc_opts, '@halide//:halide_config_x86_32_osx': _osx_opts, '@halide//:halide_config_x86_64_osx': _osx_opts, '//conditions:default': _linux_opts})
_halide_target_config_info = [('arm-32-android', None, 'armeabi-v7a', None), ('arm-64-android', None, 'arm64-v8a', None), ('x86-32-android', None, 'x86', None), ('x86-64-android', None, 'x86_64', None), ('arm-32-ios', None, None, 'armv7'), ('arm-64-ios', None, None, 'arm64'), ('x86-32-osx', None, None, 'i386'), ('x86-64-osx', None, None, 'x86_64'), ('arm-64-linux', ['arm'], None, None), ('powerpc-64-linux', ['ppc'], None, None), ('x86-64-linux', ['k8'], None, None), ('x86-32-linux', ['piii'], None, None), ('x86-64-windows', ['x64_windows_msvc'], None, None), ('armeabi-32-android', ['armeabi'], 'armeabi', None)]
_halide_target_map_default = {'x86-64-osx': ['x86-64-osx-sse41-avx-avx2-fma', 'x86-64-osx-sse41-avx', 'x86-64-osx-sse41', 'x86-64-osx'], 'x86-64-windows': ['x86-64-windows-sse41-avx-avx2-fma', 'x86-64-windows-sse41-avx', 'x86-64-windows-sse41', 'x86-64-windows'], 'x86-64-linux': ['x86-64-linux-sse41-avx-avx2-fma', 'x86-64-linux-sse41-avx', 'x86-64-linux-sse41', 'x86-64-linux'], 'x86-32-linux': ['x86-32-linux-sse41', 'x86-32-linux']}
def halide_library_default_target_map():
return _HALIDE_TARGET_MAP_DEFAULT
_halide_runtime_overrides = {}
def halide_config_settings():
"""Define config_settings for halide_library.
These settings are used to distinguish build targets for
halide_library() based on target CPU and configs. This is provided
to allow algorithmic generation of the config_settings based on
internal data structures; it should not be used outside of Halide.
"""
cpus = ['darwin', 'darwin_x86_64', 'x64_windows_msvc', 'x64_windows']
for cpu in cpus:
native.config_setting(name='halide_platform_config_%s' % cpu, values={'cpu': cpu}, visibility=['//visibility:public'])
for (base_target, _, android_cpu, ios_cpu) in _HALIDE_TARGET_CONFIG_INFO:
if android_cpu == None:
android_cpu = 'armeabi'
if ios_cpu == None:
ios_cpu = 'x86_64'
for (n, cpu) in _config_setting_names_and_cpus(base_target):
if cpu != None:
values = {'cpu': cpu, 'android_cpu': android_cpu, 'ios_cpu': ios_cpu}
else:
values = {'android_cpu': android_cpu, 'ios_cpu': ios_cpu}
native.config_setting(name=n, values=values, visibility=['//visibility:public'])
native.config_setting(name='halide_config_asan', values={'compiler': 'asan'}, visibility=['//visibility:public'])
native.config_setting(name='halide_config_msan', values={'compiler': 'msan'}, visibility=['//visibility:public'])
native.config_setting(name='halide_config_tsan', values={'compiler': 'tsan'}, visibility=['//visibility:public'])
def _canonicalize_target(halide_target):
if halide_target == 'host':
return halide_target
if ',' in halide_target:
fail('Multitarget may not be specified here')
tokens = halide_target.split('-')
if len(tokens) < 3:
fail('Illegal target: %s' % halide_target)
return '-'.join(tokens[0:3] + sorted(tokens[3:]))
def _halide_target_to_bazel_rule_name(multitarget):
subtargets = multitarget.split(',')
subtargets = [_canonicalize_target(st).replace('-', '_') for st in subtargets]
return '_'.join(subtargets)
def _extract_base_target_pieces(halide_target):
if ',' in halide_target:
fail('Multitarget may not be specified here: %s' % halide_target)
tokens = halide_target.split('-')
if len(tokens) != 3:
fail('Unexpected halide_target form: %s' % halide_target)
halide_arch = tokens[0]
halide_bits = tokens[1]
halide_os = tokens[2]
return (halide_arch, halide_bits, halide_os)
def _blaze_cpus_for_target(halide_target):
(halide_arch, halide_bits, halide_os) = _extract_base_target_pieces(halide_target)
key = '%s-%s-%s' % (halide_arch, halide_bits, halide_os)
info = None
for i in _HALIDE_TARGET_CONFIG_INFO:
if i[0] == key:
info = i
break
if info == None:
fail('The target %s is not one we understand (yet)' % key)
return info[1]
def _config_setting_names_and_cpus(halide_target):
"""Take a Halide target string and converts to a unique name suitable for a Bazel config_setting."""
(halide_arch, halide_bits, halide_os) = _extract_base_target_pieces(halide_target)
cpus = _blaze_cpus_for_target(halide_target)
if cpus == None:
cpus = [None]
if len(cpus) > 1:
return [('halide_config_%s_%s_%s_%s' % (halide_arch, halide_bits, halide_os, cpu), cpu) for cpu in cpus]
else:
return [('halide_config_%s_%s_%s' % (halide_arch, halide_bits, halide_os), cpu) for cpu in cpus]
def _config_settings(halide_target):
return ['@halide//:%s' % s for (s, _) in _config_setting_names_and_cpus(halide_target)]
_output_extensions = {'static_library': ('a', False), 'o': ('o', False), 'h': ('h', False), 'cpp_stub': ('stub.h', False), 'assembly': ('s.txt', True), 'bitcode': ('bc', True), 'stmt': ('stmt', True), 'schedule': ('schedule', True), 'html': ('html', True), 'cpp': ('generated.cpp', True)}
def _gengen_outputs(filename, halide_target, outputs):
new_outputs = {}
for o in outputs:
if o not in _output_extensions:
fail('Unknown output: ' + o)
(ext, is_multiple) = _output_extensions[o]
if is_multiple and len(halide_target) > 1:
pieces = ext.rsplit('.', 1)
extra = '.%s' % pieces[0] if len(pieces) > 1 else ''
ext = pieces[-1]
for h in halide_target:
new_outputs[o + h] = '%s%s_%s.%s' % (filename, extra, _canonicalize_target(h).replace('-', '_'), ext)
else:
new_outputs[o] = '%s.%s' % (filename, ext)
return new_outputs
def _gengen_impl(ctx):
if _has_dupes(ctx.attr.outputs):
fail('Duplicate values in outputs: ' + str(ctx.attr.outputs))
if not ctx.attr.generator_closure.generator_name:
fail('generator_name must be specified')
remaps = ['.s=.s.txt,.cpp=.generated.cpp']
halide_target = ctx.attr.halide_target
if 'windows' in halide_target[-1] and (not 'mingw' in halide_target[-1]):
remaps += ['.obj=.o', '.lib=.a']
if ctx.attr.sanitizer:
halide_target = []
for t in ctx.attr.halide_target:
ct = _canonicalize_target('%s-%s' % (t, ctx.attr.sanitizer))
halide_target += [ct]
remaps += ['%s=%s' % (ct.replace('-', '_'), t.replace('-', '_'))]
outputs = [ctx.actions.declare_file(f) for f in _gengen_outputs(ctx.attr.filename, ctx.attr.halide_target, ctx.attr.outputs).values()]
leafname = ctx.attr.filename.split('/')[-1]
arguments = ['-o', outputs[0].dirname]
if ctx.attr.generate_runtime:
arguments += ['-r', leafname]
if len(halide_target) > 1:
fail('Only one halide_target allowed here')
if ctx.attr.halide_function_name:
fail('halide_function_name not allowed here')
else:
arguments += ['-g', ctx.attr.generator_closure.generator_name]
arguments += ['-n', leafname]
if ctx.attr.halide_function_name:
arguments += ['-f', ctx.attr.halide_function_name]
if ctx.attr.outputs:
arguments += ['-e', ','.join(ctx.attr.outputs)]
arguments += ['-x', ','.join(remaps)]
arguments += ['target=%s' % ','.join(halide_target)]
if ctx.attr.halide_generator_args:
arguments += ctx.attr.halide_generator_args.split(' ')
if ctx.executable.hexagon_code_signer:
(additional_inputs, _, input_manifests) = ctx.resolve_command(tools=[ctx.attr.hexagon_code_signer])
hexagon_code_signer = ctx.executable.hexagon_code_signer.path
else:
additional_inputs = []
input_manifests = None
hexagon_code_signer = ''
progress_message = 'Executing generator %s with target (%s) args (%s).' % (ctx.attr.generator_closure.generator_name, ','.join(halide_target), ctx.attr.halide_generator_args)
for o in outputs:
s = o.path
if s.endswith('.h') or s.endswith('.a') or s.endswith('.lib'):
continue
progress_message += '\nEmitting extra Halide output: %s' % s
env = {'HL_DEBUG_CODEGEN': str(ctx.attr.debug_codegen_level), 'HL_HEXAGON_CODE_SIGNER': hexagon_code_signer}
ctx.actions.run(arguments=arguments, env=env, executable=ctx.attr.generator_closure.generator_binary.files_to_run.executable, mnemonic='ExecuteHalideGenerator', input_manifests=input_manifests, inputs=additional_inputs, outputs=outputs, progress_message=progress_message)
_gengen = rule(implementation=_gengen_impl, attrs={'debug_codegen_level': attr.int(), 'filename': attr.string(), 'generate_runtime': attr.bool(default=False), 'generator_closure': attr.label(cfg='host', providers=['generator_binary', 'generator_name']), 'halide_target': attr.string_list(), 'halide_function_name': attr.string(), 'halide_generator_args': attr.string(), 'hexagon_code_signer': attr.label(executable=True, cfg='host'), 'outputs': attr.string_list(), 'sanitizer': attr.string()}, outputs=_gengen_outputs, output_to_genfiles=True)
def _add_target_features(target, features):
if ',' in target:
fail('Cannot use multitarget here')
new_target = target.split('-')
for f in features:
if f and f not in new_target:
new_target += [f]
return '-'.join(new_target)
def _has_dupes(some_list):
clean = depset(some_list).to_list()
return sorted(some_list) != sorted(clean)
def _select_multitarget(base_target, halide_target_features, halide_target_map):
if base_target == 'armeabi-32-android':
base_target = 'arm-32-android'
wildcard_target = halide_target_map.get('*')
if wildcard_target:
expected_base = '*'
targets = wildcard_target
else:
expected_base = base_target
targets = halide_target_map.get(base_target, [base_target])
multitarget = []
for t in targets:
if not t.startswith(expected_base):
fail('target %s does not start with expected target %s for halide_target_map' % (t, expected_base))
t = t[len(expected_base):]
if t.startswith('-'):
t = t[1:]
multitarget.append(_add_target_features(base_target, t.split('-')))
if halide_target_features:
multitarget = [_add_target_features(t, halide_target_features) for t in multitarget]
multitarget = [_canonicalize_target(t) for t in multitarget]
return multitarget
def _gengen_closure_impl(ctx):
return struct(generator_binary=ctx.attr.generator_binary, generator_name=ctx.attr.halide_generator_name)
_gengen_closure = rule(implementation=_gengen_closure_impl, attrs={'generator_binary': attr.label(executable=True, allow_files=True, mandatory=True, cfg='host'), 'halide_generator_name': attr.string()})
def _discard_useless_features(halide_target_features=[]):
useless_features = depset(['user_context', 'no_asserts', 'no_bounds_query', 'profile'])
return sorted(depset([f for f in halide_target_features if f not in useless_features.to_list()]).to_list())
def _halide_library_runtime_target_name(halide_target_features=[]):
return '_'.join(['halide_library_runtime'] + _discard_useless_features(halide_target_features))
def _define_halide_library_runtime(halide_target_features=[]):
target_name = _halide_library_runtime_target_name(halide_target_features)
if not native.existing_rule('halide_library_runtime.generator'):
halide_generator(name='halide_library_runtime.generator', srcs=[], deps=[], visibility=['//visibility:private'])
condition_deps = {}
for (base_target, _, _, _) in _HALIDE_TARGET_CONFIG_INFO:
settings = _config_settings(base_target)
halide_target = 'arm-32-android' if base_target == 'armeabi-32-android' else base_target
halide_target_name = _halide_target_to_bazel_rule_name(base_target)
_gengen(name='%s_%s' % (halide_target_name, target_name), filename='%s/%s' % (halide_target_name, target_name), generate_runtime=True, generator_closure='halide_library_runtime.generator_closure', halide_target=['-'.join([halide_target] + _discard_useless_features(halide_target_features))], sanitizer=select({'@halide//:halide_config_asan': 'asan', '@halide//:halide_config_msan': 'msan', '@halide//:halide_config_tsan': 'tsan', '//conditions:default': ''}), outputs=['o'], tags=['manual'], visibility=['@halide//:__subpackages__'])
for s in settings:
condition_deps[s] = ['%s/%s.o' % (halide_target_name, target_name)]
native.cc_library(name=target_name, linkopts=halide_runtime_linkopts(), srcs=select(condition_deps), tags=['manual'], visibility=['//visibility:public'])
return target_name
def _standard_library_runtime_features():
standard_features = [[], ['asan'], ['c_plus_plus_name_mangling'], ['cuda'], ['cuda', 'matlab'], ['hvx_64'], ['hvx_128'], ['matlab'], ['metal'], ['opengl']]
return [f for f in standard_features] + [f + ['debug'] for f in standard_features]
def _standard_library_runtime_names():
return depset([_halide_library_runtime_target_name(f) for f in _standard_library_runtime_features()])
def halide_library_runtimes():
runtime_package = ''
if PACKAGE_NAME != runtime_package:
fail("halide_library_runtimes can only be used from package '%s' (this is %s)" % (runtime_package, PACKAGE_NAME))
unused = [_define_halide_library_runtime(f) for f in _standard_library_runtime_features()]
unused = unused
def halide_generator(name, srcs, copts=[], deps=[], generator_name='', includes=[], tags=[], visibility=None):
if not name.endswith('.generator'):
fail('halide_generator rules must end in .generator')
if not generator_name:
generator_name = name[:-10]
native.cc_library(name='%s_library' % name, srcs=srcs, alwayslink=1, copts=copts + halide_language_copts(), deps=depset(['@halide//:language'] + deps), tags=['manual'] + tags, visibility=['//visibility:private'])
native.cc_binary(name='%s_binary' % name, copts=copts + halide_language_copts(), linkopts=halide_language_linkopts(), deps=[':%s_library' % name, '@halide//:gengen'], tags=['manual'] + tags, visibility=['//visibility:private'])
_gengen_closure(name='%s_closure' % name, generator_binary='%s_binary' % name, halide_generator_name=generator_name, visibility=['//visibility:private'])
stub_gen_hdrs_target = []
if srcs:
stub_header_target = _select_multitarget(base_target=_HALIDE_TARGET_CONFIG_INFO[0][0], halide_target_features=[], halide_target_map={})
_gengen(name='%s_stub_gen' % name, filename=name[:-10], generator_closure=':%s_closure' % name, halide_target=stub_header_target, sanitizer=select({'@halide//:halide_config_asan': 'asan', '@halide//:halide_config_msan': 'msan', '@halide//:halide_config_tsan': 'tsan', '//conditions:default': ''}), outputs=['cpp_stub'], tags=tags, visibility=['//visibility:private'])
stub_gen_hdrs_target = [':%s_stub_gen' % name]
native.cc_library(name=name, alwayslink=1, hdrs=stub_gen_hdrs_target, deps=[':%s_library' % name, '@halide//:language'], copts=copts + halide_language_copts(), includes=includes, visibility=visibility, tags=['manual'] + tags)
def halide_library_from_generator(name, generator, debug_codegen_level=0, deps=[], extra_outputs=[], function_name=None, generator_args=[], halide_target_features=[], halide_target_map=halide_library_default_target_map(), hexagon_code_signer=None, includes=[], namespace=None, tags=[], visibility=None):
if not function_name:
function_name = name
if namespace:
function_name = '%s::%s' % (namespace, function_name)
if type(generator_args) != type(''):
generator_args = ' '.join(generator_args)
generator_args = generator_args.replace('\\', '\\\\"').replace('"', '\\"')
if _has_dupes(halide_target_features):
fail('Duplicate values in halide_target_features: %s' % str(halide_target_features))
if _has_dupes(extra_outputs):
fail('Duplicate values in extra_outputs: %s' % str(extra_outputs))
full_halide_target_features = sorted(depset(halide_target_features + ['c_plus_plus_name_mangling', 'no_runtime']).to_list())
user_halide_target_features = sorted(depset(halide_target_features).to_list())
if 'cpp' in extra_outputs:
fail("halide_library('%s') doesn't support 'cpp' in extra_outputs; please depend on '%s_cc' instead." % (name, name))
for san in ['asan', 'msan', 'tsan']:
if san in halide_target_features:
fail("halide_library('%s') doesn't support '%s' in halide_target_features; please build with --config=%s instead." % (name, san, san))
generator_closure = '%s_closure' % generator
outputs = ['static_library', 'h'] + extra_outputs
condition_deps = {}
condition_hdrs = {}
for (base_target, _, _, _) in _HALIDE_TARGET_CONFIG_INFO:
multitarget = _select_multitarget(base_target=base_target, halide_target_features=full_halide_target_features, halide_target_map=halide_target_map)
base_target_name = _halide_target_to_bazel_rule_name(base_target)
_gengen(name='%s_%s' % (base_target_name, name), filename='%s/%s' % (base_target_name, name), halide_generator_args=generator_args, generator_closure=generator_closure, halide_target=multitarget, halide_function_name=function_name, sanitizer=select({'@halide//:halide_config_asan': 'asan', '@halide//:halide_config_msan': 'msan', '@halide//:halide_config_tsan': 'tsan', '//conditions:default': ''}), debug_codegen_level=debug_codegen_level, hexagon_code_signer=hexagon_code_signer, tags=['manual'] + tags, outputs=outputs)
libname = 'halide_internal_%s_%s' % (name, base_target_name)
native.cc_library(name=libname, srcs=['%s/%s.a' % (base_target_name, name)], hdrs=['%s/%s.h' % (base_target_name, name)], tags=['manual'] + tags, visibility=['//visibility:private'])
for s in _config_settings(base_target):
condition_deps[s] = [':%s' % libname]
condition_hdrs[s] = ['%s/%s.h' % (base_target_name, name)]
native.genrule(name='%s_h' % name, srcs=select(condition_hdrs), outs=['%s.h' % name], cmd='for i in $(SRCS); do cp $$i $(@D); done', tags=tags, visibility=visibility)
cc_target = _select_multitarget(base_target=_HALIDE_TARGET_CONFIG_INFO[0][0], halide_target_features=full_halide_target_features, halide_target_map=halide_target_map)
if len(cc_target) > 1:
cc_target = [cc_target[0]]
_gengen(name='%s_cc' % name, filename=name, halide_generator_args=generator_args, generator_closure=generator_closure, halide_target=cc_target, sanitizer=select({'@halide//:halide_config_asan': 'asan', '@halide//:halide_config_msan': 'msan', '@halide//:halide_config_tsan': 'tsan', '//conditions:default': ''}), halide_function_name=function_name, outputs=['cpp'], tags=['manual'] + tags)
runtime_library = _halide_library_runtime_target_name(user_halide_target_features)
if runtime_library in _standard_library_runtime_names().to_list():
runtime_library = '@halide//:%s' % runtime_library
else:
if not native.existing_rule(runtime_library):
_define_halide_library_runtime(user_halide_target_features)
print('\nCreating Halide runtime library for feature set combination: ' + str(_discard_useless_features(user_halide_target_features)) + '\n' + 'If you see this message, there is no need to take any action; ' + 'however, please forward this message to halide-dev@lists.csail.mit.edu ' + 'so that we can include this case to reduce build times.')
runtime_library = ':%s' % runtime_library
native.cc_library(name=name, hdrs=[':%s_h' % name], deps=select(condition_deps) + deps + ['@halide//:runtime', runtime_library], includes=includes, tags=tags, visibility=visibility)
native.genrule(name='%s_RunGenStubs' % name, srcs=['@halide//:tools/RunGenStubs.cpp'], cmd='cat $(location @halide//:tools/RunGenStubs.cpp) | ' + 'sed -e \'s|HL_RUNGEN_FILTER_HEADER|"%s%s%s.h"|g\' > $@' % (PACKAGE_NAME, '/' if PACKAGE_NAME else '', name), outs=['%s_RunGenStubs.cpp' % name], tags=['manual', 'notap'] + tags, visibility=['//visibility:private'])
native.cc_binary(name='%s.rungen' % name, srcs=[':%s_RunGenStubs' % name], deps=['@halide//:rungen', ':%s' % name], tags=['manual', 'notap'] + tags, visibility=['//visibility:private'])
return '//%s:%s' % (PACKAGE_NAME, name)
def halide_library(name, srcs, copts=[], debug_codegen_level=0, extra_outputs=[], filter_deps=[], function_name=None, generator_args=[], generator_deps=[], generator_name=None, halide_target_features=[], halide_target_map=halide_library_default_target_map(), hexagon_code_signer=None, includes=[], namespace=None, visibility=None):
halide_generator(name='%s.generator' % name, srcs=srcs, generator_name=generator_name, deps=generator_deps, includes=includes, copts=copts, visibility=visibility)
return halide_library_from_generator(name=name, generator=':%s.generator' % name, deps=filter_deps, visibility=visibility, namespace=namespace, includes=includes, function_name=function_name, generator_args=generator_args, debug_codegen_level=debug_codegen_level, halide_target_features=halide_target_features, halide_target_map=halide_target_map, hexagon_code_signer=hexagon_code_signer, extra_outputs=extra_outputs) |
# pylint: disable=missing-function-docstring, missing-module-docstring/
def compare_str_isnot() :
n = 'hello world'
a = 'hello world'
return n is not a
| def compare_str_isnot():
n = 'hello world'
a = 'hello world'
return n is not a |
def calcOccurrences(itemset: list) -> int:
return len(list(filter(lambda x: x == 1, itemset)))
def calcOccurrencesOfBoth(itemset1: list, itemset2: list) -> int:
count: int = 0
for i in range(len(itemset1)):
if itemset1[i] == 1 and itemset2[i] == 1:
count += 1
return count
def support(*itemsets) -> float:
occurrencesOfItem: float = 0
if len(itemsets) == 1:
occurrencesOfItem = calcOccurrences(itemsets[0])
elif len(itemsets) == 2:
occurrencesOfItem = calcOccurrencesOfBoth(itemsets[0], itemsets[1])
return occurrencesOfItem / len(itemsets[0])
def confidence(itemset1: list, itemset2: list) -> float:
supportOfBoth: float = support(itemset1, itemset2)
return supportOfBoth / support(itemset1)
def lift(itemset1: list, itemset2: list):
supportOfBoth = support(itemset1, itemset2)
return supportOfBoth / (support(itemset1) * support(itemset2))
def main():
basket: dict = {
'milk': [1, 1, 1, 0],
'eggs': [1, 1, 0, 1],
'apples': [0, 0, 0, 1],
'bread': [1, 0, 1, 0]
}
print(f'Support {support(basket["milk"])}')
print(f'Confidence {confidence(basket["milk"], basket["eggs"])}')
print(f'Lift {lift(basket["milk"], basket["eggs"])}')
if __name__ == '__main__':
main()
| def calc_occurrences(itemset: list) -> int:
return len(list(filter(lambda x: x == 1, itemset)))
def calc_occurrences_of_both(itemset1: list, itemset2: list) -> int:
count: int = 0
for i in range(len(itemset1)):
if itemset1[i] == 1 and itemset2[i] == 1:
count += 1
return count
def support(*itemsets) -> float:
occurrences_of_item: float = 0
if len(itemsets) == 1:
occurrences_of_item = calc_occurrences(itemsets[0])
elif len(itemsets) == 2:
occurrences_of_item = calc_occurrences_of_both(itemsets[0], itemsets[1])
return occurrencesOfItem / len(itemsets[0])
def confidence(itemset1: list, itemset2: list) -> float:
support_of_both: float = support(itemset1, itemset2)
return supportOfBoth / support(itemset1)
def lift(itemset1: list, itemset2: list):
support_of_both = support(itemset1, itemset2)
return supportOfBoth / (support(itemset1) * support(itemset2))
def main():
basket: dict = {'milk': [1, 1, 1, 0], 'eggs': [1, 1, 0, 1], 'apples': [0, 0, 0, 1], 'bread': [1, 0, 1, 0]}
print(f"Support {support(basket['milk'])}")
print(f"Confidence {confidence(basket['milk'], basket['eggs'])}")
print(f"Lift {lift(basket['milk'], basket['eggs'])}")
if __name__ == '__main__':
main() |
# names = ['LHL','YB','ZSH','LY','DYC']
# # print(str(x[0]) + str(x[1]) + str(x[2]) + str(x[3]) + str(x[4]));
# for name in names:
# print(name.lower().title());
# print("SB:" + name);
# for name in names:
# print(name.lower().title());
# print("SB:" + name);
# for name in names:
# print(name.lower().title());
# print("SB:" + name);
# x = 0;
# print(x);
provinces = [['Kunming','Anning','Dali'],['Beijing'],['Shenzhen','GuangZhou','ZhuHai','Shantou']]
# [Kunming,Anning,Dali]
for province in provinces:
for city in province:
print(city);
| provinces = [['Kunming', 'Anning', 'Dali'], ['Beijing'], ['Shenzhen', 'GuangZhou', 'ZhuHai', 'Shantou']]
for province in provinces:
for city in province:
print(city) |
""" Version information for Lackey module
"""
__version__ = "0.7.4"
__sikuli_version__ = "1.1.0"
| """ Version information for Lackey module
"""
__version__ = '0.7.4'
__sikuli_version__ = '1.1.0' |
# Source : https://leetcode.com/problems/minimum-moves-to-convert-string/
# Author : foxfromworld
# Date : 10/12/2021
# First attempt
class Solution:
def minimumMoves(self, s: str) -> int:
index = 0
ret = 0
while index < len(s):
if s[index] == 'X':
ret += 1
index += 3
else:
index += 1
return ret
| class Solution:
def minimum_moves(self, s: str) -> int:
index = 0
ret = 0
while index < len(s):
if s[index] == 'X':
ret += 1
index += 3
else:
index += 1
return ret |
def fact(n):
return 1 if n == 0 else n*fact(n-1)
def comb(n, x):
return fact(n) / (fact(x) * fact(n-x))
def b(x, n, p):
return comb(n, x) * p**x * (1-p)**(n-x)
l, r = list(map(float, input().split(" ")))
odds = l / r
print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3))
| def fact(n):
return 1 if n == 0 else n * fact(n - 1)
def comb(n, x):
return fact(n) / (fact(x) * fact(n - x))
def b(x, n, p):
return comb(n, x) * p ** x * (1 - p) ** (n - x)
(l, r) = list(map(float, input().split(' ')))
odds = l / r
print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3)) |
n, m = map(int, input().split())
for _ in range(n):
if input().find('LOVE') != -1:
print('YES')
exit()
print('NO')
| (n, m) = map(int, input().split())
for _ in range(n):
if input().find('LOVE') != -1:
print('YES')
exit()
print('NO') |
# Created byMartin.cz
# Copyright (c) Martin Strohalm. All rights reserved.
class Enum(object):
"""
Defines a generic enum type, where values are provided as key:value pairs.
The key can be used to access the value like from dict (e.g. enum[key]) or
as property (e.g. enum.key). Each value must be unique.
Note that unlike the normal dict, the Enum __contains__ method is not
checking for keys but for values.
"""
def __init__(self, **kwargs):
"""Initializes a new instance of Enum."""
# get named values
self._map = kwargs
# get all values
values = list(kwargs.values())
self._values = set(values)
# check values
if len(values) != len(self._values):
message = "Enum values are not unique! -> %s" % ", ".join(str(v) for v in values)
raise AttributeError(message)
def __contains__(self, value):
"""Checks whether value exists."""
return value in self._values
def __getattr__(self, name):
"""Gets value by its name."""
if name in self._map:
return self._map[name]
raise AttributeError(name)
def __getitem__(self, name):
"""Gets value by its name."""
if name in self._map:
return self._map[name]
raise KeyError(name)
def __iter__(self):
"""Gets values iterator."""
return self._values.__iter__()
| class Enum(object):
"""
Defines a generic enum type, where values are provided as key:value pairs.
The key can be used to access the value like from dict (e.g. enum[key]) or
as property (e.g. enum.key). Each value must be unique.
Note that unlike the normal dict, the Enum __contains__ method is not
checking for keys but for values.
"""
def __init__(self, **kwargs):
"""Initializes a new instance of Enum."""
self._map = kwargs
values = list(kwargs.values())
self._values = set(values)
if len(values) != len(self._values):
message = 'Enum values are not unique! -> %s' % ', '.join((str(v) for v in values))
raise attribute_error(message)
def __contains__(self, value):
"""Checks whether value exists."""
return value in self._values
def __getattr__(self, name):
"""Gets value by its name."""
if name in self._map:
return self._map[name]
raise attribute_error(name)
def __getitem__(self, name):
"""Gets value by its name."""
if name in self._map:
return self._map[name]
raise key_error(name)
def __iter__(self):
"""Gets values iterator."""
return self._values.__iter__() |
# base path to YOLO directory
MODEL_PATH = "yolo-coco"
# initialize minimum probability to filter weak detections along with
# the threshold when applying non-maxima suppression
MIN_CONF = 0.3
NMS_THRESH = 0.3
# boolean indicating if NVIDIA CUDA GPU should be used
USE_GPU = True
# define the minimum safe distance (in pixels) that two people can be
# from each other
MIN_DISTANCE = 50
FLOWMAP_DISTANCE = 25
FLOWMAP_SIZE = 1000
FLOWMAP_BATCH = 100
BLOCKSIZE_X = 30
BLOCKSIZE_Y = BLOCKSIZE_X
OUTPUT_X = 960
OUTPUT_Y = 540
| model_path = 'yolo-coco'
min_conf = 0.3
nms_thresh = 0.3
use_gpu = True
min_distance = 50
flowmap_distance = 25
flowmap_size = 1000
flowmap_batch = 100
blocksize_x = 30
blocksize_y = BLOCKSIZE_X
output_x = 960
output_y = 540 |
# server.py flask configuration
# To use this file first export this path as SERVER_SETTINGS, before running
# the flask server. i.e. export SERVER_SETTINGS=config.py
LIRC_PATH = "/dev/lirc0"
SAVE_STATE_PATH = "/tmp/heatpump.state" | lirc_path = '/dev/lirc0'
save_state_path = '/tmp/heatpump.state' |
cx = 0
cy = 0
fsize = 0
counter = 0
class FunnyRect():
def setCenter(self, x,y):
self.cx = x
self.cy = y
def setSize(self, size):
self.size = size
def render(self):
rect(self.cx, self.cy, self.size, self.size)
funnyRect0b = FunnyRect()
funnyRect0b1 = FunnyRect()
def setup():
size(600,600)
smooth()
noStroke()
# rectMode(CENTER)
funnyRect0b.setSize(50)
funnyRect0b1.setSize(20)
def draw():
global counter
background(255)
fill(50)
obX = mouseX + sin( counter )*150
obY = mouseY + cos( counter )*150
funnyRect0b.setCenter(mouseX, mouseY)
funnyRect0b.render()
funnyRect0b1.setCenter(obX, obY)
funnyRect0b1.render()
counter+=0.05
| cx = 0
cy = 0
fsize = 0
counter = 0
class Funnyrect:
def set_center(self, x, y):
self.cx = x
self.cy = y
def set_size(self, size):
self.size = size
def render(self):
rect(self.cx, self.cy, self.size, self.size)
funny_rect0b = funny_rect()
funny_rect0b1 = funny_rect()
def setup():
size(600, 600)
smooth()
no_stroke()
funnyRect0b.setSize(50)
funnyRect0b1.setSize(20)
def draw():
global counter
background(255)
fill(50)
ob_x = mouseX + sin(counter) * 150
ob_y = mouseY + cos(counter) * 150
funnyRect0b.setCenter(mouseX, mouseY)
funnyRect0b.render()
funnyRect0b1.setCenter(obX, obY)
funnyRect0b1.render()
counter += 0.05 |
#
# PySNMP MIB module DVMRP-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:17:27 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint")
InterfaceIndexOrZero, InterfaceIndex = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero", "InterfaceIndex")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
IpAddress, Integer32, iso, experimental, Bits, Gauge32, ObjectIdentity, NotificationType, MibIdentifier, Counter64, ModuleIdentity, Counter32, TimeTicks, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Integer32", "iso", "experimental", "Bits", "Gauge32", "ObjectIdentity", "NotificationType", "MibIdentifier", "Counter64", "ModuleIdentity", "Counter32", "TimeTicks", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus")
dvmrpStdMIB = ModuleIdentity((1, 3, 6, 1, 3, 62))
dvmrpStdMIB.setRevisions(('2001-11-21 12:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: dvmrpStdMIB.setRevisionsDescriptions(('Initial version, published as RFC xxxx (to be filled in by RFC-Editor).',))
if mibBuilder.loadTexts: dvmrpStdMIB.setLastUpdated('200111211200Z')
if mibBuilder.loadTexts: dvmrpStdMIB.setOrganization('IETF IDMR Working Group.')
if mibBuilder.loadTexts: dvmrpStdMIB.setContactInfo(' Dave Thaler Microsoft One Microsoft Way Redmond, WA 98052-6399 EMail: dthaler@microsoft.com')
if mibBuilder.loadTexts: dvmrpStdMIB.setDescription('The MIB module for management of DVMRP routers.')
dvmrpMIBObjects = MibIdentifier((1, 3, 6, 1, 3, 62, 1))
dvmrp = MibIdentifier((1, 3, 6, 1, 3, 62, 1, 1))
dvmrpScalar = MibIdentifier((1, 3, 6, 1, 3, 62, 1, 1, 1))
dvmrpVersionString = MibScalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 1), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpVersionString.setStatus('current')
if mibBuilder.loadTexts: dvmrpVersionString.setDescription("The router's DVMRP version information. Similar to sysDescr in MIB-II, this is a free-form field which can be used to display vendor-specific information.")
dvmrpNumRoutes = MibScalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 3), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNumRoutes.setStatus('current')
if mibBuilder.loadTexts: dvmrpNumRoutes.setDescription('The number of entries in the routing table. This can be used to monitor the routing table size.')
dvmrpReachableRoutes = MibScalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 4), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpReachableRoutes.setStatus('current')
if mibBuilder.loadTexts: dvmrpReachableRoutes.setDescription('The number of entries in the routing table with non infinite metrics. This can be used to detect network partitions by observing the ratio of reachable routes to total routes.')
dvmrpInterfaceTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 2), )
if mibBuilder.loadTexts: dvmrpInterfaceTable.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceTable.setDescription("The (conceptual) table listing the router's multicast- capable interfaces.")
dvmrpInterfaceEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 2, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpInterfaceIndex"))
if mibBuilder.loadTexts: dvmrpInterfaceEntry.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceEntry.setDescription('An entry (conceptual row) in the dvmrpInterfaceTable. This row augments ipMRouteInterfaceEntry in the IP Multicast MIB, where the threshold object resides.')
dvmrpInterfaceIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: dvmrpInterfaceIndex.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceIndex.setDescription('The ifIndex value of the interface for which DVMRP is enabled.')
dvmrpInterfaceLocalAddress = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 2), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceLocalAddress.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceLocalAddress.setDescription('The IP address this system will use as a source address on this interface. On unnumbered interfaces, it must be the same value as dvmrpInterfaceLocalAddress for some interface on the system.')
dvmrpInterfaceMetric = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceMetric.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceMetric.setDescription('The distance metric for this interface which is used to calculate distance vectors.')
dvmrpInterfaceStatus = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceStatus.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceStatus.setDescription('The status of this entry. Creating the entry enables DVMRP on the virtual interface; destroying the entry or setting it to notInService disables DVMRP on the virtual interface.')
dvmrpInterfaceRcvBadPkts = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpInterfaceRcvBadPkts.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceRcvBadPkts.setDescription('The number of DVMRP messages received on the interface by the DVMRP process which were subsequently discarded as invalid (e.g. invalid packet format, or a route report from an unknown neighbor).')
dvmrpInterfaceRcvBadRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpInterfaceRcvBadRoutes.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceRcvBadRoutes.setDescription('The number of routes, in valid DVMRP packets, which were ignored because the entry was invalid.')
dvmrpInterfaceSentRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpInterfaceSentRoutes.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceSentRoutes.setDescription('The number of routes, in DVMRP Report packets, which have been sent on this interface. Together with dvmrpNeighborRcvRoutes at a peer, this object is useful for detecting routes being lost.')
dvmrpInterfaceKey = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 8), SnmpAdminString()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceKey.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceKey.setDescription('The (shared) key for authenticating neighbors on this interface. This object is intended solely for the purpose of setting the interface key, and MUST be accessible only via requests using both authentication and privacy. The agent MAY report an empty string in response to get, get- next, get-bulk requests.')
dvmrpInterfaceKeyVersion = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 9), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: dvmrpInterfaceKeyVersion.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceKeyVersion.setDescription('The highest version number of all known interface keys for this interface used for authenticating neighbors.')
dvmrpInterfaceGenerationId = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 10), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpInterfaceGenerationId.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceGenerationId.setDescription('The generation identifier for the interface. This is used by neighboring routers to detect whether the DVMRP routing table should be resent.')
dvmrpNeighborTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 3), )
if mibBuilder.loadTexts: dvmrpNeighborTable.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborTable.setDescription("The (conceptual) table listing the router's DVMRP neighbors, as discovered by receiving DVMRP messages.")
dvmrpNeighborEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 3, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpNeighborIfIndex"), (0, "DVMRP-STD-MIB", "dvmrpNeighborAddress"))
if mibBuilder.loadTexts: dvmrpNeighborEntry.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborEntry.setDescription('An entry (conceptual row) in the dvmrpNeighborTable.')
dvmrpNeighborIfIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: dvmrpNeighborIfIndex.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborIfIndex.setDescription('The value of ifIndex for the virtual interface used to reach this DVMRP neighbor.')
dvmrpNeighborAddress = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpNeighborAddress.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborAddress.setDescription('The IP address of the DVMRP neighbor for which this entry contains information.')
dvmrpNeighborUpTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 3), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborUpTime.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborUpTime.setDescription('The time since this DVMRP neighbor (last) became a neighbor of the local router.')
dvmrpNeighborExpiryTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborExpiryTime.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborExpiryTime.setDescription('The minimum time remaining before this DVMRP neighbor will be aged out.')
dvmrpNeighborGenerationId = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborGenerationId.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborGenerationId.setDescription("The neighboring router's generation identifier.")
dvmrpNeighborMajorVersion = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborMajorVersion.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborMajorVersion.setDescription("The neighboring router's major DVMRP version number.")
dvmrpNeighborMinorVersion = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborMinorVersion.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborMinorVersion.setDescription("The neighboring router's minor DVMRP version number.")
dvmrpNeighborCapabilities = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 8), Bits().clone(namedValues=NamedValues(("leaf", 0), ("prune", 1), ("generationID", 2), ("mtrace", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborCapabilities.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborCapabilities.setDescription("This object describes the neighboring router's capabilities. The leaf bit indicates that the neighbor has only one interface with neighbors. The prune bit indicates that the neighbor supports pruning. The generationID bit indicates that the neighbor sends its generationID in Probe messages. The mtrace bit indicates that the neighbor can handle mtrace requests.")
dvmrpNeighborRcvRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborRcvRoutes.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborRcvRoutes.setDescription('The total number of routes received in valid DVMRP packets received from this neighbor. This can be used to diagnose problems such as unicast route injection, as well as giving an indication of the level of DVMRP route exchange activity.')
dvmrpNeighborRcvBadPkts = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborRcvBadPkts.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborRcvBadPkts.setDescription('The number of packet received from this neighbor which were discarded as invalid.')
dvmrpNeighborRcvBadRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborRcvBadRoutes.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborRcvBadRoutes.setDescription('The number of routes, in valid DVMRP packets received from this neighbor, which were ignored because the entry was invalid.')
dvmrpNeighborState = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("oneway", 1), ("active", 2), ("ignoring", 3), ("down", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpNeighborState.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborState.setDescription('State of the neighbor adjacency.')
dvmrpRouteTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 4), )
if mibBuilder.loadTexts: dvmrpRouteTable.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteTable.setDescription('The table of routes learned through DVMRP route exchange.')
dvmrpRouteEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 4, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpRouteSource"), (0, "DVMRP-STD-MIB", "dvmrpRouteSourceMask"))
if mibBuilder.loadTexts: dvmrpRouteEntry.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteEntry.setDescription('An entry (conceptual row) containing the multicast routing information used by DVMRP in place of the unicast routing information.')
dvmrpRouteSource = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 1), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteSource.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteSource.setDescription('The network address which when combined with the corresponding value of dvmrpRouteSourceMask identifies the sources for which this entry contains multicast routing information.')
dvmrpRouteSourceMask = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteSourceMask.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteSourceMask.setDescription('The network mask which when combined with the corresponding value of dvmrpRouteSource identifies the sources for which this entry contains multicast routing information.')
dvmrpRouteUpstreamNeighbor = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteUpstreamNeighbor.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteUpstreamNeighbor.setDescription('The address of the upstream neighbor (e.g., RPF neighbor) from which IP datagrams from these sources are received.')
dvmrpRouteIfIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 4), InterfaceIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteIfIndex.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteIfIndex.setDescription('The value of ifIndex for the interface on which IP datagrams sent by these sources are received. A value of 0 typically means the route is an aggregate for which no next- hop interface exists.')
dvmrpRouteMetric = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteMetric.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteMetric.setDescription('The distance in hops to the source subnet.')
dvmrpRouteExpiryTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 6), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteExpiryTime.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteExpiryTime.setDescription('The minimum amount of time remaining before this entry will be aged out.')
dvmrpRouteUpTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 7), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteUpTime.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteUpTime.setDescription('The time since the route represented by this entry was learned by the router.')
dvmrpRouteNextHopTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 5), )
if mibBuilder.loadTexts: dvmrpRouteNextHopTable.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteNextHopTable.setDescription('The (conceptual) table containing information on the next hops on outgoing interfaces for routing IP multicast datagrams.')
dvmrpRouteNextHopEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 5, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpRouteNextHopSource"), (0, "DVMRP-STD-MIB", "dvmrpRouteNextHopSourceMask"), (0, "DVMRP-STD-MIB", "dvmrpRouteNextHopIfIndex"))
if mibBuilder.loadTexts: dvmrpRouteNextHopEntry.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteNextHopEntry.setDescription('An entry (conceptual row) in the list of next hops on outgoing interfaces to which IP multicast datagrams from particular sources are routed.')
dvmrpRouteNextHopSource = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 1), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteNextHopSource.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteNextHopSource.setDescription('The network address which when combined with the corresponding value of dvmrpRouteNextHopSourceMask identifies the sources for which this entry specifies a next hop on an outgoing interface.')
dvmrpRouteNextHopSourceMask = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpRouteNextHopSourceMask.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteNextHopSourceMask.setDescription('The network mask which when combined with the corresponding value of dvmrpRouteNextHopSource identifies the sources for which this entry specifies a next hop on an outgoing interface.')
dvmrpRouteNextHopIfIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 3), InterfaceIndex())
if mibBuilder.loadTexts: dvmrpRouteNextHopIfIndex.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteNextHopIfIndex.setDescription('The ifIndex value of the interface for the outgoing interface for this next hop.')
dvmrpRouteNextHopType = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("leaf", 1), ("branch", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpRouteNextHopType.setStatus('current')
if mibBuilder.loadTexts: dvmrpRouteNextHopType.setDescription('Type is leaf if no downstream dependent neighbors exist on the outgoing virtual interface. Otherwise, type is branch.')
dvmrpPruneTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 6), )
if mibBuilder.loadTexts: dvmrpPruneTable.setStatus('current')
if mibBuilder.loadTexts: dvmrpPruneTable.setDescription("The (conceptual) table listing the router's upstream prune state.")
dvmrpPruneEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 6, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpPruneGroup"), (0, "DVMRP-STD-MIB", "dvmrpPruneSource"), (0, "DVMRP-STD-MIB", "dvmrpPruneSourceMask"))
if mibBuilder.loadTexts: dvmrpPruneEntry.setStatus('current')
if mibBuilder.loadTexts: dvmrpPruneEntry.setDescription('An entry (conceptual row) in the dvmrpPruneTable.')
dvmrpPruneGroup = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 1), IpAddress())
if mibBuilder.loadTexts: dvmrpPruneGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpPruneGroup.setDescription('The group address which has been pruned.')
dvmrpPruneSource = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 2), IpAddress())
if mibBuilder.loadTexts: dvmrpPruneSource.setStatus('current')
if mibBuilder.loadTexts: dvmrpPruneSource.setDescription('The address of the source or source network which has been pruned.')
dvmrpPruneSourceMask = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 3), IpAddress())
if mibBuilder.loadTexts: dvmrpPruneSourceMask.setStatus('current')
if mibBuilder.loadTexts: dvmrpPruneSourceMask.setDescription("The address of the source or source network which has been pruned. The mask must either be all 1's, or else dvmrpPruneSource and dvmrpPruneSourceMask must match dvmrpRouteSource and dvmrpRouteSourceMask for some entry in the dvmrpRouteTable.")
dvmrpPruneExpiryTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 4), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: dvmrpPruneExpiryTime.setStatus('current')
if mibBuilder.loadTexts: dvmrpPruneExpiryTime.setDescription("The amount of time remaining before this prune should expire at the upstream neighbor. This value should be the minimum of the default prune lifetime and the remaining prune lifetimes of the local router's downstream neighbors, if any.")
dvmrpTraps = MibIdentifier((1, 3, 6, 1, 3, 62, 1, 1, 7))
dvmrpNeighborLoss = NotificationType((1, 3, 6, 1, 3, 62, 1, 1, 7, 1)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB", "dvmrpNeighborState"))
if mibBuilder.loadTexts: dvmrpNeighborLoss.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborLoss.setDescription('A dvmrpNeighborLoss trap signifies the loss of a 2-way adjacency with a neighbor. This trap should be generated when the neighbor state changes from active to one-way, ignoring, or down. The trap should be generated only if the router has no other neighbors on the same interface with a lower IP address than itself.')
dvmrpNeighborNotPruning = NotificationType((1, 3, 6, 1, 3, 62, 1, 1, 7, 2)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB", "dvmrpNeighborCapabilities"))
if mibBuilder.loadTexts: dvmrpNeighborNotPruning.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborNotPruning.setDescription('A dvmrpNeighborNotPruning trap signifies that a non-pruning neighbor has been detected (in an implementation-dependent manner). This trap should be generated at most once per generation ID of the neighbor. For example, it should be generated at the time a neighbor is first heard from if the prune bit is not set in its capabilities. It should also be generated if the local system has the ability to tell that a neighbor which sets the the prune bit in its capabilities is not pruning any branches over an extended period of time. The trap should be generated only if the router has no other neighbors on the same interface with a lower IP address than itself.')
dvmrpMIBConformance = MibIdentifier((1, 3, 6, 1, 3, 62, 2))
dvmrpMIBCompliances = MibIdentifier((1, 3, 6, 1, 3, 62, 2, 1))
dvmrpMIBGroups = MibIdentifier((1, 3, 6, 1, 3, 62, 2, 2))
dvmrpMIBCompliance = ModuleCompliance((1, 3, 6, 1, 3, 62, 2, 1, 1)).setObjects(("DVMRP-STD-MIB", "dvmrpGeneralGroup"), ("DVMRP-STD-MIB", "dvmrpInterfaceGroup"), ("DVMRP-STD-MIB", "dvmrpNeighborGroup"), ("DVMRP-STD-MIB", "dvmrpRoutingGroup"), ("DVMRP-STD-MIB", "dvmrpTreeGroup"), ("DVMRP-STD-MIB", "dvmrpSecurityGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpMIBCompliance = dvmrpMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: dvmrpMIBCompliance.setDescription('The compliance statement for the DVMRP MIB.')
dvmrpGeneralGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 2)).setObjects(("DVMRP-STD-MIB", "dvmrpVersionString"), ("DVMRP-STD-MIB", "dvmrpNumRoutes"), ("DVMRP-STD-MIB", "dvmrpReachableRoutes"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpGeneralGroup = dvmrpGeneralGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpGeneralGroup.setDescription('A collection of objects used to describe general DVMRP configuration information.')
dvmrpInterfaceGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 3)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB", "dvmrpInterfaceMetric"), ("DVMRP-STD-MIB", "dvmrpInterfaceStatus"), ("DVMRP-STD-MIB", "dvmrpInterfaceGenerationId"), ("DVMRP-STD-MIB", "dvmrpInterfaceRcvBadPkts"), ("DVMRP-STD-MIB", "dvmrpInterfaceRcvBadRoutes"), ("DVMRP-STD-MIB", "dvmrpInterfaceSentRoutes"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpInterfaceGroup = dvmrpInterfaceGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpInterfaceGroup.setDescription('A collection of objects used to describe DVMRP interface configuration and statistics.')
dvmrpNeighborGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 4)).setObjects(("DVMRP-STD-MIB", "dvmrpNeighborUpTime"), ("DVMRP-STD-MIB", "dvmrpNeighborExpiryTime"), ("DVMRP-STD-MIB", "dvmrpNeighborGenerationId"), ("DVMRP-STD-MIB", "dvmrpNeighborMajorVersion"), ("DVMRP-STD-MIB", "dvmrpNeighborMinorVersion"), ("DVMRP-STD-MIB", "dvmrpNeighborCapabilities"), ("DVMRP-STD-MIB", "dvmrpNeighborRcvRoutes"), ("DVMRP-STD-MIB", "dvmrpNeighborRcvBadPkts"), ("DVMRP-STD-MIB", "dvmrpNeighborRcvBadRoutes"), ("DVMRP-STD-MIB", "dvmrpNeighborState"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpNeighborGroup = dvmrpNeighborGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpNeighborGroup.setDescription('A collection of objects used to describe DVMRP peer configuration and statistics.')
dvmrpRoutingGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 5)).setObjects(("DVMRP-STD-MIB", "dvmrpRouteUpstreamNeighbor"), ("DVMRP-STD-MIB", "dvmrpRouteIfIndex"), ("DVMRP-STD-MIB", "dvmrpRouteMetric"), ("DVMRP-STD-MIB", "dvmrpRouteExpiryTime"), ("DVMRP-STD-MIB", "dvmrpRouteUpTime"), ("DVMRP-STD-MIB", "dvmrpRouteNextHopType"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpRoutingGroup = dvmrpRoutingGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpRoutingGroup.setDescription('A collection of objects used to store the DVMRP routing table.')
dvmrpSecurityGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 6)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceKey"), ("DVMRP-STD-MIB", "dvmrpInterfaceKeyVersion"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpSecurityGroup = dvmrpSecurityGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpSecurityGroup.setDescription('A collection of objects used to store information related to DVMRP security.')
dvmrpTreeGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 7)).setObjects(("DVMRP-STD-MIB", "dvmrpPruneExpiryTime"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpTreeGroup = dvmrpTreeGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpTreeGroup.setDescription('A collection of objects used to store information related to DVMRP prune state.')
dvmrpNotificationGroup = NotificationGroup((1, 3, 6, 1, 3, 62, 2, 2, 8)).setObjects(("DVMRP-STD-MIB", "dvmrpNeighborLoss"), ("DVMRP-STD-MIB", "dvmrpNeighborNotPruning"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrpNotificationGroup = dvmrpNotificationGroup.setStatus('current')
if mibBuilder.loadTexts: dvmrpNotificationGroup.setDescription('A collection of notifications for signaling important DVMRP events.')
mibBuilder.exportSymbols("DVMRP-STD-MIB", dvmrpStdMIB=dvmrpStdMIB, dvmrpRouteUpstreamNeighbor=dvmrpRouteUpstreamNeighbor, dvmrpInterfaceLocalAddress=dvmrpInterfaceLocalAddress, dvmrpGeneralGroup=dvmrpGeneralGroup, dvmrpRouteNextHopEntry=dvmrpRouteNextHopEntry, dvmrpNumRoutes=dvmrpNumRoutes, dvmrpRouteNextHopSourceMask=dvmrpRouteNextHopSourceMask, dvmrpRouteNextHopSource=dvmrpRouteNextHopSource, dvmrpNeighborMinorVersion=dvmrpNeighborMinorVersion, dvmrpRouteIfIndex=dvmrpRouteIfIndex, dvmrpNeighborRcvRoutes=dvmrpNeighborRcvRoutes, dvmrpRouteMetric=dvmrpRouteMetric, dvmrpScalar=dvmrpScalar, dvmrpNeighborGenerationId=dvmrpNeighborGenerationId, dvmrpPruneTable=dvmrpPruneTable, dvmrpPruneGroup=dvmrpPruneGroup, dvmrpPruneSourceMask=dvmrpPruneSourceMask, dvmrp=dvmrp, dvmrpNeighborCapabilities=dvmrpNeighborCapabilities, dvmrpMIBConformance=dvmrpMIBConformance, dvmrpInterfaceMetric=dvmrpInterfaceMetric, dvmrpInterfaceKey=dvmrpInterfaceKey, dvmrpNeighborAddress=dvmrpNeighborAddress, dvmrpReachableRoutes=dvmrpReachableRoutes, dvmrpRouteTable=dvmrpRouteTable, dvmrpRouteSource=dvmrpRouteSource, dvmrpRouteSourceMask=dvmrpRouteSourceMask, dvmrpNeighborState=dvmrpNeighborState, dvmrpNeighborGroup=dvmrpNeighborGroup, dvmrpRoutingGroup=dvmrpRoutingGroup, dvmrpPruneSource=dvmrpPruneSource, dvmrpTraps=dvmrpTraps, dvmrpNeighborRcvBadPkts=dvmrpNeighborRcvBadPkts, dvmrpInterfaceRcvBadPkts=dvmrpInterfaceRcvBadPkts, dvmrpNeighborTable=dvmrpNeighborTable, dvmrpNeighborLoss=dvmrpNeighborLoss, dvmrpNeighborNotPruning=dvmrpNeighborNotPruning, dvmrpInterfaceTable=dvmrpInterfaceTable, dvmrpMIBGroups=dvmrpMIBGroups, dvmrpInterfaceGroup=dvmrpInterfaceGroup, PYSNMP_MODULE_ID=dvmrpStdMIB, dvmrpNeighborMajorVersion=dvmrpNeighborMajorVersion, dvmrpVersionString=dvmrpVersionString, dvmrpRouteNextHopType=dvmrpRouteNextHopType, dvmrpInterfaceEntry=dvmrpInterfaceEntry, dvmrpPruneEntry=dvmrpPruneEntry, dvmrpInterfaceKeyVersion=dvmrpInterfaceKeyVersion, dvmrpNeighborRcvBadRoutes=dvmrpNeighborRcvBadRoutes, dvmrpInterfaceIndex=dvmrpInterfaceIndex, dvmrpNeighborUpTime=dvmrpNeighborUpTime, dvmrpNeighborEntry=dvmrpNeighborEntry, dvmrpRouteExpiryTime=dvmrpRouteExpiryTime, dvmrpMIBObjects=dvmrpMIBObjects, dvmrpNeighborIfIndex=dvmrpNeighborIfIndex, dvmrpInterfaceStatus=dvmrpInterfaceStatus, dvmrpTreeGroup=dvmrpTreeGroup, dvmrpInterfaceSentRoutes=dvmrpInterfaceSentRoutes, dvmrpNeighborExpiryTime=dvmrpNeighborExpiryTime, dvmrpInterfaceRcvBadRoutes=dvmrpInterfaceRcvBadRoutes, dvmrpMIBCompliances=dvmrpMIBCompliances, dvmrpRouteNextHopIfIndex=dvmrpRouteNextHopIfIndex, dvmrpSecurityGroup=dvmrpSecurityGroup, dvmrpRouteEntry=dvmrpRouteEntry, dvmrpRouteUpTime=dvmrpRouteUpTime, dvmrpRouteNextHopTable=dvmrpRouteNextHopTable, dvmrpPruneExpiryTime=dvmrpPruneExpiryTime, dvmrpNotificationGroup=dvmrpNotificationGroup, dvmrpMIBCompliance=dvmrpMIBCompliance, dvmrpInterfaceGenerationId=dvmrpInterfaceGenerationId)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, constraints_union, value_range_constraint, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint')
(interface_index_or_zero, interface_index) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndexOrZero', 'InterfaceIndex')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(ip_address, integer32, iso, experimental, bits, gauge32, object_identity, notification_type, mib_identifier, counter64, module_identity, counter32, time_ticks, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Integer32', 'iso', 'experimental', 'Bits', 'Gauge32', 'ObjectIdentity', 'NotificationType', 'MibIdentifier', 'Counter64', 'ModuleIdentity', 'Counter32', 'TimeTicks', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn')
(display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus')
dvmrp_std_mib = module_identity((1, 3, 6, 1, 3, 62))
dvmrpStdMIB.setRevisions(('2001-11-21 12:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
dvmrpStdMIB.setRevisionsDescriptions(('Initial version, published as RFC xxxx (to be filled in by RFC-Editor).',))
if mibBuilder.loadTexts:
dvmrpStdMIB.setLastUpdated('200111211200Z')
if mibBuilder.loadTexts:
dvmrpStdMIB.setOrganization('IETF IDMR Working Group.')
if mibBuilder.loadTexts:
dvmrpStdMIB.setContactInfo(' Dave Thaler Microsoft One Microsoft Way Redmond, WA 98052-6399 EMail: dthaler@microsoft.com')
if mibBuilder.loadTexts:
dvmrpStdMIB.setDescription('The MIB module for management of DVMRP routers.')
dvmrp_mib_objects = mib_identifier((1, 3, 6, 1, 3, 62, 1))
dvmrp = mib_identifier((1, 3, 6, 1, 3, 62, 1, 1))
dvmrp_scalar = mib_identifier((1, 3, 6, 1, 3, 62, 1, 1, 1))
dvmrp_version_string = mib_scalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 1), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpVersionString.setStatus('current')
if mibBuilder.loadTexts:
dvmrpVersionString.setDescription("The router's DVMRP version information. Similar to sysDescr in MIB-II, this is a free-form field which can be used to display vendor-specific information.")
dvmrp_num_routes = mib_scalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 3), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNumRoutes.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNumRoutes.setDescription('The number of entries in the routing table. This can be used to monitor the routing table size.')
dvmrp_reachable_routes = mib_scalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 4), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpReachableRoutes.setStatus('current')
if mibBuilder.loadTexts:
dvmrpReachableRoutes.setDescription('The number of entries in the routing table with non infinite metrics. This can be used to detect network partitions by observing the ratio of reachable routes to total routes.')
dvmrp_interface_table = mib_table((1, 3, 6, 1, 3, 62, 1, 1, 2))
if mibBuilder.loadTexts:
dvmrpInterfaceTable.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceTable.setDescription("The (conceptual) table listing the router's multicast- capable interfaces.")
dvmrp_interface_entry = mib_table_row((1, 3, 6, 1, 3, 62, 1, 1, 2, 1)).setIndexNames((0, 'DVMRP-STD-MIB', 'dvmrpInterfaceIndex'))
if mibBuilder.loadTexts:
dvmrpInterfaceEntry.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceEntry.setDescription('An entry (conceptual row) in the dvmrpInterfaceTable. This row augments ipMRouteInterfaceEntry in the IP Multicast MIB, where the threshold object resides.')
dvmrp_interface_index = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 1), interface_index())
if mibBuilder.loadTexts:
dvmrpInterfaceIndex.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceIndex.setDescription('The ifIndex value of the interface for which DVMRP is enabled.')
dvmrp_interface_local_address = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 2), ip_address()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
dvmrpInterfaceLocalAddress.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceLocalAddress.setDescription('The IP address this system will use as a source address on this interface. On unnumbered interfaces, it must be the same value as dvmrpInterfaceLocalAddress for some interface on the system.')
dvmrp_interface_metric = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 31)).clone(1)).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
dvmrpInterfaceMetric.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceMetric.setDescription('The distance metric for this interface which is used to calculate distance vectors.')
dvmrp_interface_status = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 4), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
dvmrpInterfaceStatus.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceStatus.setDescription('The status of this entry. Creating the entry enables DVMRP on the virtual interface; destroying the entry or setting it to notInService disables DVMRP on the virtual interface.')
dvmrp_interface_rcv_bad_pkts = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpInterfaceRcvBadPkts.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceRcvBadPkts.setDescription('The number of DVMRP messages received on the interface by the DVMRP process which were subsequently discarded as invalid (e.g. invalid packet format, or a route report from an unknown neighbor).')
dvmrp_interface_rcv_bad_routes = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpInterfaceRcvBadRoutes.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceRcvBadRoutes.setDescription('The number of routes, in valid DVMRP packets, which were ignored because the entry was invalid.')
dvmrp_interface_sent_routes = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpInterfaceSentRoutes.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceSentRoutes.setDescription('The number of routes, in DVMRP Report packets, which have been sent on this interface. Together with dvmrpNeighborRcvRoutes at a peer, this object is useful for detecting routes being lost.')
dvmrp_interface_key = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 8), snmp_admin_string()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
dvmrpInterfaceKey.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceKey.setDescription('The (shared) key for authenticating neighbors on this interface. This object is intended solely for the purpose of setting the interface key, and MUST be accessible only via requests using both authentication and privacy. The agent MAY report an empty string in response to get, get- next, get-bulk requests.')
dvmrp_interface_key_version = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 9), integer32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
dvmrpInterfaceKeyVersion.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceKeyVersion.setDescription('The highest version number of all known interface keys for this interface used for authenticating neighbors.')
dvmrp_interface_generation_id = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 10), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpInterfaceGenerationId.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceGenerationId.setDescription('The generation identifier for the interface. This is used by neighboring routers to detect whether the DVMRP routing table should be resent.')
dvmrp_neighbor_table = mib_table((1, 3, 6, 1, 3, 62, 1, 1, 3))
if mibBuilder.loadTexts:
dvmrpNeighborTable.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborTable.setDescription("The (conceptual) table listing the router's DVMRP neighbors, as discovered by receiving DVMRP messages.")
dvmrp_neighbor_entry = mib_table_row((1, 3, 6, 1, 3, 62, 1, 1, 3, 1)).setIndexNames((0, 'DVMRP-STD-MIB', 'dvmrpNeighborIfIndex'), (0, 'DVMRP-STD-MIB', 'dvmrpNeighborAddress'))
if mibBuilder.loadTexts:
dvmrpNeighborEntry.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborEntry.setDescription('An entry (conceptual row) in the dvmrpNeighborTable.')
dvmrp_neighbor_if_index = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 1), interface_index())
if mibBuilder.loadTexts:
dvmrpNeighborIfIndex.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborIfIndex.setDescription('The value of ifIndex for the virtual interface used to reach this DVMRP neighbor.')
dvmrp_neighbor_address = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 2), ip_address())
if mibBuilder.loadTexts:
dvmrpNeighborAddress.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborAddress.setDescription('The IP address of the DVMRP neighbor for which this entry contains information.')
dvmrp_neighbor_up_time = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 3), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborUpTime.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborUpTime.setDescription('The time since this DVMRP neighbor (last) became a neighbor of the local router.')
dvmrp_neighbor_expiry_time = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 4), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborExpiryTime.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborExpiryTime.setDescription('The minimum time remaining before this DVMRP neighbor will be aged out.')
dvmrp_neighbor_generation_id = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 5), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborGenerationId.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborGenerationId.setDescription("The neighboring router's generation identifier.")
dvmrp_neighbor_major_version = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborMajorVersion.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborMajorVersion.setDescription("The neighboring router's major DVMRP version number.")
dvmrp_neighbor_minor_version = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborMinorVersion.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborMinorVersion.setDescription("The neighboring router's minor DVMRP version number.")
dvmrp_neighbor_capabilities = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 8), bits().clone(namedValues=named_values(('leaf', 0), ('prune', 1), ('generationID', 2), ('mtrace', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborCapabilities.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborCapabilities.setDescription("This object describes the neighboring router's capabilities. The leaf bit indicates that the neighbor has only one interface with neighbors. The prune bit indicates that the neighbor supports pruning. The generationID bit indicates that the neighbor sends its generationID in Probe messages. The mtrace bit indicates that the neighbor can handle mtrace requests.")
dvmrp_neighbor_rcv_routes = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborRcvRoutes.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborRcvRoutes.setDescription('The total number of routes received in valid DVMRP packets received from this neighbor. This can be used to diagnose problems such as unicast route injection, as well as giving an indication of the level of DVMRP route exchange activity.')
dvmrp_neighbor_rcv_bad_pkts = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborRcvBadPkts.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborRcvBadPkts.setDescription('The number of packet received from this neighbor which were discarded as invalid.')
dvmrp_neighbor_rcv_bad_routes = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborRcvBadRoutes.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborRcvBadRoutes.setDescription('The number of routes, in valid DVMRP packets received from this neighbor, which were ignored because the entry was invalid.')
dvmrp_neighbor_state = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('oneway', 1), ('active', 2), ('ignoring', 3), ('down', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpNeighborState.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborState.setDescription('State of the neighbor adjacency.')
dvmrp_route_table = mib_table((1, 3, 6, 1, 3, 62, 1, 1, 4))
if mibBuilder.loadTexts:
dvmrpRouteTable.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteTable.setDescription('The table of routes learned through DVMRP route exchange.')
dvmrp_route_entry = mib_table_row((1, 3, 6, 1, 3, 62, 1, 1, 4, 1)).setIndexNames((0, 'DVMRP-STD-MIB', 'dvmrpRouteSource'), (0, 'DVMRP-STD-MIB', 'dvmrpRouteSourceMask'))
if mibBuilder.loadTexts:
dvmrpRouteEntry.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteEntry.setDescription('An entry (conceptual row) containing the multicast routing information used by DVMRP in place of the unicast routing information.')
dvmrp_route_source = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 1), ip_address())
if mibBuilder.loadTexts:
dvmrpRouteSource.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteSource.setDescription('The network address which when combined with the corresponding value of dvmrpRouteSourceMask identifies the sources for which this entry contains multicast routing information.')
dvmrp_route_source_mask = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 2), ip_address())
if mibBuilder.loadTexts:
dvmrpRouteSourceMask.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteSourceMask.setDescription('The network mask which when combined with the corresponding value of dvmrpRouteSource identifies the sources for which this entry contains multicast routing information.')
dvmrp_route_upstream_neighbor = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 3), ip_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpRouteUpstreamNeighbor.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteUpstreamNeighbor.setDescription('The address of the upstream neighbor (e.g., RPF neighbor) from which IP datagrams from these sources are received.')
dvmrp_route_if_index = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 4), interface_index_or_zero()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpRouteIfIndex.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteIfIndex.setDescription('The value of ifIndex for the interface on which IP datagrams sent by these sources are received. A value of 0 typically means the route is an aggregate for which no next- hop interface exists.')
dvmrp_route_metric = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 32))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpRouteMetric.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteMetric.setDescription('The distance in hops to the source subnet.')
dvmrp_route_expiry_time = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 6), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpRouteExpiryTime.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteExpiryTime.setDescription('The minimum amount of time remaining before this entry will be aged out.')
dvmrp_route_up_time = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 7), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpRouteUpTime.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteUpTime.setDescription('The time since the route represented by this entry was learned by the router.')
dvmrp_route_next_hop_table = mib_table((1, 3, 6, 1, 3, 62, 1, 1, 5))
if mibBuilder.loadTexts:
dvmrpRouteNextHopTable.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteNextHopTable.setDescription('The (conceptual) table containing information on the next hops on outgoing interfaces for routing IP multicast datagrams.')
dvmrp_route_next_hop_entry = mib_table_row((1, 3, 6, 1, 3, 62, 1, 1, 5, 1)).setIndexNames((0, 'DVMRP-STD-MIB', 'dvmrpRouteNextHopSource'), (0, 'DVMRP-STD-MIB', 'dvmrpRouteNextHopSourceMask'), (0, 'DVMRP-STD-MIB', 'dvmrpRouteNextHopIfIndex'))
if mibBuilder.loadTexts:
dvmrpRouteNextHopEntry.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteNextHopEntry.setDescription('An entry (conceptual row) in the list of next hops on outgoing interfaces to which IP multicast datagrams from particular sources are routed.')
dvmrp_route_next_hop_source = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 1), ip_address())
if mibBuilder.loadTexts:
dvmrpRouteNextHopSource.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteNextHopSource.setDescription('The network address which when combined with the corresponding value of dvmrpRouteNextHopSourceMask identifies the sources for which this entry specifies a next hop on an outgoing interface.')
dvmrp_route_next_hop_source_mask = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 2), ip_address())
if mibBuilder.loadTexts:
dvmrpRouteNextHopSourceMask.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteNextHopSourceMask.setDescription('The network mask which when combined with the corresponding value of dvmrpRouteNextHopSource identifies the sources for which this entry specifies a next hop on an outgoing interface.')
dvmrp_route_next_hop_if_index = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 3), interface_index())
if mibBuilder.loadTexts:
dvmrpRouteNextHopIfIndex.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteNextHopIfIndex.setDescription('The ifIndex value of the interface for the outgoing interface for this next hop.')
dvmrp_route_next_hop_type = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('leaf', 1), ('branch', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpRouteNextHopType.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRouteNextHopType.setDescription('Type is leaf if no downstream dependent neighbors exist on the outgoing virtual interface. Otherwise, type is branch.')
dvmrp_prune_table = mib_table((1, 3, 6, 1, 3, 62, 1, 1, 6))
if mibBuilder.loadTexts:
dvmrpPruneTable.setStatus('current')
if mibBuilder.loadTexts:
dvmrpPruneTable.setDescription("The (conceptual) table listing the router's upstream prune state.")
dvmrp_prune_entry = mib_table_row((1, 3, 6, 1, 3, 62, 1, 1, 6, 1)).setIndexNames((0, 'DVMRP-STD-MIB', 'dvmrpPruneGroup'), (0, 'DVMRP-STD-MIB', 'dvmrpPruneSource'), (0, 'DVMRP-STD-MIB', 'dvmrpPruneSourceMask'))
if mibBuilder.loadTexts:
dvmrpPruneEntry.setStatus('current')
if mibBuilder.loadTexts:
dvmrpPruneEntry.setDescription('An entry (conceptual row) in the dvmrpPruneTable.')
dvmrp_prune_group = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 1), ip_address())
if mibBuilder.loadTexts:
dvmrpPruneGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpPruneGroup.setDescription('The group address which has been pruned.')
dvmrp_prune_source = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 2), ip_address())
if mibBuilder.loadTexts:
dvmrpPruneSource.setStatus('current')
if mibBuilder.loadTexts:
dvmrpPruneSource.setDescription('The address of the source or source network which has been pruned.')
dvmrp_prune_source_mask = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 3), ip_address())
if mibBuilder.loadTexts:
dvmrpPruneSourceMask.setStatus('current')
if mibBuilder.loadTexts:
dvmrpPruneSourceMask.setDescription("The address of the source or source network which has been pruned. The mask must either be all 1's, or else dvmrpPruneSource and dvmrpPruneSourceMask must match dvmrpRouteSource and dvmrpRouteSourceMask for some entry in the dvmrpRouteTable.")
dvmrp_prune_expiry_time = mib_table_column((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 4), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
dvmrpPruneExpiryTime.setStatus('current')
if mibBuilder.loadTexts:
dvmrpPruneExpiryTime.setDescription("The amount of time remaining before this prune should expire at the upstream neighbor. This value should be the minimum of the default prune lifetime and the remaining prune lifetimes of the local router's downstream neighbors, if any.")
dvmrp_traps = mib_identifier((1, 3, 6, 1, 3, 62, 1, 1, 7))
dvmrp_neighbor_loss = notification_type((1, 3, 6, 1, 3, 62, 1, 1, 7, 1)).setObjects(('DVMRP-STD-MIB', 'dvmrpInterfaceLocalAddress'), ('DVMRP-STD-MIB', 'dvmrpNeighborState'))
if mibBuilder.loadTexts:
dvmrpNeighborLoss.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborLoss.setDescription('A dvmrpNeighborLoss trap signifies the loss of a 2-way adjacency with a neighbor. This trap should be generated when the neighbor state changes from active to one-way, ignoring, or down. The trap should be generated only if the router has no other neighbors on the same interface with a lower IP address than itself.')
dvmrp_neighbor_not_pruning = notification_type((1, 3, 6, 1, 3, 62, 1, 1, 7, 2)).setObjects(('DVMRP-STD-MIB', 'dvmrpInterfaceLocalAddress'), ('DVMRP-STD-MIB', 'dvmrpNeighborCapabilities'))
if mibBuilder.loadTexts:
dvmrpNeighborNotPruning.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborNotPruning.setDescription('A dvmrpNeighborNotPruning trap signifies that a non-pruning neighbor has been detected (in an implementation-dependent manner). This trap should be generated at most once per generation ID of the neighbor. For example, it should be generated at the time a neighbor is first heard from if the prune bit is not set in its capabilities. It should also be generated if the local system has the ability to tell that a neighbor which sets the the prune bit in its capabilities is not pruning any branches over an extended period of time. The trap should be generated only if the router has no other neighbors on the same interface with a lower IP address than itself.')
dvmrp_mib_conformance = mib_identifier((1, 3, 6, 1, 3, 62, 2))
dvmrp_mib_compliances = mib_identifier((1, 3, 6, 1, 3, 62, 2, 1))
dvmrp_mib_groups = mib_identifier((1, 3, 6, 1, 3, 62, 2, 2))
dvmrp_mib_compliance = module_compliance((1, 3, 6, 1, 3, 62, 2, 1, 1)).setObjects(('DVMRP-STD-MIB', 'dvmrpGeneralGroup'), ('DVMRP-STD-MIB', 'dvmrpInterfaceGroup'), ('DVMRP-STD-MIB', 'dvmrpNeighborGroup'), ('DVMRP-STD-MIB', 'dvmrpRoutingGroup'), ('DVMRP-STD-MIB', 'dvmrpTreeGroup'), ('DVMRP-STD-MIB', 'dvmrpSecurityGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_mib_compliance = dvmrpMIBCompliance.setStatus('current')
if mibBuilder.loadTexts:
dvmrpMIBCompliance.setDescription('The compliance statement for the DVMRP MIB.')
dvmrp_general_group = object_group((1, 3, 6, 1, 3, 62, 2, 2, 2)).setObjects(('DVMRP-STD-MIB', 'dvmrpVersionString'), ('DVMRP-STD-MIB', 'dvmrpNumRoutes'), ('DVMRP-STD-MIB', 'dvmrpReachableRoutes'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_general_group = dvmrpGeneralGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpGeneralGroup.setDescription('A collection of objects used to describe general DVMRP configuration information.')
dvmrp_interface_group = object_group((1, 3, 6, 1, 3, 62, 2, 2, 3)).setObjects(('DVMRP-STD-MIB', 'dvmrpInterfaceLocalAddress'), ('DVMRP-STD-MIB', 'dvmrpInterfaceMetric'), ('DVMRP-STD-MIB', 'dvmrpInterfaceStatus'), ('DVMRP-STD-MIB', 'dvmrpInterfaceGenerationId'), ('DVMRP-STD-MIB', 'dvmrpInterfaceRcvBadPkts'), ('DVMRP-STD-MIB', 'dvmrpInterfaceRcvBadRoutes'), ('DVMRP-STD-MIB', 'dvmrpInterfaceSentRoutes'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_interface_group = dvmrpInterfaceGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpInterfaceGroup.setDescription('A collection of objects used to describe DVMRP interface configuration and statistics.')
dvmrp_neighbor_group = object_group((1, 3, 6, 1, 3, 62, 2, 2, 4)).setObjects(('DVMRP-STD-MIB', 'dvmrpNeighborUpTime'), ('DVMRP-STD-MIB', 'dvmrpNeighborExpiryTime'), ('DVMRP-STD-MIB', 'dvmrpNeighborGenerationId'), ('DVMRP-STD-MIB', 'dvmrpNeighborMajorVersion'), ('DVMRP-STD-MIB', 'dvmrpNeighborMinorVersion'), ('DVMRP-STD-MIB', 'dvmrpNeighborCapabilities'), ('DVMRP-STD-MIB', 'dvmrpNeighborRcvRoutes'), ('DVMRP-STD-MIB', 'dvmrpNeighborRcvBadPkts'), ('DVMRP-STD-MIB', 'dvmrpNeighborRcvBadRoutes'), ('DVMRP-STD-MIB', 'dvmrpNeighborState'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_neighbor_group = dvmrpNeighborGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNeighborGroup.setDescription('A collection of objects used to describe DVMRP peer configuration and statistics.')
dvmrp_routing_group = object_group((1, 3, 6, 1, 3, 62, 2, 2, 5)).setObjects(('DVMRP-STD-MIB', 'dvmrpRouteUpstreamNeighbor'), ('DVMRP-STD-MIB', 'dvmrpRouteIfIndex'), ('DVMRP-STD-MIB', 'dvmrpRouteMetric'), ('DVMRP-STD-MIB', 'dvmrpRouteExpiryTime'), ('DVMRP-STD-MIB', 'dvmrpRouteUpTime'), ('DVMRP-STD-MIB', 'dvmrpRouteNextHopType'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_routing_group = dvmrpRoutingGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpRoutingGroup.setDescription('A collection of objects used to store the DVMRP routing table.')
dvmrp_security_group = object_group((1, 3, 6, 1, 3, 62, 2, 2, 6)).setObjects(('DVMRP-STD-MIB', 'dvmrpInterfaceKey'), ('DVMRP-STD-MIB', 'dvmrpInterfaceKeyVersion'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_security_group = dvmrpSecurityGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpSecurityGroup.setDescription('A collection of objects used to store information related to DVMRP security.')
dvmrp_tree_group = object_group((1, 3, 6, 1, 3, 62, 2, 2, 7)).setObjects(('DVMRP-STD-MIB', 'dvmrpPruneExpiryTime'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_tree_group = dvmrpTreeGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpTreeGroup.setDescription('A collection of objects used to store information related to DVMRP prune state.')
dvmrp_notification_group = notification_group((1, 3, 6, 1, 3, 62, 2, 2, 8)).setObjects(('DVMRP-STD-MIB', 'dvmrpNeighborLoss'), ('DVMRP-STD-MIB', 'dvmrpNeighborNotPruning'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
dvmrp_notification_group = dvmrpNotificationGroup.setStatus('current')
if mibBuilder.loadTexts:
dvmrpNotificationGroup.setDescription('A collection of notifications for signaling important DVMRP events.')
mibBuilder.exportSymbols('DVMRP-STD-MIB', dvmrpStdMIB=dvmrpStdMIB, dvmrpRouteUpstreamNeighbor=dvmrpRouteUpstreamNeighbor, dvmrpInterfaceLocalAddress=dvmrpInterfaceLocalAddress, dvmrpGeneralGroup=dvmrpGeneralGroup, dvmrpRouteNextHopEntry=dvmrpRouteNextHopEntry, dvmrpNumRoutes=dvmrpNumRoutes, dvmrpRouteNextHopSourceMask=dvmrpRouteNextHopSourceMask, dvmrpRouteNextHopSource=dvmrpRouteNextHopSource, dvmrpNeighborMinorVersion=dvmrpNeighborMinorVersion, dvmrpRouteIfIndex=dvmrpRouteIfIndex, dvmrpNeighborRcvRoutes=dvmrpNeighborRcvRoutes, dvmrpRouteMetric=dvmrpRouteMetric, dvmrpScalar=dvmrpScalar, dvmrpNeighborGenerationId=dvmrpNeighborGenerationId, dvmrpPruneTable=dvmrpPruneTable, dvmrpPruneGroup=dvmrpPruneGroup, dvmrpPruneSourceMask=dvmrpPruneSourceMask, dvmrp=dvmrp, dvmrpNeighborCapabilities=dvmrpNeighborCapabilities, dvmrpMIBConformance=dvmrpMIBConformance, dvmrpInterfaceMetric=dvmrpInterfaceMetric, dvmrpInterfaceKey=dvmrpInterfaceKey, dvmrpNeighborAddress=dvmrpNeighborAddress, dvmrpReachableRoutes=dvmrpReachableRoutes, dvmrpRouteTable=dvmrpRouteTable, dvmrpRouteSource=dvmrpRouteSource, dvmrpRouteSourceMask=dvmrpRouteSourceMask, dvmrpNeighborState=dvmrpNeighborState, dvmrpNeighborGroup=dvmrpNeighborGroup, dvmrpRoutingGroup=dvmrpRoutingGroup, dvmrpPruneSource=dvmrpPruneSource, dvmrpTraps=dvmrpTraps, dvmrpNeighborRcvBadPkts=dvmrpNeighborRcvBadPkts, dvmrpInterfaceRcvBadPkts=dvmrpInterfaceRcvBadPkts, dvmrpNeighborTable=dvmrpNeighborTable, dvmrpNeighborLoss=dvmrpNeighborLoss, dvmrpNeighborNotPruning=dvmrpNeighborNotPruning, dvmrpInterfaceTable=dvmrpInterfaceTable, dvmrpMIBGroups=dvmrpMIBGroups, dvmrpInterfaceGroup=dvmrpInterfaceGroup, PYSNMP_MODULE_ID=dvmrpStdMIB, dvmrpNeighborMajorVersion=dvmrpNeighborMajorVersion, dvmrpVersionString=dvmrpVersionString, dvmrpRouteNextHopType=dvmrpRouteNextHopType, dvmrpInterfaceEntry=dvmrpInterfaceEntry, dvmrpPruneEntry=dvmrpPruneEntry, dvmrpInterfaceKeyVersion=dvmrpInterfaceKeyVersion, dvmrpNeighborRcvBadRoutes=dvmrpNeighborRcvBadRoutes, dvmrpInterfaceIndex=dvmrpInterfaceIndex, dvmrpNeighborUpTime=dvmrpNeighborUpTime, dvmrpNeighborEntry=dvmrpNeighborEntry, dvmrpRouteExpiryTime=dvmrpRouteExpiryTime, dvmrpMIBObjects=dvmrpMIBObjects, dvmrpNeighborIfIndex=dvmrpNeighborIfIndex, dvmrpInterfaceStatus=dvmrpInterfaceStatus, dvmrpTreeGroup=dvmrpTreeGroup, dvmrpInterfaceSentRoutes=dvmrpInterfaceSentRoutes, dvmrpNeighborExpiryTime=dvmrpNeighborExpiryTime, dvmrpInterfaceRcvBadRoutes=dvmrpInterfaceRcvBadRoutes, dvmrpMIBCompliances=dvmrpMIBCompliances, dvmrpRouteNextHopIfIndex=dvmrpRouteNextHopIfIndex, dvmrpSecurityGroup=dvmrpSecurityGroup, dvmrpRouteEntry=dvmrpRouteEntry, dvmrpRouteUpTime=dvmrpRouteUpTime, dvmrpRouteNextHopTable=dvmrpRouteNextHopTable, dvmrpPruneExpiryTime=dvmrpPruneExpiryTime, dvmrpNotificationGroup=dvmrpNotificationGroup, dvmrpMIBCompliance=dvmrpMIBCompliance, dvmrpInterfaceGenerationId=dvmrpInterfaceGenerationId) |
class Solution(object):
def combinationSum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
def combinationSumRecu(self, candidates, result, start, intermediate, target):
if target == 0:
result.append(list(intermediate))
prev = 0
while start < len(candidates) and candidates[start] <= target:
if prev != candidates[start]:
intermediate.append(candidates[start])
self.combinationSumRecu(candidates, result, start + 1, intermediate, target - candidates[start])
intermediate.pop()
prev = candidates[start]
start += 1
candidates = [10,1,2,7,6,1,5]
target = 8
res = Solution().combinationSum2(candidates, target)
print(res) | class Solution(object):
def combination_sum2(self, candidates, target):
result = []
self.combinationSumRecu(sorted(candidates), result, 0, [], target)
return result
def combination_sum_recu(self, candidates, result, start, intermediate, target):
if target == 0:
result.append(list(intermediate))
prev = 0
while start < len(candidates) and candidates[start] <= target:
if prev != candidates[start]:
intermediate.append(candidates[start])
self.combinationSumRecu(candidates, result, start + 1, intermediate, target - candidates[start])
intermediate.pop()
prev = candidates[start]
start += 1
candidates = [10, 1, 2, 7, 6, 1, 5]
target = 8
res = solution().combinationSum2(candidates, target)
print(res) |
"""This file provides the PEP0249 compliant variables for this module.
See https://www.python.org/dev/peps/pep-0249 for more information on these.
"""
# Copyright 2012, Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can
# be found in the LICENSE file.
# Follows the Python Database API 2.0.
apilevel = '2.0'
# Threads may share the module, but not connections.
# (we store session information in the conection now, that should be in the
# cursor but are not for historical reasons).
threadsafety = 2
# Named style, e.g. ...WHERE name=:name.
#
# Note we also provide a function in dbapi to convert from 'pyformat'
# to 'named', and prune unused bind variables in the SQL query.
#
# Also, we use an extension to bind variables to handle lists:
# Using the '::name' syntax (instead of ':name') will indicate a list bind
# variable. The type then has to be a list, set or tuple.
paramstyle = 'named'
| """This file provides the PEP0249 compliant variables for this module.
See https://www.python.org/dev/peps/pep-0249 for more information on these.
"""
apilevel = '2.0'
threadsafety = 2
paramstyle = 'named' |
_EVT_INIT = 'INITIALIZE'
EVT_START = 'START'
EVT_READY = 'READY'
EVT_CLOSE = 'CLOSE'
EVT_STOP = 'STOP'
EVT_APP_LOAD = 'APP_LOAD'
EVT_APP_UNLOAD = 'APP_UNLOAD'
EVT_INTENT_SUBSCRIBE = 'INTENT_SUBSCRIBE'
EVT_INTENT_START = 'INTENT_START'
EVT_INTENT_END = 'INTENT_END'
EVT_ANY = '*'
_META_EVENTS = (
_EVT_INIT, EVT_APP_LOAD, EVT_APP_UNLOAD,
EVT_INTENT_SUBSCRIBE, EVT_INTENT_START, EVT_INTENT_END
)
| _evt_init = 'INITIALIZE'
evt_start = 'START'
evt_ready = 'READY'
evt_close = 'CLOSE'
evt_stop = 'STOP'
evt_app_load = 'APP_LOAD'
evt_app_unload = 'APP_UNLOAD'
evt_intent_subscribe = 'INTENT_SUBSCRIBE'
evt_intent_start = 'INTENT_START'
evt_intent_end = 'INTENT_END'
evt_any = '*'
_meta_events = (_EVT_INIT, EVT_APP_LOAD, EVT_APP_UNLOAD, EVT_INTENT_SUBSCRIBE, EVT_INTENT_START, EVT_INTENT_END) |
#
# PySNMP MIB module ADTRAN-AOS-DESKTOP-AUDITING (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-DESKTOP-AUDITING
# Produced by pysmi-0.3.4 at Wed May 1 11:13:58 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)
#
adGenAOSConformance, adGenAOSSwitch = mibBuilder.importSymbols("ADTRAN-AOS", "adGenAOSConformance", "adGenAOSSwitch")
adIdentity, = mibBuilder.importSymbols("ADTRAN-MIB", "adIdentity")
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion")
ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
Counter32, NotificationType, ObjectIdentity, Gauge32, iso, Counter64, Integer32, Bits, MibIdentifier, ModuleIdentity, TimeTicks, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "NotificationType", "ObjectIdentity", "Gauge32", "iso", "Counter64", "Integer32", "Bits", "MibIdentifier", "ModuleIdentity", "TimeTicks", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress")
DateAndTime, TimeStamp, TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DateAndTime", "TimeStamp", "TruthValue", "DisplayString", "TextualConvention")
adGenAOSDesktopAuditingMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 664, 6, 10000, 53, 4, 1))
if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setLastUpdated('200912140000Z')
if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setOrganization('ADTRAN, Inc.')
if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setContactInfo('Technical Support Dept. Postal: ADTRAN, Inc. 901 Explorer Blvd. Huntsville, AL 35806 Tel: +1 800 726-8663 Fax: +1 256 963 6217 E-mail: support@adtran.com')
if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setDescription('First Draft of ADTRAN-AOS-DESKTOP-AUDITING MIB module.')
adGenDesktopAuditing = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2))
adGenNapClients = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0))
adGenNapClientsTable = MibTable((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1), )
if mibBuilder.loadTexts: adGenNapClientsTable.setStatus('current')
if mibBuilder.loadTexts: adGenNapClientsTable.setDescription('The NAP client table displays NAP information of NAP capable clients. It displays information such as clients firewall, antivirus, antispyware, and security states. ')
adGenNapClientsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1), ).setIndexNames((0, "ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientMac"), (0, "ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientVlanId"))
if mibBuilder.loadTexts: adGenNapClientsEntry.setStatus('current')
if mibBuilder.loadTexts: adGenNapClientsEntry.setDescription('NAP information of the client')
adNapClientMac = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 1), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientMac.setStatus('current')
if mibBuilder.loadTexts: adNapClientMac.setDescription('NAP clients MAC address. This is unique to the Desktop Auditing MIB.')
adNapClientVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 2), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientVlanId.setStatus('current')
if mibBuilder.loadTexts: adNapClientVlanId.setDescription('NAP clients VLAN ID. This ID is unique to the Desktop Auditing MIB.')
adNapClientIp = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientIp.setStatus('current')
if mibBuilder.loadTexts: adNapClientIp.setDescription('NAP clients IP address.')
adNapClientHostname = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 4), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientHostname.setStatus('current')
if mibBuilder.loadTexts: adNapClientHostname.setDescription('NAP clients hostname.')
adNapClientSrcPortIfId = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientSrcPortIfId.setStatus('current')
if mibBuilder.loadTexts: adNapClientSrcPortIfId.setDescription('NAP clients source port interface ID.')
adNapClientSrcPortIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientSrcPortIfType.setStatus('current')
if mibBuilder.loadTexts: adNapClientSrcPortIfType.setDescription('NAP clients source port interface type.')
adNapServerMac = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapServerMac.setStatus('current')
if mibBuilder.loadTexts: adNapServerMac.setDescription('NAP servers MAC address.')
adNapServerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 8), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapServerIp.setStatus('current')
if mibBuilder.loadTexts: adNapServerIp.setDescription('NAP servers IP address.')
adNapCollectionMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 9), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapCollectionMethod.setStatus('current')
if mibBuilder.loadTexts: adNapCollectionMethod.setDescription('Method by which the NAP information is collected.')
adNapCollectionTime = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 10), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapCollectionTime.setStatus('current')
if mibBuilder.loadTexts: adNapCollectionTime.setDescription('Time when the NAP information was collected.')
adNapCapableClient = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 11), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapCapableClient.setStatus('current')
if mibBuilder.loadTexts: adNapCapableClient.setDescription('Client is NAP capable.')
adNapCapableServer = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 12), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapCapableServer.setStatus('current')
if mibBuilder.loadTexts: adNapCapableServer.setDescription('Server is NAP capable.')
adNapClientOsVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 13), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientOsVersion.setStatus('current')
if mibBuilder.loadTexts: adNapClientOsVersion.setDescription('NAP clients OS version.')
adNapClientOsServicePk = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 14), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientOsServicePk.setStatus('current')
if mibBuilder.loadTexts: adNapClientOsServicePk.setDescription('NAP clients service pack.')
adNapClientOsProcessorArc = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 15), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientOsProcessorArc.setStatus('current')
if mibBuilder.loadTexts: adNapClientOsProcessorArc.setDescription('NAP clients processor architecture.')
adNapClientLastSecurityUpdate = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 16), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientLastSecurityUpdate.setStatus('current')
if mibBuilder.loadTexts: adNapClientLastSecurityUpdate.setDescription('Last time the NAP clients security was updated.')
adNapClientSecurityUpdateServer = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 17), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientSecurityUpdateServer.setStatus('current')
if mibBuilder.loadTexts: adNapClientSecurityUpdateServer.setDescription('NAP clients security update server.')
adNapClientRequiresRemediation = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unknown", 1), ("true", 2), ("false", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientRequiresRemediation.setStatus('current')
if mibBuilder.loadTexts: adNapClientRequiresRemediation.setDescription('NAP clients requires remediation.')
adNapClientLocalPolicyViolator = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 19), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientLocalPolicyViolator.setStatus('current')
if mibBuilder.loadTexts: adNapClientLocalPolicyViolator.setDescription('NAP clients violates local policies.')
adNapClientFirewallState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEnaNotUTD", 5), ("micsftNotEnaNotUTD", 6), ("notEnaUTD", 7), ("micsftNotEnaUTD", 8), ("enaNotUTDSn", 9), ("micsftEnaNotUTDSn", 10), ("enaNotUTDNotSn", 11), ("micsftEnaNotUTDNotSn", 12), ("enaUTDSn", 13), ("micsftEnaUTDSn", 14), ("enaUTDNotSn", 15), ("micsftEnaUTDNotSn", 16)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientFirewallState.setStatus('current')
if mibBuilder.loadTexts: adNapClientFirewallState.setDescription('NAP clients firewall state.')
adNapClientFirewall = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 21), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientFirewall.setStatus('current')
if mibBuilder.loadTexts: adNapClientFirewall.setDescription('NAP clients firewall.')
adNapClientAntivirusState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEnaNotUTD", 5), ("micsftNotEnaNotUTD", 6), ("notEnaUTD", 7), ("micsftNotEnaUTD", 8), ("enaNotUTDSn", 9), ("micsftEnaNotUTDSn", 10), ("enaNotUTDNotSn", 11), ("micsftEnaNotUTDNotSn", 12), ("enaUTDSn", 13), ("micsftEnaUTDSn", 14), ("enaUTDNotSn", 15), ("micsftEnaUTDNotSn", 16)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientAntivirusState.setStatus('current')
if mibBuilder.loadTexts: adNapClientAntivirusState.setDescription('NAP clients antivirus state.')
adNapClientAntivirus = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 23), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientAntivirus.setStatus('current')
if mibBuilder.loadTexts: adNapClientAntivirus.setDescription('NAP clients antivirus.')
adNapClientAntispywareState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEnaNotUTD", 5), ("micsftNotEnaNotUTD", 6), ("notEnaUTD", 7), ("micsftNotEnaUTD", 8), ("enaNotUTDSn", 9), ("micsftEnaNotUTDSn", 10), ("enaNotUTDNotSn", 11), ("micsftEnaNotUTDNotSn", 12), ("enaUTDSn", 13), ("micsftEnaUTDSn", 14), ("enaUTDNotSn", 15), ("micsftEnaUTDNotSn", 16)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientAntispywareState.setStatus('current')
if mibBuilder.loadTexts: adNapClientAntispywareState.setDescription('NAP clients antispyware state.')
adNapClientAntispyware = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 25), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientAntispyware.setStatus('current')
if mibBuilder.loadTexts: adNapClientAntispyware.setDescription('NAP clients antispyware.')
adNapClientAutoupdateState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEna", 5), ("enaCkUpdateOnly", 6), ("enaDownload", 7), ("enaDownloadInstall", 8), ("neverConfigured", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientAutoupdateState.setStatus('current')
if mibBuilder.loadTexts: adNapClientAutoupdateState.setDescription('NAP clients auto update state.')
adNapClientSecurityupdateState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("unknown", 1), ("noMissingUpdate", 2), ("missingUpdate", 3), ("noWUS", 4), ("noClientID", 5), ("wuaServiceDisabled", 6), ("wuaCommFailed", 7), ("updateInsNeedReboot", 8), ("wuaNotStarted", 9)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientSecurityupdateState.setStatus('current')
if mibBuilder.loadTexts: adNapClientSecurityupdateState.setDescription('NAP clients security update state.')
adNapClientSecuritySeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("unknown", 1), ("unspecified", 2), ("low", 3), ("moderate", 4), ("important", 5), ("critical", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientSecuritySeverity.setStatus('current')
if mibBuilder.loadTexts: adNapClientSecuritySeverity.setDescription('NAP clients security update severity.')
adNapClientConnectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("unknown", 1), ("notRestricted", 2), ("notResMaybeLater", 3), ("restricted", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: adNapClientConnectionState.setStatus('current')
if mibBuilder.loadTexts: adNapClientConnectionState.setDescription('NAP clients network connection state.')
adGenAOSDesktopAuditingConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10))
adGenAOSDesktopAuditingGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 1))
adGenAOSDesktopAuditingCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 2))
adGenAOSDesktopAuditingFullCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 2, 1)).setObjects(("ADTRAN-AOS-DESKTOP-AUDITING", "adGenNapClientsGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
adGenAOSDesktopAuditingFullCompliance = adGenAOSDesktopAuditingFullCompliance.setStatus('current')
if mibBuilder.loadTexts: adGenAOSDesktopAuditingFullCompliance.setDescription('The compliance statement for SNMP entities which implement version 1 of the adGenAosDesktopAuditing MIB. When this MIB is implemented with support for read-only, then such an implementation can claim full compliance. ')
adGenNapClientsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 1, 1)).setObjects(("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientMac"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientVlanId"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientIp"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientHostname"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSrcPortIfId"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSrcPortIfType"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapServerMac"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapServerIp"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCollectionMethod"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCollectionTime"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCapableClient"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCapableServer"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientOsVersion"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientOsServicePk"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientOsProcessorArc"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientLastSecurityUpdate"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSecurityUpdateServer"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientRequiresRemediation"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientLocalPolicyViolator"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientFirewallState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientFirewall"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntivirusState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntivirus"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntispywareState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntispyware"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAutoupdateState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSecurityupdateState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSecuritySeverity"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientConnectionState"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
adGenNapClientsGroup = adGenNapClientsGroup.setStatus('current')
if mibBuilder.loadTexts: adGenNapClientsGroup.setDescription('The adGenNapClientGroup group contains read-only NAP information of clients in the network that are NAP capable.')
mibBuilder.exportSymbols("ADTRAN-AOS-DESKTOP-AUDITING", adNapClientSecurityupdateState=adNapClientSecurityupdateState, adNapClientFirewall=adNapClientFirewall, PYSNMP_MODULE_ID=adGenAOSDesktopAuditingMib, adGenNapClientsTable=adGenNapClientsTable, adGenAOSDesktopAuditingGroups=adGenAOSDesktopAuditingGroups, adNapServerMac=adNapServerMac, adNapServerIp=adNapServerIp, adNapClientMac=adNapClientMac, adNapCollectionMethod=adNapCollectionMethod, adNapClientIp=adNapClientIp, adNapClientSecurityUpdateServer=adNapClientSecurityUpdateServer, adNapClientVlanId=adNapClientVlanId, adNapClientConnectionState=adNapClientConnectionState, adGenAOSDesktopAuditingConformance=adGenAOSDesktopAuditingConformance, adNapClientAntispywareState=adNapClientAntispywareState, adGenAOSDesktopAuditingCompliances=adGenAOSDesktopAuditingCompliances, adGenDesktopAuditing=adGenDesktopAuditing, adNapCollectionTime=adNapCollectionTime, adNapClientOsProcessorArc=adNapClientOsProcessorArc, adGenAOSDesktopAuditingFullCompliance=adGenAOSDesktopAuditingFullCompliance, adNapClientRequiresRemediation=adNapClientRequiresRemediation, adNapClientAutoupdateState=adNapClientAutoupdateState, adNapClientAntivirusState=adNapClientAntivirusState, adNapClientFirewallState=adNapClientFirewallState, adNapClientOsServicePk=adNapClientOsServicePk, adNapClientLocalPolicyViolator=adNapClientLocalPolicyViolator, adNapClientAntivirus=adNapClientAntivirus, adNapClientSrcPortIfType=adNapClientSrcPortIfType, adGenNapClientsEntry=adGenNapClientsEntry, adNapClientSecuritySeverity=adNapClientSecuritySeverity, adNapClientOsVersion=adNapClientOsVersion, adNapCapableServer=adNapCapableServer, adNapCapableClient=adNapCapableClient, adNapClientHostname=adNapClientHostname, adGenNapClients=adGenNapClients, adNapClientAntispyware=adNapClientAntispyware, adGenNapClientsGroup=adGenNapClientsGroup, adGenAOSDesktopAuditingMib=adGenAOSDesktopAuditingMib, adNapClientLastSecurityUpdate=adNapClientLastSecurityUpdate, adNapClientSrcPortIfId=adNapClientSrcPortIfId)
| (ad_gen_aos_conformance, ad_gen_aos_switch) = mibBuilder.importSymbols('ADTRAN-AOS', 'adGenAOSConformance', 'adGenAOSSwitch')
(ad_identity,) = mibBuilder.importSymbols('ADTRAN-MIB', 'adIdentity')
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, value_size_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion')
(object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance')
(counter32, notification_type, object_identity, gauge32, iso, counter64, integer32, bits, mib_identifier, module_identity, time_ticks, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'NotificationType', 'ObjectIdentity', 'Gauge32', 'iso', 'Counter64', 'Integer32', 'Bits', 'MibIdentifier', 'ModuleIdentity', 'TimeTicks', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress')
(date_and_time, time_stamp, truth_value, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DateAndTime', 'TimeStamp', 'TruthValue', 'DisplayString', 'TextualConvention')
ad_gen_aos_desktop_auditing_mib = module_identity((1, 3, 6, 1, 4, 1, 664, 6, 10000, 53, 4, 1))
if mibBuilder.loadTexts:
adGenAOSDesktopAuditingMib.setLastUpdated('200912140000Z')
if mibBuilder.loadTexts:
adGenAOSDesktopAuditingMib.setOrganization('ADTRAN, Inc.')
if mibBuilder.loadTexts:
adGenAOSDesktopAuditingMib.setContactInfo('Technical Support Dept. Postal: ADTRAN, Inc. 901 Explorer Blvd. Huntsville, AL 35806 Tel: +1 800 726-8663 Fax: +1 256 963 6217 E-mail: support@adtran.com')
if mibBuilder.loadTexts:
adGenAOSDesktopAuditingMib.setDescription('First Draft of ADTRAN-AOS-DESKTOP-AUDITING MIB module.')
ad_gen_desktop_auditing = mib_identifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2))
ad_gen_nap_clients = mib_identifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0))
ad_gen_nap_clients_table = mib_table((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1))
if mibBuilder.loadTexts:
adGenNapClientsTable.setStatus('current')
if mibBuilder.loadTexts:
adGenNapClientsTable.setDescription('The NAP client table displays NAP information of NAP capable clients. It displays information such as clients firewall, antivirus, antispyware, and security states. ')
ad_gen_nap_clients_entry = mib_table_row((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1)).setIndexNames((0, 'ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientMac'), (0, 'ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientVlanId'))
if mibBuilder.loadTexts:
adGenNapClientsEntry.setStatus('current')
if mibBuilder.loadTexts:
adGenNapClientsEntry.setDescription('NAP information of the client')
ad_nap_client_mac = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 1), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientMac.setStatus('current')
if mibBuilder.loadTexts:
adNapClientMac.setDescription('NAP clients MAC address. This is unique to the Desktop Auditing MIB.')
ad_nap_client_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 2), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientVlanId.setStatus('current')
if mibBuilder.loadTexts:
adNapClientVlanId.setDescription('NAP clients VLAN ID. This ID is unique to the Desktop Auditing MIB.')
ad_nap_client_ip = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientIp.setStatus('current')
if mibBuilder.loadTexts:
adNapClientIp.setDescription('NAP clients IP address.')
ad_nap_client_hostname = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 4), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientHostname.setStatus('current')
if mibBuilder.loadTexts:
adNapClientHostname.setDescription('NAP clients hostname.')
ad_nap_client_src_port_if_id = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 5), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientSrcPortIfId.setStatus('current')
if mibBuilder.loadTexts:
adNapClientSrcPortIfId.setDescription('NAP clients source port interface ID.')
ad_nap_client_src_port_if_type = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 6), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientSrcPortIfType.setStatus('current')
if mibBuilder.loadTexts:
adNapClientSrcPortIfType.setDescription('NAP clients source port interface type.')
ad_nap_server_mac = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 7), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapServerMac.setStatus('current')
if mibBuilder.loadTexts:
adNapServerMac.setDescription('NAP servers MAC address.')
ad_nap_server_ip = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 8), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapServerIp.setStatus('current')
if mibBuilder.loadTexts:
adNapServerIp.setDescription('NAP servers IP address.')
ad_nap_collection_method = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 9), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapCollectionMethod.setStatus('current')
if mibBuilder.loadTexts:
adNapCollectionMethod.setDescription('Method by which the NAP information is collected.')
ad_nap_collection_time = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 10), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapCollectionTime.setStatus('current')
if mibBuilder.loadTexts:
adNapCollectionTime.setDescription('Time when the NAP information was collected.')
ad_nap_capable_client = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 11), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapCapableClient.setStatus('current')
if mibBuilder.loadTexts:
adNapCapableClient.setDescription('Client is NAP capable.')
ad_nap_capable_server = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 12), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapCapableServer.setStatus('current')
if mibBuilder.loadTexts:
adNapCapableServer.setDescription('Server is NAP capable.')
ad_nap_client_os_version = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 13), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientOsVersion.setStatus('current')
if mibBuilder.loadTexts:
adNapClientOsVersion.setDescription('NAP clients OS version.')
ad_nap_client_os_service_pk = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 14), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientOsServicePk.setStatus('current')
if mibBuilder.loadTexts:
adNapClientOsServicePk.setDescription('NAP clients service pack.')
ad_nap_client_os_processor_arc = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 15), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientOsProcessorArc.setStatus('current')
if mibBuilder.loadTexts:
adNapClientOsProcessorArc.setDescription('NAP clients processor architecture.')
ad_nap_client_last_security_update = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 16), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientLastSecurityUpdate.setStatus('current')
if mibBuilder.loadTexts:
adNapClientLastSecurityUpdate.setDescription('Last time the NAP clients security was updated.')
ad_nap_client_security_update_server = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 17), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientSecurityUpdateServer.setStatus('current')
if mibBuilder.loadTexts:
adNapClientSecurityUpdateServer.setDescription('NAP clients security update server.')
ad_nap_client_requires_remediation = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 18), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('unknown', 1), ('true', 2), ('false', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientRequiresRemediation.setStatus('current')
if mibBuilder.loadTexts:
adNapClientRequiresRemediation.setDescription('NAP clients requires remediation.')
ad_nap_client_local_policy_violator = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 19), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientLocalPolicyViolator.setStatus('current')
if mibBuilder.loadTexts:
adNapClientLocalPolicyViolator.setDescription('NAP clients violates local policies.')
ad_nap_client_firewall_state = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=named_values(('unknown', 1), ('notInstalled', 2), ('wscServiceDown', 3), ('wscNotStarted', 4), ('notEnaNotUTD', 5), ('micsftNotEnaNotUTD', 6), ('notEnaUTD', 7), ('micsftNotEnaUTD', 8), ('enaNotUTDSn', 9), ('micsftEnaNotUTDSn', 10), ('enaNotUTDNotSn', 11), ('micsftEnaNotUTDNotSn', 12), ('enaUTDSn', 13), ('micsftEnaUTDSn', 14), ('enaUTDNotSn', 15), ('micsftEnaUTDNotSn', 16)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientFirewallState.setStatus('current')
if mibBuilder.loadTexts:
adNapClientFirewallState.setDescription('NAP clients firewall state.')
ad_nap_client_firewall = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 21), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientFirewall.setStatus('current')
if mibBuilder.loadTexts:
adNapClientFirewall.setDescription('NAP clients firewall.')
ad_nap_client_antivirus_state = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 22), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=named_values(('unknown', 1), ('notInstalled', 2), ('wscServiceDown', 3), ('wscNotStarted', 4), ('notEnaNotUTD', 5), ('micsftNotEnaNotUTD', 6), ('notEnaUTD', 7), ('micsftNotEnaUTD', 8), ('enaNotUTDSn', 9), ('micsftEnaNotUTDSn', 10), ('enaNotUTDNotSn', 11), ('micsftEnaNotUTDNotSn', 12), ('enaUTDSn', 13), ('micsftEnaUTDSn', 14), ('enaUTDNotSn', 15), ('micsftEnaUTDNotSn', 16)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientAntivirusState.setStatus('current')
if mibBuilder.loadTexts:
adNapClientAntivirusState.setDescription('NAP clients antivirus state.')
ad_nap_client_antivirus = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 23), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientAntivirus.setStatus('current')
if mibBuilder.loadTexts:
adNapClientAntivirus.setDescription('NAP clients antivirus.')
ad_nap_client_antispyware_state = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 24), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=named_values(('unknown', 1), ('notInstalled', 2), ('wscServiceDown', 3), ('wscNotStarted', 4), ('notEnaNotUTD', 5), ('micsftNotEnaNotUTD', 6), ('notEnaUTD', 7), ('micsftNotEnaUTD', 8), ('enaNotUTDSn', 9), ('micsftEnaNotUTDSn', 10), ('enaNotUTDNotSn', 11), ('micsftEnaNotUTDNotSn', 12), ('enaUTDSn', 13), ('micsftEnaUTDSn', 14), ('enaUTDNotSn', 15), ('micsftEnaUTDNotSn', 16)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientAntispywareState.setStatus('current')
if mibBuilder.loadTexts:
adNapClientAntispywareState.setDescription('NAP clients antispyware state.')
ad_nap_client_antispyware = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 25), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientAntispyware.setStatus('current')
if mibBuilder.loadTexts:
adNapClientAntispyware.setDescription('NAP clients antispyware.')
ad_nap_client_autoupdate_state = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 26), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=named_values(('unknown', 1), ('notInstalled', 2), ('wscServiceDown', 3), ('wscNotStarted', 4), ('notEna', 5), ('enaCkUpdateOnly', 6), ('enaDownload', 7), ('enaDownloadInstall', 8), ('neverConfigured', 9)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientAutoupdateState.setStatus('current')
if mibBuilder.loadTexts:
adNapClientAutoupdateState.setDescription('NAP clients auto update state.')
ad_nap_client_securityupdate_state = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 27), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=named_values(('unknown', 1), ('noMissingUpdate', 2), ('missingUpdate', 3), ('noWUS', 4), ('noClientID', 5), ('wuaServiceDisabled', 6), ('wuaCommFailed', 7), ('updateInsNeedReboot', 8), ('wuaNotStarted', 9)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientSecurityupdateState.setStatus('current')
if mibBuilder.loadTexts:
adNapClientSecurityupdateState.setDescription('NAP clients security update state.')
ad_nap_client_security_severity = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 28), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('unknown', 1), ('unspecified', 2), ('low', 3), ('moderate', 4), ('important', 5), ('critical', 6)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientSecuritySeverity.setStatus('current')
if mibBuilder.loadTexts:
adNapClientSecuritySeverity.setDescription('NAP clients security update severity.')
ad_nap_client_connection_state = mib_table_column((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 29), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('unknown', 1), ('notRestricted', 2), ('notResMaybeLater', 3), ('restricted', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
adNapClientConnectionState.setStatus('current')
if mibBuilder.loadTexts:
adNapClientConnectionState.setDescription('NAP clients network connection state.')
ad_gen_aos_desktop_auditing_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10))
ad_gen_aos_desktop_auditing_groups = mib_identifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 1))
ad_gen_aos_desktop_auditing_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 2))
ad_gen_aos_desktop_auditing_full_compliance = module_compliance((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 2, 1)).setObjects(('ADTRAN-AOS-DESKTOP-AUDITING', 'adGenNapClientsGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ad_gen_aos_desktop_auditing_full_compliance = adGenAOSDesktopAuditingFullCompliance.setStatus('current')
if mibBuilder.loadTexts:
adGenAOSDesktopAuditingFullCompliance.setDescription('The compliance statement for SNMP entities which implement version 1 of the adGenAosDesktopAuditing MIB. When this MIB is implemented with support for read-only, then such an implementation can claim full compliance. ')
ad_gen_nap_clients_group = object_group((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 1, 1)).setObjects(('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientMac'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientVlanId'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientIp'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientHostname'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientSrcPortIfId'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientSrcPortIfType'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapServerMac'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapServerIp'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapCollectionMethod'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapCollectionTime'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapCapableClient'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapCapableServer'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientOsVersion'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientOsServicePk'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientOsProcessorArc'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientLastSecurityUpdate'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientSecurityUpdateServer'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientRequiresRemediation'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientLocalPolicyViolator'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientFirewallState'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientFirewall'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientAntivirusState'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientAntivirus'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientAntispywareState'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientAntispyware'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientAutoupdateState'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientSecurityupdateState'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientSecuritySeverity'), ('ADTRAN-AOS-DESKTOP-AUDITING', 'adNapClientConnectionState'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ad_gen_nap_clients_group = adGenNapClientsGroup.setStatus('current')
if mibBuilder.loadTexts:
adGenNapClientsGroup.setDescription('The adGenNapClientGroup group contains read-only NAP information of clients in the network that are NAP capable.')
mibBuilder.exportSymbols('ADTRAN-AOS-DESKTOP-AUDITING', adNapClientSecurityupdateState=adNapClientSecurityupdateState, adNapClientFirewall=adNapClientFirewall, PYSNMP_MODULE_ID=adGenAOSDesktopAuditingMib, adGenNapClientsTable=adGenNapClientsTable, adGenAOSDesktopAuditingGroups=adGenAOSDesktopAuditingGroups, adNapServerMac=adNapServerMac, adNapServerIp=adNapServerIp, adNapClientMac=adNapClientMac, adNapCollectionMethod=adNapCollectionMethod, adNapClientIp=adNapClientIp, adNapClientSecurityUpdateServer=adNapClientSecurityUpdateServer, adNapClientVlanId=adNapClientVlanId, adNapClientConnectionState=adNapClientConnectionState, adGenAOSDesktopAuditingConformance=adGenAOSDesktopAuditingConformance, adNapClientAntispywareState=adNapClientAntispywareState, adGenAOSDesktopAuditingCompliances=adGenAOSDesktopAuditingCompliances, adGenDesktopAuditing=adGenDesktopAuditing, adNapCollectionTime=adNapCollectionTime, adNapClientOsProcessorArc=adNapClientOsProcessorArc, adGenAOSDesktopAuditingFullCompliance=adGenAOSDesktopAuditingFullCompliance, adNapClientRequiresRemediation=adNapClientRequiresRemediation, adNapClientAutoupdateState=adNapClientAutoupdateState, adNapClientAntivirusState=adNapClientAntivirusState, adNapClientFirewallState=adNapClientFirewallState, adNapClientOsServicePk=adNapClientOsServicePk, adNapClientLocalPolicyViolator=adNapClientLocalPolicyViolator, adNapClientAntivirus=adNapClientAntivirus, adNapClientSrcPortIfType=adNapClientSrcPortIfType, adGenNapClientsEntry=adGenNapClientsEntry, adNapClientSecuritySeverity=adNapClientSecuritySeverity, adNapClientOsVersion=adNapClientOsVersion, adNapCapableServer=adNapCapableServer, adNapCapableClient=adNapCapableClient, adNapClientHostname=adNapClientHostname, adGenNapClients=adGenNapClients, adNapClientAntispyware=adNapClientAntispyware, adGenNapClientsGroup=adGenNapClientsGroup, adGenAOSDesktopAuditingMib=adGenAOSDesktopAuditingMib, adNapClientLastSecurityUpdate=adNapClientLastSecurityUpdate, adNapClientSrcPortIfId=adNapClientSrcPortIfId) |
try:
raise ValueError("invalid!")
except ValueError as error:
print(str(error) + " input")
finally:
print("Finishd")
| try:
raise value_error('invalid!')
except ValueError as error:
print(str(error) + ' input')
finally:
print('Finishd') |
if __name__ == "__main__":
a = [1,2,3]
i = -1
print(a[-1])
for i in range(-1,-4,-1):
print(a[i]) | if __name__ == '__main__':
a = [1, 2, 3]
i = -1
print(a[-1])
for i in range(-1, -4, -1):
print(a[i]) |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Presubmit script for build/chromeos/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into depot_tools.
"""
def CommonChecks(input_api, output_api):
results = []
results += input_api.canned_checks.RunPylint(
input_api, output_api, pylintrc='pylintrc')
tests = input_api.canned_checks.GetUnitTestsInDirectory(
input_api, output_api, '.', [r'^.+_test\.py$'])
results += input_api.RunTests(tests)
return results
def CheckChangeOnUpload(input_api, output_api):
return CommonChecks(input_api, output_api)
def CheckChangeOnCommit(input_api, output_api):
return CommonChecks(input_api, output_api)
| """Presubmit script for build/chromeos/.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into depot_tools.
"""
def common_checks(input_api, output_api):
results = []
results += input_api.canned_checks.RunPylint(input_api, output_api, pylintrc='pylintrc')
tests = input_api.canned_checks.GetUnitTestsInDirectory(input_api, output_api, '.', ['^.+_test\\.py$'])
results += input_api.RunTests(tests)
return results
def check_change_on_upload(input_api, output_api):
return common_checks(input_api, output_api)
def check_change_on_commit(input_api, output_api):
return common_checks(input_api, output_api) |
N, W = map(int, input().split())
vw = [list(map(int, input().split())) for _ in range(N)]
dp = [[0] * W for _ in range(N)]
for i in range(N):
for w in range(W):
if w >= vw[i][1]:
dp[i + 1][w] = max(dp[i][w - vw[i][1]] + vw[i][0], dp[i][w])
| (n, w) = map(int, input().split())
vw = [list(map(int, input().split())) for _ in range(N)]
dp = [[0] * W for _ in range(N)]
for i in range(N):
for w in range(W):
if w >= vw[i][1]:
dp[i + 1][w] = max(dp[i][w - vw[i][1]] + vw[i][0], dp[i][w]) |
valor = int(input("Informe um valor: "))
triplo = valor * 3
contador = 0
while contador<5:
print(triplo)
contador = contador + 1
print("Acabou!")
| valor = int(input('Informe um valor: '))
triplo = valor * 3
contador = 0
while contador < 5:
print(triplo)
contador = contador + 1
print('Acabou!') |
class IBindingList:
""" Provides the features required to support both complex and simple scenarios when binding to a data source. """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return IBindingList()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def AddIndex(self,property):
"""
AddIndex(self: IBindingList,property: PropertyDescriptor)
Adds the System.ComponentModel.PropertyDescriptor to the indexes used for searching.
property: The System.ComponentModel.PropertyDescriptor to add to the indexes used for searching.
"""
pass
def AddNew(self):
"""
AddNew(self: IBindingList) -> object
Adds a new item to the list.
Returns: The item added to the list.
"""
pass
def ApplySort(self,property,direction):
"""
ApplySort(self: IBindingList,property: PropertyDescriptor,direction: ListSortDirection)
Sorts the list based on a System.ComponentModel.PropertyDescriptor and a System.ComponentModel.ListSortDirection.
property: The System.ComponentModel.PropertyDescriptor to sort by.
direction: One of the System.ComponentModel.ListSortDirection values.
"""
pass
def Find(self,property,key):
"""
Find(self: IBindingList,property: PropertyDescriptor,key: object) -> int
Returns the index of the row that has the given System.ComponentModel.PropertyDescriptor.
property: The System.ComponentModel.PropertyDescriptor to search on.
key: The value of the property parameter to search for.
Returns: The index of the row that has the given System.ComponentModel.PropertyDescriptor.
"""
pass
def RemoveIndex(self,property):
"""
RemoveIndex(self: IBindingList,property: PropertyDescriptor)
Removes the System.ComponentModel.PropertyDescriptor from the indexes used for searching.
property: The System.ComponentModel.PropertyDescriptor to remove from the indexes used for searching.
"""
pass
def RemoveSort(self):
"""
RemoveSort(self: IBindingList)
Removes any sort applied using System.ComponentModel.IBindingList.ApplySort(System.ComponentModel.PropertyDescriptor,System.ComponentModel.ListSortDirection).
"""
pass
def __contains__(self,*args):
"""
__contains__(self: IList,value: object) -> bool
Determines whether the System.Collections.IList contains a specific value.
value: The object to locate in the System.Collections.IList.
Returns: true if the System.Object is found in the System.Collections.IList; otherwise,false.
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __iter__(self,*args):
""" __iter__(self: IEnumerable) -> object """
pass
def __len__(self,*args):
""" x.__len__() <==> len(x) """
pass
AllowEdit=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets whether you can update items in the list.
Get: AllowEdit(self: IBindingList) -> bool
"""
AllowNew=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets whether you can add items to the list using System.ComponentModel.IBindingList.AddNew.
Get: AllowNew(self: IBindingList) -> bool
"""
AllowRemove=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets whether you can remove items from the list,using System.Collections.IList.Remove(System.Object) or System.Collections.IList.RemoveAt(System.Int32).
Get: AllowRemove(self: IBindingList) -> bool
"""
IsSorted=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets whether the items in the list are sorted.
Get: IsSorted(self: IBindingList) -> bool
"""
SortDirection=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the direction of the sort.
Get: SortDirection(self: IBindingList) -> ListSortDirection
"""
SortProperty=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the System.ComponentModel.PropertyDescriptor that is being used for sorting.
Get: SortProperty(self: IBindingList) -> PropertyDescriptor
"""
SupportsChangeNotification=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets whether a System.ComponentModel.IBindingList.ListChanged event is raised when the list changes or an item in the list changes.
Get: SupportsChangeNotification(self: IBindingList) -> bool
"""
SupportsSearching=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets whether the list supports searching using the System.ComponentModel.IBindingList.Find(System.ComponentModel.PropertyDescriptor,System.Object) method.
Get: SupportsSearching(self: IBindingList) -> bool
"""
SupportsSorting=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets whether the list supports sorting.
Get: SupportsSorting(self: IBindingList) -> bool
"""
ListChanged=None
| class Ibindinglist:
""" Provides the features required to support both complex and simple scenarios when binding to a data source. """
def zzz(self):
"""hardcoded/mock instance of the class"""
return i_binding_list()
instance = zzz()
'hardcoded/returns an instance of the class'
def add_index(self, property):
"""
AddIndex(self: IBindingList,property: PropertyDescriptor)
Adds the System.ComponentModel.PropertyDescriptor to the indexes used for searching.
property: The System.ComponentModel.PropertyDescriptor to add to the indexes used for searching.
"""
pass
def add_new(self):
"""
AddNew(self: IBindingList) -> object
Adds a new item to the list.
Returns: The item added to the list.
"""
pass
def apply_sort(self, property, direction):
"""
ApplySort(self: IBindingList,property: PropertyDescriptor,direction: ListSortDirection)
Sorts the list based on a System.ComponentModel.PropertyDescriptor and a System.ComponentModel.ListSortDirection.
property: The System.ComponentModel.PropertyDescriptor to sort by.
direction: One of the System.ComponentModel.ListSortDirection values.
"""
pass
def find(self, property, key):
"""
Find(self: IBindingList,property: PropertyDescriptor,key: object) -> int
Returns the index of the row that has the given System.ComponentModel.PropertyDescriptor.
property: The System.ComponentModel.PropertyDescriptor to search on.
key: The value of the property parameter to search for.
Returns: The index of the row that has the given System.ComponentModel.PropertyDescriptor.
"""
pass
def remove_index(self, property):
"""
RemoveIndex(self: IBindingList,property: PropertyDescriptor)
Removes the System.ComponentModel.PropertyDescriptor from the indexes used for searching.
property: The System.ComponentModel.PropertyDescriptor to remove from the indexes used for searching.
"""
pass
def remove_sort(self):
"""
RemoveSort(self: IBindingList)
Removes any sort applied using System.ComponentModel.IBindingList.ApplySort(System.ComponentModel.PropertyDescriptor,System.ComponentModel.ListSortDirection).
"""
pass
def __contains__(self, *args):
"""
__contains__(self: IList,value: object) -> bool
Determines whether the System.Collections.IList contains a specific value.
value: The object to locate in the System.Collections.IList.
Returns: true if the System.Object is found in the System.Collections.IList; otherwise,false.
"""
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __iter__(self, *args):
""" __iter__(self: IEnumerable) -> object """
pass
def __len__(self, *args):
""" x.__len__() <==> len(x) """
pass
allow_edit = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets whether you can update items in the list.\n\n\n\nGet: AllowEdit(self: IBindingList) -> bool\n\n\n\n'
allow_new = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets whether you can add items to the list using System.ComponentModel.IBindingList.AddNew.\n\n\n\nGet: AllowNew(self: IBindingList) -> bool\n\n\n\n'
allow_remove = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets whether you can remove items from the list,using System.Collections.IList.Remove(System.Object) or System.Collections.IList.RemoveAt(System.Int32).\n\n\n\nGet: AllowRemove(self: IBindingList) -> bool\n\n\n\n'
is_sorted = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets whether the items in the list are sorted.\n\n\n\nGet: IsSorted(self: IBindingList) -> bool\n\n\n\n'
sort_direction = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the direction of the sort.\n\n\n\nGet: SortDirection(self: IBindingList) -> ListSortDirection\n\n\n\n'
sort_property = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the System.ComponentModel.PropertyDescriptor that is being used for sorting.\n\n\n\nGet: SortProperty(self: IBindingList) -> PropertyDescriptor\n\n\n\n'
supports_change_notification = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets whether a System.ComponentModel.IBindingList.ListChanged event is raised when the list changes or an item in the list changes.\n\n\n\nGet: SupportsChangeNotification(self: IBindingList) -> bool\n\n\n\n'
supports_searching = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets whether the list supports searching using the System.ComponentModel.IBindingList.Find(System.ComponentModel.PropertyDescriptor,System.Object) method.\n\n\n\nGet: SupportsSearching(self: IBindingList) -> bool\n\n\n\n'
supports_sorting = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets whether the list supports sorting.\n\n\n\nGet: SupportsSorting(self: IBindingList) -> bool\n\n\n\n'
list_changed = None |
__author__ = 'alse'
def content_length_test(train_metas, test_examples):
max_length = 0.0
min_length = 1000.0
for metadata in train_metas:
if max_length < metadata.length * 1.0 / metadata.size:
max_length = metadata.length * 1.0 / metadata.size
if min_length > metadata.length * 1.0 / metadata.size:
min_length = metadata.length * 1.0 / metadata.size
avg_length = (min_length + max_length) / 2
sum_length = 0
sum_length += len(" ".join(test_examples).split())
return abs(sum_length * 1.0 / len(test_examples) - avg_length)
def jaccard_similarity(x, y):
intersection_cardinality = len(set.intersection(*[set(x), set(y)]))
union_cardinality = len(set.union(*[set(x), set(y)]))
return intersection_cardinality / float(union_cardinality)
def get_n_grams(sentence, n):
return [sentence[i:i + n] for i in xrange(len(sentence) - n)]
def label_text_test(train_metas, test_label): # TODO check if this is right
return max([jaccard_similarity(get_n_grams(x, 2), get_n_grams(test_label, 2)) for x in train_metas])
| __author__ = 'alse'
def content_length_test(train_metas, test_examples):
max_length = 0.0
min_length = 1000.0
for metadata in train_metas:
if max_length < metadata.length * 1.0 / metadata.size:
max_length = metadata.length * 1.0 / metadata.size
if min_length > metadata.length * 1.0 / metadata.size:
min_length = metadata.length * 1.0 / metadata.size
avg_length = (min_length + max_length) / 2
sum_length = 0
sum_length += len(' '.join(test_examples).split())
return abs(sum_length * 1.0 / len(test_examples) - avg_length)
def jaccard_similarity(x, y):
intersection_cardinality = len(set.intersection(*[set(x), set(y)]))
union_cardinality = len(set.union(*[set(x), set(y)]))
return intersection_cardinality / float(union_cardinality)
def get_n_grams(sentence, n):
return [sentence[i:i + n] for i in xrange(len(sentence) - n)]
def label_text_test(train_metas, test_label):
return max([jaccard_similarity(get_n_grams(x, 2), get_n_grams(test_label, 2)) for x in train_metas]) |
while True:
op = input("Digite o Operador: ")
result = 0
if (op != '+') and (op != '-') and (op != '*') and (op != '/') and (op != '#'):
print("Operador invalido!")
else:
if op == '#':
print("Encerrando!")
break
n1 = float(input("Digite o valor 1: "))
n2 = float(input("Digite o valor 2: "))
if op == '+':
result = n1 + n2
elif op == '-':
result = n1 - n2
elif op == '*':
result = n1 * n2
elif op == '/':
if n2 == 0:
print("Operacao invalida (Divisao por 0)")
else:
result = n1 / n2
print(f"O resultado eh {result}") | while True:
op = input('Digite o Operador: ')
result = 0
if op != '+' and op != '-' and (op != '*') and (op != '/') and (op != '#'):
print('Operador invalido!')
else:
if op == '#':
print('Encerrando!')
break
n1 = float(input('Digite o valor 1: '))
n2 = float(input('Digite o valor 2: '))
if op == '+':
result = n1 + n2
elif op == '-':
result = n1 - n2
elif op == '*':
result = n1 * n2
elif op == '/':
if n2 == 0:
print('Operacao invalida (Divisao por 0)')
else:
result = n1 / n2
print(f'O resultado eh {result}') |
input = """
% Bug in rewrinting. Count is eliminated as it is considered isolated.
% Instead it must be considered as a false literal as the aggregate is
% always violated, and bug shouldn't be true.
c(1).
b(1).
bug :- c(Y), Y < #sum{ V:b(V) }.
"""
output = """
{b(1), c(1)}
"""
| input = "\n% Bug in rewrinting. Count is eliminated as it is considered isolated.\n% Instead it must be considered as a false literal as the aggregate is\n% always violated, and bug shouldn't be true. \n\nc(1).\nb(1).\n\nbug :- c(Y), Y < #sum{ V:b(V) }.\n"
output = '\n{b(1), c(1)}\n' |
class Solution:
def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
nums_copy = nums.copy()
ret = []
count = 0
for i in range(len(nums)):
nums.pop(i)
nums.insert(0, nums_copy[i])
count = 0
j = 1
while j < len(nums) :
if nums[0] > nums[j]:
count += 1
j += 1
ret.append(count)
return ret
| class Solution:
def smaller_numbers_than_current(self, nums: List[int]) -> List[int]:
nums_copy = nums.copy()
ret = []
count = 0
for i in range(len(nums)):
nums.pop(i)
nums.insert(0, nums_copy[i])
count = 0
j = 1
while j < len(nums):
if nums[0] > nums[j]:
count += 1
j += 1
ret.append(count)
return ret |
""" Misc. code helper """
def _generate_unique_attribute(fun):
return "__init_%s_%s" % (fun.func_name, str(id(fun)))
def init_function_attrs(fun, **vars):
""" Add the variables with values as attributes to the function fun
if they do not exist and return the function.
Usage: self = init_function_attr(myFun, a = 2, b = 3)
Results in: self = myFun, self.a = 2, self.b = 3
"""
unique_attr = _generate_unique_attribute(fun)
try:
getattr(fun, unique_attr)
except AttributeError:
for (key, val) in vars.items():
setattr(fun, key, val)
setattr(fun, unique_attr, True)
return fun
def reset_function_attrs(fun):
try:
getattr(fun, _generate_unique_attribute(fun))
except AttributeError:
pass
else:
delattr(fun, _generate_unique_attribute(fun))
| """ Misc. code helper """
def _generate_unique_attribute(fun):
return '__init_%s_%s' % (fun.func_name, str(id(fun)))
def init_function_attrs(fun, **vars):
""" Add the variables with values as attributes to the function fun
if they do not exist and return the function.
Usage: self = init_function_attr(myFun, a = 2, b = 3)
Results in: self = myFun, self.a = 2, self.b = 3
"""
unique_attr = _generate_unique_attribute(fun)
try:
getattr(fun, unique_attr)
except AttributeError:
for (key, val) in vars.items():
setattr(fun, key, val)
setattr(fun, unique_attr, True)
return fun
def reset_function_attrs(fun):
try:
getattr(fun, _generate_unique_attribute(fun))
except AttributeError:
pass
else:
delattr(fun, _generate_unique_attribute(fun)) |
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/betting-game/0
def sol(s):
"""
Update rules as per the statement
"""
ba = 1
n = len(s)
i = 0
t = 4
while i < n:
if t < ba:
return -1
if s[i] == "W":
t = t + ba
ba = 1
else:
t = t - ba
ba = 2*ba
i+=1
return t | def sol(s):
"""
Update rules as per the statement
"""
ba = 1
n = len(s)
i = 0
t = 4
while i < n:
if t < ba:
return -1
if s[i] == 'W':
t = t + ba
ba = 1
else:
t = t - ba
ba = 2 * ba
i += 1
return t |
#############################################################
# rename or copy this file to config.py if you make changes #
#############################################################
# change this to your fully-qualified domain name to run a
# remote server. The default value of localhost will
# only allow connections from the same computer.
#
# for remote (cloud) deployments, it is advised to remove
# the "local" data_sources item below, and to serve static
# files using a standard webserver
#
# if use_redis is False, server will use in-memory cache.
# TODO: Convert this to JSON file in web-accesible ('static')
# directory.
config = {
# ssl_args for https serving the rpc
# ssl_args = {"keyfile": None, "certfile": None}
# Cache engines are diskcache, redis, or memory if not specified
"cache": {
"engine": "diskcache",
"params": {"size_limit": int(4*2**30)}
},
"data_sources": [
{
"name": "local",
"url": "file:///",
"start_path": "",
},
{
"name": "ncnr",
"url": "http://ncnr.nist.gov/pub/",
"start_path": "ncnrdata",
"file_helper_url": "https://ncnr.nist.gov/ncnrdata/listftpfiles_json.php",
},
{
"name": "charlotte",
"url": "http://charlotte.ncnr.nist.gov/pub",
"start_path": "",
"file_helper_url": "http://charlotte.ncnr.nist.gov/ncnrdata/listftpfiles_json.php",
},
# set start_path for local files to usr/local/nice/server_data/experiments
# for instrument installs
{
"name": "ncnr_DOI",
"DOI": "10.18434/T4201B",
"file_helper_url": "https://ncnr.nist.gov/ncnrdata/listncnrdatafiles_json.php"
},
],
# if not set, will instantiate all instruments.
"instruments": ["refl", "ospec", "sans"]
}
| config = {'cache': {'engine': 'diskcache', 'params': {'size_limit': int(4 * 2 ** 30)}}, 'data_sources': [{'name': 'local', 'url': 'file:///', 'start_path': ''}, {'name': 'ncnr', 'url': 'http://ncnr.nist.gov/pub/', 'start_path': 'ncnrdata', 'file_helper_url': 'https://ncnr.nist.gov/ncnrdata/listftpfiles_json.php'}, {'name': 'charlotte', 'url': 'http://charlotte.ncnr.nist.gov/pub', 'start_path': '', 'file_helper_url': 'http://charlotte.ncnr.nist.gov/ncnrdata/listftpfiles_json.php'}, {'name': 'ncnr_DOI', 'DOI': '10.18434/T4201B', 'file_helper_url': 'https://ncnr.nist.gov/ncnrdata/listncnrdatafiles_json.php'}], 'instruments': ['refl', 'ospec', 'sans']} |
# Kernel config
c.IPKernelApp.pylab = 'inline' # if you want plotting support always in your notebook
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.token = ''
c.NotebookApp.password = u''
c.notebookApp.open_browser = True | c.IPKernelApp.pylab = 'inline'
c = get_config()
c.NotebookApp.ip = '*'
c.NotebookApp.port = 8888
c.NotebookApp.open_browser = False
c.NotebookApp.token = ''
c.NotebookApp.password = u''
c.notebookApp.open_browser = True |
def check_parity(a: int, b: int, c: int) -> bool:
return a%2 == b%2 == c%2
def print_result(result: bool) -> None:
if result:
print("WIN")
else:
print("FAIL")
a, b, c = map(int, input().strip().split())
print_result(check_parity(a, b, c))
| def check_parity(a: int, b: int, c: int) -> bool:
return a % 2 == b % 2 == c % 2
def print_result(result: bool) -> None:
if result:
print('WIN')
else:
print('FAIL')
(a, b, c) = map(int, input().strip().split())
print_result(check_parity(a, b, c)) |
class employee:
def __init__(self,first,last,pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' +last + '@gmail.com'
def fullname(self):
return '{} {}'.format(self.first,self.last)
#instance variables contain data that is unique to each instances
emp1 = employee('corey','schafer',50000)
emp2 = employee('baken','henry',40000)
# print(emp1)
# print(emp2)
print(emp1.email)
print(emp2.email)
# print('{} {}'.format(emp1.first,emp1.last))
print(emp1.fullname()) | class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
self.email = first + '.' + last + '@gmail.com'
def fullname(self):
return '{} {}'.format(self.first, self.last)
emp1 = employee('corey', 'schafer', 50000)
emp2 = employee('baken', 'henry', 40000)
print(emp1.email)
print(emp2.email)
print(emp1.fullname()) |
class Solution:
def findDuplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
low, high, mid = 0, len(nums)-1, len(nums)-1 // 2
while high - low > 1:
count, mid = 0, (high + low) // 2
for k in nums:
if mid < k <= high: count += 1
if count > high - mid: low = mid
else: high = mid
return high | class Solution:
def find_duplicate(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
(low, high, mid) = (0, len(nums) - 1, len(nums) - 1 // 2)
while high - low > 1:
(count, mid) = (0, (high + low) // 2)
for k in nums:
if mid < k <= high:
count += 1
if count > high - mid:
low = mid
else:
high = mid
return high |
"""
The `gcp_hpo.test` module contains some scripts to test how GCP behaves.
### Regression
The regression folder tests GCP on regression tasks. While `display_branin_function.py` and `simple_test.py` are mostly there to visualize what is happening,
`full_test.py` can be used to quantify its accuracy. More precisely, this enables to test GCP for regression on different functions (see the file `function_utils.py`)
and to measure the likelihood of the fit as well as the mean squared errors of the predictions.
### Acquisition functions
In GCP-based Bayezian optimization, a GCP is fitted on an unknown function and the fit is used to compute some acquisition function. The folder `acquisition_functions` folder
contains two scripts to see the behaviors of the Expected Improvement and the confidence bounds with GCP.
""" | """
The `gcp_hpo.test` module contains some scripts to test how GCP behaves.
### Regression
The regression folder tests GCP on regression tasks. While `display_branin_function.py` and `simple_test.py` are mostly there to visualize what is happening,
`full_test.py` can be used to quantify its accuracy. More precisely, this enables to test GCP for regression on different functions (see the file `function_utils.py`)
and to measure the likelihood of the fit as well as the mean squared errors of the predictions.
### Acquisition functions
In GCP-based Bayezian optimization, a GCP is fitted on an unknown function and the fit is used to compute some acquisition function. The folder `acquisition_functions` folder
contains two scripts to see the behaviors of the Expected Improvement and the confidence bounds with GCP.
""" |
# Copyright (c) 2013, Tomohiro Kusumi
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# RELEASE is basically always 1.
# It was added only to sync with RPM versioning.
# Everytime a batch of new commits is pushed to GitHub, MINOR2 gets incremented.
# RPM patches within the same fileobj version may or may not increment RELEASE.
MAJOR = 0
MINOR1 = 7
MINOR2 = 106
RELEASE = 1
def get_version():
return MAJOR, MINOR1, MINOR2
def get_release():
return MAJOR, MINOR1, MINOR2, RELEASE
def get_version_string():
return "{0}.{1}.{2}".format(*get_version())
def get_release_string():
return "{0}.{1}.{2}-{3}".format(*get_release())
def get_tag_string():
return "v" + get_version_string()
try:
__version__ = get_version_string()
except Exception:
__version__ = "???" # .format() unsupported
| major = 0
minor1 = 7
minor2 = 106
release = 1
def get_version():
return (MAJOR, MINOR1, MINOR2)
def get_release():
return (MAJOR, MINOR1, MINOR2, RELEASE)
def get_version_string():
return '{0}.{1}.{2}'.format(*get_version())
def get_release_string():
return '{0}.{1}.{2}-{3}'.format(*get_release())
def get_tag_string():
return 'v' + get_version_string()
try:
__version__ = get_version_string()
except Exception:
__version__ = '???' |
'''
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Example 1:
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Note:
1 <= S.length <= 20000
S consists only of English lowercase letters.
'''
class Solution(object):
def removeDuplicates(self, S):
"""
:type S: str
:rtype: str
"""
stack = []
if not S:
return ""
for char in S:
if not stack:
stack.append(char)
else:
first = stack[-1]
if first == char:
stack.pop()
else:
stack.append(char)
if not stack:
return ""
return ''.join(stack)
| """
Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them.
We repeatedly make duplicate removals on S until we no longer can.
Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique.
Example 1:
Input: "abbaca"
Output: "ca"
Explanation:
For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca".
Note:
1 <= S.length <= 20000
S consists only of English lowercase letters.
"""
class Solution(object):
def remove_duplicates(self, S):
"""
:type S: str
:rtype: str
"""
stack = []
if not S:
return ''
for char in S:
if not stack:
stack.append(char)
else:
first = stack[-1]
if first == char:
stack.pop()
else:
stack.append(char)
if not stack:
return ''
return ''.join(stack) |
def file_name_for_format(file_format):
names = {
'json': 'data',
'xlsx': 'catalog'
}
file_name = names[file_format]
return file_name
| def file_name_for_format(file_format):
names = {'json': 'data', 'xlsx': 'catalog'}
file_name = names[file_format]
return file_name |
def main(request, response):
location = request.GET.first(b"location")
if request.method == u"OPTIONS":
if b"redirect_preflight" in request.GET:
response.status = 302
response.headers.set(b"Location", location)
else:
response.status = 200
response.headers.set(b"Access-Control-Allow-Methods", b"GET")
response.headers.set(b"Access-Control-Max-Age", 1)
elif request.method == u"GET":
response.status = 302
response.headers.set(b"Location", location)
if b"allow_origin" in request.GET:
response.headers.set(b"Access-Control-Allow-Origin", request.headers.get(b"origin"))
if b"allow_header" in request.GET:
response.headers.set(b"Access-Control-Allow-Headers", request.GET.first(b"allow_header"))
| def main(request, response):
location = request.GET.first(b'location')
if request.method == u'OPTIONS':
if b'redirect_preflight' in request.GET:
response.status = 302
response.headers.set(b'Location', location)
else:
response.status = 200
response.headers.set(b'Access-Control-Allow-Methods', b'GET')
response.headers.set(b'Access-Control-Max-Age', 1)
elif request.method == u'GET':
response.status = 302
response.headers.set(b'Location', location)
if b'allow_origin' in request.GET:
response.headers.set(b'Access-Control-Allow-Origin', request.headers.get(b'origin'))
if b'allow_header' in request.GET:
response.headers.set(b'Access-Control-Allow-Headers', request.GET.first(b'allow_header')) |
# set random number generator
np.random.seed(2020)
# initialize step_end, t_range, v and syn
step_end = int(t_max / dt)
t_range = np.linspace(0, t_max, num=step_end)
v = el * np.ones(step_end)
syn = i_mean * (1 + 0.1 * (t_max/dt) ** (0.5) * (2 * np.random.random(step_end) - 1))
# loop for step_end - 1 steps
for step in range(1, step_end):
v[step] = v[step - 1] + (dt / tau) * (el - v[step - 1] + r * syn[step])
with plt.xkcd():
# initialize the figure
plt.figure()
plt.title('$V_m$ with random I(t)')
plt.xlabel('time (s)')
plt.ylabel(r'$V_m$ (V)')
plt.plot(t_range, v, 'k.')
plt.show() | np.random.seed(2020)
step_end = int(t_max / dt)
t_range = np.linspace(0, t_max, num=step_end)
v = el * np.ones(step_end)
syn = i_mean * (1 + 0.1 * (t_max / dt) ** 0.5 * (2 * np.random.random(step_end) - 1))
for step in range(1, step_end):
v[step] = v[step - 1] + dt / tau * (el - v[step - 1] + r * syn[step])
with plt.xkcd():
plt.figure()
plt.title('$V_m$ with random I(t)')
plt.xlabel('time (s)')
plt.ylabel('$V_m$ (V)')
plt.plot(t_range, v, 'k.')
plt.show() |
##Patterns: E0107
def test():
a = 1
##Err: E0107
++a
##Err: E0107
--a | def test():
a = 1
++a
--a |
#
# PySNMP MIB module BIANCA-BRICK-OSPF-ERR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BIANCA-BRICK-OSPF-ERR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:21:24 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)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Integer32, iso, Bits, enterprises, ModuleIdentity, Unsigned32, Gauge32, ObjectIdentity, MibIdentifier, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, NotificationType, Counter64, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Integer32", "iso", "Bits", "enterprises", "ModuleIdentity", "Unsigned32", "Gauge32", "ObjectIdentity", "MibIdentifier", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "NotificationType", "Counter64", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
bintec = MibIdentifier((1, 3, 6, 1, 4, 1, 272))
bibo = MibIdentifier((1, 3, 6, 1, 4, 1, 272, 4))
biboip = MibIdentifier((1, 3, 6, 1, 4, 1, 272, 4, 5))
ospfErr = MibIdentifier((1, 3, 6, 1, 4, 1, 272, 4, 5, 11))
ospfErrOspfBadVersion = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadVersion.setStatus('mandatory')
ospfErrOspfBadPacketType = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadPacketType.setStatus('mandatory')
ospfErrOspfBadChecksum = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadChecksum.setStatus('mandatory')
ospfErrIpBadDestination = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrIpBadDestination.setStatus('mandatory')
ospfErrOspfBadAreaId = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfBadAreaId.setStatus('mandatory')
ospfErrOspfAuthenticationFailed = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfAuthenticationFailed.setStatus('mandatory')
ospfErrOspfUnknownNeighbor = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfUnknownNeighbor.setStatus('mandatory')
ospfErrHelloNetmaskMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloNetmaskMismatch.setStatus('mandatory')
ospfErrHelloDeadTimerMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloDeadTimerMismatch.setStatus('mandatory')
ospfErrHelloTimerMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloTimerMismatch.setStatus('mandatory')
ospfErrHelloOptionMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrHelloOptionMismatch.setStatus('mandatory')
ospfErrOspfRouterIdConfusion = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfRouterIdConfusion.setStatus('mandatory')
ospfErrOspfUnknownLsaType = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrOspfUnknownLsaType.setStatus('mandatory')
ospfErrDdOptionMismatch = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrDdOptionMismatch.setStatus('mandatory')
ospfErrDdNeighborStateLow = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 15), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrDdNeighborStateLow.setStatus('mandatory')
ospfErrLsackBadAck = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 16), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsackBadAck.setStatus('mandatory')
ospfErrLsackDuplicateAck = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 17), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsackDuplicateAck.setStatus('mandatory')
ospfErrLsreqBadRequest = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsreqBadRequest.setStatus('mandatory')
ospfErrLsreqNeighborStateLow = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsreqNeighborStateLow.setStatus('mandatory')
ospfErrLsupdNeighborStateLow = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdNeighborStateLow.setStatus('mandatory')
ospfErrLsupdBadLsaChecksum = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 21), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdBadLsaChecksum.setStatus('mandatory')
ospfErrLsupdNewerSelfgenLsa = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 22), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdNewerSelfgenLsa.setStatus('mandatory')
ospfErrLsupdLessRecentLsa = MibScalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 23), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ospfErrLsupdLessRecentLsa.setStatus('mandatory')
mibBuilder.exportSymbols("BIANCA-BRICK-OSPF-ERR-MIB", ospfErrLsupdBadLsaChecksum=ospfErrLsupdBadLsaChecksum, ospfErrOspfBadChecksum=ospfErrOspfBadChecksum, ospfErr=ospfErr, ospfErrHelloTimerMismatch=ospfErrHelloTimerMismatch, ospfErrOspfBadVersion=ospfErrOspfBadVersion, ospfErrOspfUnknownNeighbor=ospfErrOspfUnknownNeighbor, ospfErrOspfUnknownLsaType=ospfErrOspfUnknownLsaType, ospfErrOspfRouterIdConfusion=ospfErrOspfRouterIdConfusion, ospfErrLsackBadAck=ospfErrLsackBadAck, ospfErrLsupdNewerSelfgenLsa=ospfErrLsupdNewerSelfgenLsa, bibo=bibo, ospfErrLsreqNeighborStateLow=ospfErrLsreqNeighborStateLow, ospfErrLsreqBadRequest=ospfErrLsreqBadRequest, ospfErrDdOptionMismatch=ospfErrDdOptionMismatch, ospfErrLsupdNeighborStateLow=ospfErrLsupdNeighborStateLow, ospfErrLsackDuplicateAck=ospfErrLsackDuplicateAck, ospfErrOspfBadAreaId=ospfErrOspfBadAreaId, ospfErrLsupdLessRecentLsa=ospfErrLsupdLessRecentLsa, ospfErrHelloOptionMismatch=ospfErrHelloOptionMismatch, ospfErrOspfBadPacketType=ospfErrOspfBadPacketType, ospfErrHelloDeadTimerMismatch=ospfErrHelloDeadTimerMismatch, ospfErrDdNeighborStateLow=ospfErrDdNeighborStateLow, bintec=bintec, ospfErrOspfAuthenticationFailed=ospfErrOspfAuthenticationFailed, ospfErrHelloNetmaskMismatch=ospfErrHelloNetmaskMismatch, biboip=biboip, ospfErrIpBadDestination=ospfErrIpBadDestination)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(integer32, iso, bits, enterprises, module_identity, unsigned32, gauge32, object_identity, mib_identifier, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, notification_type, counter64, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'Integer32', 'iso', 'Bits', 'enterprises', 'ModuleIdentity', 'Unsigned32', 'Gauge32', 'ObjectIdentity', 'MibIdentifier', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'NotificationType', 'Counter64', 'IpAddress')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
bintec = mib_identifier((1, 3, 6, 1, 4, 1, 272))
bibo = mib_identifier((1, 3, 6, 1, 4, 1, 272, 4))
biboip = mib_identifier((1, 3, 6, 1, 4, 1, 272, 4, 5))
ospf_err = mib_identifier((1, 3, 6, 1, 4, 1, 272, 4, 5, 11))
ospf_err_ospf_bad_version = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfBadVersion.setStatus('mandatory')
ospf_err_ospf_bad_packet_type = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfBadPacketType.setStatus('mandatory')
ospf_err_ospf_bad_checksum = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfBadChecksum.setStatus('mandatory')
ospf_err_ip_bad_destination = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrIpBadDestination.setStatus('mandatory')
ospf_err_ospf_bad_area_id = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfBadAreaId.setStatus('mandatory')
ospf_err_ospf_authentication_failed = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfAuthenticationFailed.setStatus('mandatory')
ospf_err_ospf_unknown_neighbor = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfUnknownNeighbor.setStatus('mandatory')
ospf_err_hello_netmask_mismatch = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrHelloNetmaskMismatch.setStatus('mandatory')
ospf_err_hello_dead_timer_mismatch = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrHelloDeadTimerMismatch.setStatus('mandatory')
ospf_err_hello_timer_mismatch = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrHelloTimerMismatch.setStatus('mandatory')
ospf_err_hello_option_mismatch = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrHelloOptionMismatch.setStatus('mandatory')
ospf_err_ospf_router_id_confusion = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 12), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfRouterIdConfusion.setStatus('mandatory')
ospf_err_ospf_unknown_lsa_type = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 13), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrOspfUnknownLsaType.setStatus('mandatory')
ospf_err_dd_option_mismatch = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 14), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrDdOptionMismatch.setStatus('mandatory')
ospf_err_dd_neighbor_state_low = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 15), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrDdNeighborStateLow.setStatus('mandatory')
ospf_err_lsack_bad_ack = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 16), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsackBadAck.setStatus('mandatory')
ospf_err_lsack_duplicate_ack = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 17), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsackDuplicateAck.setStatus('mandatory')
ospf_err_lsreq_bad_request = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 18), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsreqBadRequest.setStatus('mandatory')
ospf_err_lsreq_neighbor_state_low = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 19), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsreqNeighborStateLow.setStatus('mandatory')
ospf_err_lsupd_neighbor_state_low = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 20), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsupdNeighborStateLow.setStatus('mandatory')
ospf_err_lsupd_bad_lsa_checksum = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 21), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsupdBadLsaChecksum.setStatus('mandatory')
ospf_err_lsupd_newer_selfgen_lsa = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 22), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsupdNewerSelfgenLsa.setStatus('mandatory')
ospf_err_lsupd_less_recent_lsa = mib_scalar((1, 3, 6, 1, 4, 1, 272, 4, 5, 11, 23), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ospfErrLsupdLessRecentLsa.setStatus('mandatory')
mibBuilder.exportSymbols('BIANCA-BRICK-OSPF-ERR-MIB', ospfErrLsupdBadLsaChecksum=ospfErrLsupdBadLsaChecksum, ospfErrOspfBadChecksum=ospfErrOspfBadChecksum, ospfErr=ospfErr, ospfErrHelloTimerMismatch=ospfErrHelloTimerMismatch, ospfErrOspfBadVersion=ospfErrOspfBadVersion, ospfErrOspfUnknownNeighbor=ospfErrOspfUnknownNeighbor, ospfErrOspfUnknownLsaType=ospfErrOspfUnknownLsaType, ospfErrOspfRouterIdConfusion=ospfErrOspfRouterIdConfusion, ospfErrLsackBadAck=ospfErrLsackBadAck, ospfErrLsupdNewerSelfgenLsa=ospfErrLsupdNewerSelfgenLsa, bibo=bibo, ospfErrLsreqNeighborStateLow=ospfErrLsreqNeighborStateLow, ospfErrLsreqBadRequest=ospfErrLsreqBadRequest, ospfErrDdOptionMismatch=ospfErrDdOptionMismatch, ospfErrLsupdNeighborStateLow=ospfErrLsupdNeighborStateLow, ospfErrLsackDuplicateAck=ospfErrLsackDuplicateAck, ospfErrOspfBadAreaId=ospfErrOspfBadAreaId, ospfErrLsupdLessRecentLsa=ospfErrLsupdLessRecentLsa, ospfErrHelloOptionMismatch=ospfErrHelloOptionMismatch, ospfErrOspfBadPacketType=ospfErrOspfBadPacketType, ospfErrHelloDeadTimerMismatch=ospfErrHelloDeadTimerMismatch, ospfErrDdNeighborStateLow=ospfErrDdNeighborStateLow, bintec=bintec, ospfErrOspfAuthenticationFailed=ospfErrOspfAuthenticationFailed, ospfErrHelloNetmaskMismatch=ospfErrHelloNetmaskMismatch, biboip=biboip, ospfErrIpBadDestination=ospfErrIpBadDestination) |
"""
File: complement.py
----------------------------
This program uses string manipulation to
tackle a real world problem - finding the
complement strand of a DNA sequence.
THe program asks uses for a DNA sequence as
a python string that is case-insensitive.
Your job is to output the complement of it.
"""
def main():
"""
This App provides complement sequence of DNA
"""
dna = input('Please give me a DNA strand and I\'ll find the complement:')
dna = dna.upper()
complement_dna = find_complement(dna)
print('The complement of ' + dna + ' is ' + complement_dna)
def find_complement(dna):
"""
:param dna: str, DNA consequence provided by user to be compared
:return: str, complement DNA consequence for given DNA consequence
"""
complement = ''
for i in range(len(dna)):
ch = dna[i]
if ch == 'A':
complement += 'T'
elif ch == 'T':
complement += 'A'
elif ch == 'C':
complement += 'G'
else:
complement += 'C'
return complement
###### DO NOT EDIT CODE BELOW THIS LINE ######
if __name__ == '__main__':
main()
| """
File: complement.py
----------------------------
This program uses string manipulation to
tackle a real world problem - finding the
complement strand of a DNA sequence.
THe program asks uses for a DNA sequence as
a python string that is case-insensitive.
Your job is to output the complement of it.
"""
def main():
"""
This App provides complement sequence of DNA
"""
dna = input("Please give me a DNA strand and I'll find the complement:")
dna = dna.upper()
complement_dna = find_complement(dna)
print('The complement of ' + dna + ' is ' + complement_dna)
def find_complement(dna):
"""
:param dna: str, DNA consequence provided by user to be compared
:return: str, complement DNA consequence for given DNA consequence
"""
complement = ''
for i in range(len(dna)):
ch = dna[i]
if ch == 'A':
complement += 'T'
elif ch == 'T':
complement += 'A'
elif ch == 'C':
complement += 'G'
else:
complement += 'C'
return complement
if __name__ == '__main__':
main() |
def deep_index(lst, w):
return [[i, sub.index(w)] for (i, sub) in enumerate(lst) if w in sub]
class variable():
def __init__(self, name, val):
self.name = name
self.val = val
class variableHandler():
def __init__(self):
self.varList = []
def create(self, varName, varVal):
inList = False
for var in self.varList:
if var.name == varName:
inList = True
if not inList:
var = variable(varName, varVal)
self.varList.append(var)
return var
else:
for var in self.varList:
if var.name == varName:
var.val = varVal
return variable(varName, varVal)
def get(self, varName):
for var in self.varList:
if var.name == varName:
return var.val
return None | def deep_index(lst, w):
return [[i, sub.index(w)] for (i, sub) in enumerate(lst) if w in sub]
class Variable:
def __init__(self, name, val):
self.name = name
self.val = val
class Variablehandler:
def __init__(self):
self.varList = []
def create(self, varName, varVal):
in_list = False
for var in self.varList:
if var.name == varName:
in_list = True
if not inList:
var = variable(varName, varVal)
self.varList.append(var)
return var
else:
for var in self.varList:
if var.name == varName:
var.val = varVal
return variable(varName, varVal)
def get(self, varName):
for var in self.varList:
if var.name == varName:
return var.val
return None |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.