content stringlengths 7 1.05M |
|---|
# Messages issued by the bot to the user
REMOVAL_MESSAGE = """
The message by {username} was deleted as it violated the channel's moral guidelines.
Multiple such violations may lead to a temporary or even a permanent ban
"""
PERSONAL_MESSAGE_AFTER_REMOVAL = """
We deleted your message because it was found to be toxic. Please refrain from using such messages in the channels. \
Repeated violations will result in stricter actions.
"""
INFO_MESSAGE = """
Hi {username}, this is Mr Toxic Bot. \
I'm responsible for ensuring a friendly environment that promotes social well being in the channel. \
Any message that I deem toxic, insulting, threatening etc will be removed and the author will be given a warning. \
"""
HELP_MESSAGE = """
Hi {username}, this is Mr Toxic Bot. \n
Here's a list of commands you can use to chat with me: \n
- /report - With this command you'll receive the link of the GitHub page of the project to report bugs and issues \n
- /info - You'll receive some info about me :D \n
- /help - You'll receive the list of commands
"""
WELCOME_MESSAGE = """
Hi {0.mention}, Welcome to {1.name} Server.
"""
WELCOME_DM_MESSAGE = """
Hi {0.mention}, Welcome to {1.name} Server.
Use /help to see various commands you can use to chat with me
"""
REPORT_MESSAGE = """
Need something wrong? Here's a link to report that!
"""
ONLY_PRIVATE_DMS = """
Hey {user}, the command can only be invoked by a private DM to ToxicBot.
"""
ADMIN_MESSAGE_AFTER_BOT_JOIN = """
Howdy, I am Mr. Toxic Bot. I am responsible for ensuring that the server is family friendly. \
Any obscene or toxic message sent to the server will be immediately deleted and the author will be warned. \
Here's some configuration that is applied to the server:\n
- Toxic Count before suspending an user : 20\n
- Number of days before previous toxic count history is erased for an user : 14 days
The above configurations can be modified by the server administrator.
"""
REQUISITE_PERMISSION = """
Sorry {user}, you do not have the requisite priviledges to execute the above command.
"""
NOT_BOT_OWNER = """
Sorry {user}, only the owner of the bot can run the above command.
"""
ADMIN_REQUEST_SERVER_ID = """
It seems that you are part of multiple servers. Please select which server you want to get the information about.
"""
ADMIN_CONFIG = """
Here are the current configurations for the server {guild}:\n
- Toxic Count before suspending an user : {count}\n
- Number of days before previous toxic count history is erased for an user : {time} days
"""
REQUIRE_NUMERICAL_VALUE = """
{entity} must be a numerical value
"""
SUCCESSFUL_UPDATE = """
{entity} updated for server {server}
"""
ADMIN_HELP_MESSAGE = """
Hi {username}, this is Mr Toxic Bot. \n
Here's a list of commands you can use to chat with me: \n
- /report - With this command you'll receive the link of the GitHub page of the project to report bugs and issues \n
- /info - You'll receive some info about me :D \n
- /help - You'll receive the list of commands \n
Here's a list of admin commands which only server owners can use: \n
- /config - Current configurations of toxic bot \n
- /setcount 10 - Set the toxic comment count before suspending an user ( 10 is just an arbitrary number ) \n
- /setdays 15 - Set the number of days before resetting toxic count for an user ( 15 is just an arbitrary number ) \n
- /toptoxic 5 - Get the top toxic comments by users for a server ( 5 is just an arbitrary number )
"""
BAD_ARGUMENT = """
Improper arguments passed.
"""
REQUEST_TIMEOUT = """
Oopsies. Looks like the request timed out. Please try again
"""
|
def _get_ratio(ratio):
if isinstance(ratio, str):
if ':' in ratio:
r_w, r_h = ratio.split(':')
try:
ratio = float(r_w) / float(r_h)
except:
raise
if not isinstance(ratio, float):
ratio = float(ratio)
return ratio
def centerratio(size, center, ratio=1.0):
def _calc_max_size(size, center):
w, h = size
x_l, y_t = center
x_r, y_b = w-x_l, h-y_t
return min(x_l, x_r)*2, min(y_t, y_b)*2
ratio = _get_ratio(ratio)
width_max, height_max = _calc_max_size(size, center)
width_ratio = round(height_max * ratio)
width = min(width_max, width_ratio)
height = round(width / ratio)
return center[0] - round(width/2), \
center[1] - round(height/2), \
width, height
def expandratio(size, ratio=1.0):
ratio = _get_ratio(ratio)
w, h = size
w_r = round(h * ratio)
if w > w_r:
h_r = round(w / ratio)
return w, h_r, 0, int((h_r-h)/2)
elif w < w_r:
return w_r, h, int((w_r-w)/2), 0
else:
return w, h, 0, 0
|
# @Title: 千位分隔数 (Thousand Separator)
# @Author: KivenC
# @Date: 2020-08-23 01:03:42
# @Runtime: 36 ms
# @Memory: 13.6 MB
class Solution:
def thousandSeparator(self, n: int) -> str:
# return format(n, ',').replace(',', '.')
s = str(n)
count = len(s)
res = ''
for c in s:
res += c
count -= 1
if count > 0 and count % 3 == 0:
res += '.'
return res
|
# Copyright (c) 2015, Sofiat Olaosebikan. All Rights Reserved
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class HopcroftKarp(object):
def __init__(self, graph):
"""
:param graph: an unweighted bipartite graph represented as a dictionary.
Vertices in the left and right vertex set must have different labelling
:return: a maximum matching of the given graph represented as a dictionary.
"""
self._matching = {}
self._dfs_paths = []
self._dfs_parent = {}
self._left = set(graph.keys())
self._right = set()
for value in graph.values():
self._right.update(value)
for vertex in self._left:
for neighbour in graph[vertex]:
if neighbour not in graph:
graph[neighbour] = set()
graph[neighbour].add(vertex)
else:
graph[neighbour].add(vertex)
self._graph = graph
def __bfs(self):
layers = []
layer = set()
for vertex in self._left: # for each free vertex in the left vertex set
if vertex not in self._matching: # confirms that the vertex is free
layer.add(vertex)
layers.append(layer)
visited = set() # to keep track of the visited vertices
while True:
# we take the most recent layer in the partitioning on every repeat
layer = layers[-1]
new_layer = set() # new list for subsequent layers
for vertex in layer:
if vertex in self._left: # if true, we traverse unmatched edges to vertices in right
visited.add(vertex)
for neighbour in self._graph[vertex]:
# check if the neighbour is not already visited
# check if vertex is matched or the edge between neighbour and vertex is not matched
if neighbour not in visited and (vertex not in self._matching or neighbour != self._matching[vertex]):
new_layer.add(neighbour)
else: # we traverse matched edges to vertices in left
visited.add(vertex) # we don't want to traverse the vertex again
for neighbour in self._graph[vertex]:
# check if the neighbour is not already visited
# check if vertex is in the matching and if the edge between vertex and neighbour is matched
if neighbour not in visited and (vertex in self._matching and neighbour == self._matching[vertex]):
new_layer.add(neighbour)
layers.append(new_layer) # we add the new layer to the set of layers
# if new_layer is empty, we have to break the BFS while loop....
if len(new_layer) == 0:
return layers # break
# else, we terminate search at the first layer k where one or more free vertices in V are reached
if any(vertex in self._right and vertex not in self._matching for vertex in new_layer):
return layers # break
# break
# --------------------------------------------------------------------------------------------------------------
# if we are able to collate these free vertices, we run DFS recursively on each of them
# this algorithm finds a maximal set of vertex disjoint augmenting paths of length k (shortest path),
# stores them in P and increments M...
# --------------------------------------------------------------------------------------------------------------
def __dfs(self, v, index, layers):
"""
we recursively run dfs on each vertices in free_vertex,
:param v: vertices in free_vertex
:return: True if P is not empty (i.e., the maximal set of vertex-disjoint alternating path of length k)
and false otherwise.
"""
if index == 0:
path = [v]
while self._dfs_parent[v] != v:
path.append(self._dfs_parent[v])
v = self._dfs_parent[v]
self._dfs_paths.append(path)
return True
for neighbour in self._graph[v]: # check the neighbours of vertex
if neighbour in layers[index - 1]:
# if neighbour is in left, we are traversing unmatched edges..
if neighbour in self._dfs_parent:
continue
if (neighbour in self._left and (v not in self._matching or neighbour != self._matching[v])) or \
(neighbour in self._right and (v in self._matching and neighbour == self._matching[v])):
self._dfs_parent[neighbour] = v
if self.__dfs(neighbour, index-1, layers):
return True
return False
def maximum_matching(self):
while True:
layers = self.__bfs()
# we break out of the whole while loop if the most recent layer added to layers is empty
# since if there are no vertices in the recent layer, then there is no way augmenting paths can be found
if len(layers[-1]) == 0:
break
free_vertex = set([vertex for vertex in layers[-1] if vertex not in self._matching])
# the maximal set of vertex-disjoint augmenting path and parent dictionary
# has to be cleared each time the while loop runs
# self._dfs_paths.clear() - .clear() and .copy() attribute works for python 3.3 and above
del self._dfs_paths[:]
self._dfs_parent.clear()
for vertex in free_vertex: # O(m) - every vertex considered once, each edge considered once
# this creates a loop of the vertex to itself in the parent dictionary,
self._dfs_parent[vertex] = vertex
self.__dfs(vertex, len(layers)-1, layers)
# if the set of paths is empty, nothing to add to the matching...break
if len(self._dfs_paths) == 0:
break
# if not, we swap the matched and unmatched edges in the paths formed and add them to the existing matching.
# the paths are augmenting implies the first and start vertices are free. Edges 1, 3, 5, .. are thus matched
for path in self._dfs_paths:
for i in range(len(path)):
if i % 2 == 0:
self._matching[path[i]] = path[i+1]
self._matching[path[i+1]] = path[i]
return self._matching
if __name__ == "__main__":
#graph = {'a': {1}, 'b': {1, 2}, 'c': {1, 2}, 'd': {2, 3, 4}, 'e': {3, 4}, 'f': {4, 5, 6}, 'g': {5, 6, 7}, 'h': {8}}
#print(HopcroftKarp(graph).maximum_matching())
graph = {'a': {2,3}, 'b': {1, 2,4,5}, 'c': {2, 3}, 'd': {2, 3}, 'e': {4, 5}}
print(HopcroftKarp(graph).maximum_matching())
|
class DefaultAlias(object):
''' unless explicitly assigned, this attribute aliases to another. '''
def __init__(self, name):
self.name = name
def __get__(self, inst, cls):
if inst is None:
# attribute accessed on class, return `self' descriptor
return self
return getattr(inst, self.name)
class Alias(DefaultAlias):
''' this attribute unconditionally aliases to another. '''
def __set__(self, inst, value):
setattr(inst, self.name, value)
def __delete__(self, inst):
delattr(inst, self.name)
|
#使用BFS, 单词和length一块记录, dict中每个单词只能用一次, 所以用过即删。dict给的是set类型, 检查一个单词在不在其中(word in dict)为O(1)时间。设单词长度为L, dict里有N个单词, 每次扫一遍dict判断每个单词是否与当前单词只差一个字母的时间复杂度是O(N*L), 而每次变换当前单词的一个字母, 看变换出的词是否在dict中的时间复杂度是O(26*L), 所以要选择后者。Python真是慢啊, 同样的代码C++ 668ms过, Python 1416ms过。看到双向BFS的做法, 应该能更快, 再研究研究。
class Solution:
# @param start, a string
# @param end, a string
# @param dict, a set of string
# @return an integer
def ladderLength(self, start, end, dict):
dict.add(end)
wordLen = len(start)
queue = collections.deque([(start, 1)])
while queue:
curr = queue.popleft()
currWord = curr[0]; currLen = curr[1]
if currWord == end: return currLen
for i in xrange(wordLen):
part1 = currWord[:i]; part2 = currWord[i+1:]
for j in 'abcdefghijklmnopqrstuvwxyz':
if currWord[i] != j:
nextWord = part1 + j + part2
if nextWord in dict:
queue.append((nextWord, currLen + 1))
dict.remove(nextWord)
return 0
|
f1 = open("unprocessed/Cit-HepTh-dates.csv", "w")
f2 = open("unprocessed/Cit-HepTh.csv", "w")
with open("unprocessed/Cit-HepTh-dates.txt", "r") as file:
c = 0
for line in file:
if not c == 0:
l = line.split()
nl = l[0] + "," + l[1] + '\n'
f1.write(nl)
else:
c += 1
with open("unprocessed/Cit-HepTh.txt", "r") as file:
for line in file:
if c > 4:
l = line.split()
nl = l[0] + "," + l[1] + '\n'
f2.write(nl)
else:
c += 1
class Paper:
def __init__(self, id, date, citates):
self.id = id
self.date = date
|
def color_analysis(img):
# obtain the color palatte of the image
palatte = defaultdict(int)
for pixel in img.getdata():
palatte[pixel] += 1
# sort the colors present in the image
sorted_x = sorted(palatte.items(), key=operator.itemgetter(1), reverse = True)
light_shade, dark_shade, shade_count, pixel_limit = 0, 0, 0, 25
for i, x in enumerate(sorted_x[:pixel_limit]):
if all(xx <= 20 for xx in x[0][:3]): ## dull : too much darkness
dark_shade += x[1]
if all(xx >= 240 for xx in x[0][:3]): ## bright : too much whiteness
light_shade += x[1]
shade_count += x[1]
light_percent = round((float(light_shade)/shade_count)*100, 2)
dark_percent = round((float(dark_shade)/shade_count)*100, 2)
return light_percent, dark_percent
|
#Write a program using while loops that asks the user for a positive integer 'n' and prints
#a triangle using numbers from 1 to 'n'.
number = int(input("Give me a number: "))
count = 0
for x in range(1, number+1):
count += 1
dibujar = str(x)
print (dibujar*count)
|
"""
factorial() is function factorial(number),
take the number parameter been passed and
return the factorial of it
"""
def factorial(number):
if number == 0:
return 1
else:
ans = number * factorial(number - 1)
return ans
|
class Solution:
def getFactors(self, n):
"""
:type n: int
:rtype: List[List[int]]
"""
ans = []
self.helper(n, [], n, ans)
return ans
def helper(self, n, factors, left, ans):
if left == 1:
if factors:
ans.append(factors)
else:
lo = 2 if not factors else factors[-1]
for i in range(lo, min(n, left + 1)):
if left % i == 0:
self.helper(n, factors + [i], left // i, ans)
|
class Board(object):
def __init__(self, boards):
if len(boards) != 25:
raise Exception(f"Invalid board : {len(boards)}")
self.boards = boards
self.marked = [False] * 25
@staticmethod
def parse(lines):
boards = []
for line in lines:
boards.extend([int(x) for x in line.split()])
return Board(boards)
def mark(self, nb):
for i, n in enumerate(self.boards):
if n == nb:
self.marked[i] = True
def won(self):
# row
for i in range(0, 25, 5):
if all(self.marked[i: i + 5]):
return True
# col
for i in range(5):
if all(self.marked[i::5]):
return True
return False
def unmarked(self):
u = []
for i, m in enumerate(self.marked):
if not m:
u.append(self.boards[i])
return u
class Bingo(object):
def __init__(self, order, boards):
self.order = order
self.boards = boards
@staticmethod
def parse(text: str):
lines = text.splitlines()
order = [int(x) for x in lines[0].split(",")]
boards = []
l = 2
while True:
boards.append(Board.parse(lines[l: l + 5]))
l += 6
if l >= len(lines):
break
return Bingo(order, boards)
def play(self):
for o in self.order:
for board in self.boards:
board.mark(o)
if board.won():
return sum(board.unmarked()) * o
if __name__ == "__main__":
little = """7,4,9,5,11,17,23,2,0,14,21,24,10,16,13,6,15,25,12,22,18,20,8,19,3,26,1
22 13 17 11 0
8 2 23 4 24
21 9 14 16 7
6 10 3 18 5
1 12 20 15 19
3 15 0 2 22
9 18 13 17 5
19 8 7 25 23
20 11 10 24 4
14 21 16 12 6
14 21 17 24 4
10 16 15 9 19
18 8 23 26 20
22 11 13 6 5
2 0 12 3 7
"""
bingo = Bingo.parse(little)
print(bingo.play())
with open("../input", "r") as f:
bingo = Bingo.parse(f.read())
print(bingo.play())
|
{
"format_version": "1.16.0",
"minecraft:entity": {
"description": {
"identifier": f"{namespace}:pig_{color}",
"is_spawnable": true,
"is_summonable": true,
"is_experimental": false
},
"components": {
"minecraft:type_family": {
"family": [
f"pig_{color}",
"pig",
"mob"
]
},
"minecraft:breathable": {
"total_supply": 15,
"suffocate_time": 0
},
"minecraft:health": {
"value": 10,
"max": 10
},
"minecraft:hurt_on_condition": {
"damage_conditions": [
{
"filters": {
"test": "in_lava",
"subject": "self",
"operator": "==",
"value": true
},
"cause": "lava",
"damage_per_tick": 4
}
]
},
"minecraft:movement": {
"value": 0.25
},
"minecraft:navigation.walk": {
"can_path_over_water": true,
"avoid_water": true,
"avoid_damage_blocks": true
},
"minecraft:movement.basic": {},
"minecraft:jump.static": {},
"minecraft:can_climb": {},
"minecraft:collision_box": {
"width": 0.9,
"height": 0.9
},
"minecraft:despawn": {
"despawn_from_distance": {}
},
"minecraft:behavior.float": {
"priority": 2
},
"minecraft:behavior.panic": {
"priority": 3,
"speed_multiplier": 1.25
},
"minecraft:behavior.random_stroll": {
"priority": 7,
"speed_multiplier": 1.0
},
"minecraft:behavior.look_at_player": {
"priority": 8,
"look_distance": 6.0,
"probability": 0.02
},
"minecraft:behavior.random_look_around": {
"priority": 9
},
"minecraft:physics": {},
"minecraft:pushable": {
"is_pushable": true,
"is_pushable_by_piston": true
},
"minecraft:conditional_bandwidth_optimization": {}
}
}
} |
"""
The :mod:`stan.proc_functions.merge` module is the proc merge function
"""
def merge(dt_left, dt_right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True):
return dt_left.merge(dt_right, how='inner', on=None, left_on=None, right_on=None, left_index=False, right_index=False, sort=False, suffixes=('_x', '_y'), copy=True)
|
"""
Constants
Author: Brady Volkmann
Date: 6/21/2019
Constants file for the Tektroniks TTR506 VNA
"""
# INITIALIZE CONSTANTS ======================================================
# configure acquisition parameters
startFreqSweep = '50 MHz'
stopFreqSweep = '6 GHz'
sweepDelay = '1s'
snpFilename = 'test.s1p'
sParam = 'S21'
|
description = 'The outside temperature on the campus'
group = 'lowlevel'
devices = dict(
OutsideTemp = device('nicos.devices.entangle.Sensor',
description = 'Outdoor air temperature',
tangodevice = 'tango://ictrlfs.ictrl.frm2:10000/frm2/meteo/temp',
),
)
|
#This is just a demo server file to demonstrate the working of Telopy Backend
#This program consist the last line of Telopy
#import time
#import sys
#cursor = ['|','/','-','\\']
print('Telopy Server is Live ',end="")
#while True:
# for i in cursor:
# print(i+"\x08",end="")
# sys.stdout.flush()
# time.sleep(0.1) |
class VersioningError(Exception):
pass
class ClassNotVersioned(VersioningError):
pass
class ImproperlyConfigured(VersioningError):
pass
|
def create_groups(items, n):
"""Splits items into n groups of equal size, although the last one may be shorter."""
# determine the size each group should be
try:
# this line could cause a ZeroDivisionError exception
size = len(items) // n
except ZeroDivisionError:
print('WARNING: Returning empty list. Please use a nonzero number.')
return []
else:
# create each group and append to a new list
groups = []
for i in range(0, len(items), size):
groups.append(items[i:i + size])
return groups
finally:
# print the number of groups and return groups
print("{} groups returned.".format(n))
print("Creating 6 groups...")
for group in create_groups(range(32), 6):
print(list(group))
print("\nCreating 0 groups...")
for group in create_groups(range(32), 0):
print(list(group))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@created: 22.01.20
@author: felix
"""
NORMALIZE = False
class EasyDict(dict):
def __init__(self, *args, **kwargs):
global NORMALIZE
NORMALIZE = kwargs.pop('normalize', False)
super(EasyDict, self).__init__(*args, **kwargs)
def __getattr__(self, item):
if NORMALIZE and item.replace('_', ' ') in self.keys():
return self.get(item)
elif item not in self.keys():
raise AttributeError()
else:
return self.get(item)
def __setattr__(self, key, value):
if NORMALIZE:
key = key.replace('_', ' ')
self.__setitem__(key, value)
def get(self, k, *args):
if NORMALIZE:
k = k.replace('_', ' ')
if k not in self.keys() and len(args) == 1:
return args[0]
else:
return super().get(k)
|
fig, axs = plt.subplots(1, 2, figsize=(20,5))
p1=boroughs4.plot(column='Controlled drugs',ax=axs[0],cmap='Blues',legend=True);
p2=boroughs4.plot(column='Stolen goods',ax=axs[1], cmap='Reds',legend=True);
axs[0].set_title('Controlled drugs', fontdict={'fontsize': '12', 'fontweight' : '5'});
axs[1].set_title('Stolen goods', fontdict={'fontsize': '12', 'fontweight' : '5'});
|
#Höfundur Einar Karl
#Dagsetning 24/09/2018
val=""
#While loop
while (val !="6"):
#Valmynd
print("------------------------------------------------") #Lína til að láta forritið líta betur út
print("1. Liður 1 (Tölu innsláttur) ")
print("2. Liður 2 (Ferhyrnings Reikningur) ")
print("3. Liður 3 (Leyniorðs innsláttur) ")
print("4. Liður 4 (Gengur fimm í tölu?) ")
print("5. Liður 5 (Fleiri reikningar) ")
print("6. Hætta")
val=input("Veldu 1, 2, 3, 4, 5 eða 6 til að hætta ")
if val=="1":
aftur="já" #Set 'aftur' sem 'já'
while (aftur == "já" or aftur == "Já"): #svo lengi sem aftur er já þá keyrir forritið
tala=int(input("Sláðu inn heiltölu "))#biður um tölu
#Útskrift
print("Þú hefur valið töluna:",tala)
aftur=input("Viltu slá inn aðra heiltölu? ") #Ef valið er 'já' þá keyrir forritið ef ekki þá hættir það
elif val=="2":
svar="já" #'svar' er skilgreint
while (svar == "já" or svar == "Já"): #Á meðan að svarið er já þá keyrir forritið
lengd=int(input("Sláðu inn lengd á ferhyrningi "))
breidd=int(input("Sláðu inn breidd á ferhyrningi "))
#Útskrift
print("Flatarmálið er",lengd*breidd)
svar=input("Viltu endurtaka þetta? ")#Ef valið er já þá keyrir forritið annars ekki
elif val=="3":
leyniord="einar" #Leyniorðið er skráð
svar=0
while svar != leyniord: #Á meðan að leyniorðið er ekki rétt þá keyrir forritið
svar=input("Skrifaðu leyniorðið þitt ")
#Útskrift ef rétt lykilorð er skrifað
print("Vel Gert")
elif val=="4":
tala=int(input("Sláðu inn heiltölu ")) #Beðið er um tölu
if tala % 5==0: #Ef 5 gengur upp í töluna:
#Útskrift
print("Talan",tala,"er í fimm sinnum töflunni")
else: #Útskrift ef fimm gengur ekki upp í töluna
print("Talan",tala,"er ekki í fimm sinnum töflunni")
elif val=="5":
val2=""
tel2=0 #val2 og tel2 er skilgreint
while (val2 !="3"): #Á meðan að valið er ekki 3 keyrir forritið
print("------------------------------------------------")
tel2=tel2+1 #Teljari fyrir hve oft forritið keyrir
print("1. Biður um 10 tölur. Finnur summu þeirra og meðaltal.")
print("2. Biður um tölu og athugar hvort talan sé jöfntala eða oddatala ")
print("3. Hætta í forritinu og skrifa ’Ég er frábær forritari’ á skjáinn 10 sinnum og tilgreina hversu oft forritið var keyrt. ")
val2=input("Veldu 1, 2 eða 3 ") #Önnur valmynd
if val2=="1":
telur=-1
summa=0
while telur<9: #Eftirfarandi kóði er endurtekinn 10 sinnum
telur=telur+1
tala=int(input("Sláðu inn tölu "+str(telur+1)+" ")) #Spurt er um tölu
summa=summa+tala
print("Summa talnanna er",summa)
medaltal=summa/10 #Formúla fyrir meðaltölu talnanna
#útskrift
print("Meðaltal talnanna er",medaltal)
elif val2=="2":
tala=int(input("Sláðu inn tölu "))
if tala % 2==1: #Formúla til að finna hvort talan er oddatala eða ekki
#Útskrift
print("Þetta er oddatala")
else:
#Útskrift 2
print("Þetta er jöfntala")
elif val2=="3":
tel=1#Tel er skilgreint
while tel<=10: #Eftirfarandi kóði er keyrður 10 sinnum
print("Ég er frábær forritari")
tel=tel+1
#Útskrift
print("Aðallúppan hefur keyrt",tel2,"sinnum") #Forritið skrifar hve oft while lúppan keyrði
else: #Þetta kemur ef eitthvað annað en 1, 2, eða 3, er skrifað
print("Rangur Innsláttur")
elif val=="6":
#Útskrift
print("Ókei Bæ")
#Hér hættir forritið að keyra
else:
print("Rangur Innsláttur")#Ef valið er eitthvað annað en 1 til 6
# Í fyrri kóðanum sem kemur í word skjalinu keyrir kóðinn upp í 10 og hættir svo. Þá er 'i' 0 og hann bætir við sig 1
#Þegar forritið er keyrt þá fer i frá 1 upp í 10. While kóðinn segir forritinu að stoppa þegar 10 kemur
# Í seinni kóðanum er 'i' 1 og þá bætir hann við sig 2. While loopan segir að forritið á að hætta þegar 10 kemur(Heldur áfram á meðan 10 er ekki)
#Þegar maður keyrir samt forritið þá heldur það áfram að eilífu. Ástæðan fyrir því er að forritið fer aldrei upp í 10. Ef það myndi byrja á 0 þá myndi það hætta.
|
class Reaction:
def __init__(self):
pass
def from_json(json):
reaction = Reaction()
reaction.reaction = json["reaction"].encode("unicode-escape")
reaction.actor = json["actor"]
return reaction
def list_from_json(json):
reactions = []
for child in json:
reactions.append(Reaction.from_json(child))
return reactions |
class Triangulo():
def __init__(self, a, b, c):
self.a = a
self.b = b
self.c = c
def semelhantes(self, triangulo):
a, b, c = triangulo.a, triangulo.b, triangulo.c
if ((a % self.a) == 0 ) and ((b % self.b) == 0) and ((c % self.c) == 0):
return True
elif ((a // self.a) == 0 ) and ((b // self.b) == 0) and ((c // self.c) == 0):
return True
return False
# t1 = Triangulo(2, 2, 2)
# t2 = Triangulo(4, 4, 4)
# print(t1.semelhantes(t2))
# t3 = Triangulo(3, 4, 5)
# t4 = Triangulo(3, 4, 5)
# print(t3.semelhantes(t4))
# t5 = Triangulo(6, 8, 10)
# t6 = Triangulo(3, 4, 5)
# print(t5.semelhantes(t6)) |
age = input("Please enter your age: ")
if age.isdigit():
print(age)
age = int(input("Please enter your age: "))
while(True):
try:
age = int(input("Please enter your age: "))
except ValueError:
print("Sorry, I didn't understand that.")
continue
else:
break
raise Exception("arguments") |
def fasttsq(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fasttsq3d(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fasttsqp(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fastq(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError
def fastq3d(M,psi,Y,y,m,c,o,plm):
#TODO
raise NotImplementedError |
## A - O somatorio de 2 com 2 e menor do que 4?
print(2+2 < 4)
##-------------------------
## B - O valor 7//3 e igual a 1+1?
print(7 // 3 == 1+1)
##--------------------------
## C - A soma de 3 elevado ao quadrado com 4 elevado ao quadrado e igual a 25?
print(3 ** 2 + 4 ** 2 == 25)
##--------------------------
## D - A soma de 2,4 e 6 e maior que 12
print(2+4+6 > 12)
##--------------------------
## E - 1387 e divisivel por 19?
## Pra mim saber se e divisivel e preciso saber se o resto termina em 0 usando o operador %
print(1387 % 19 == 0)
##-------------------------
## F - 31 e par?
print(31 % 2 == 0)
##-------------------------
## G- O menor valor entre: 34,29 e 31 e menor do que 30?
print(min(34,29,31) < 30)
##------------------------------
## CONDICIONAL SIMPLES EXERCICIOS
## TRADUZA AS AFIRMACOES A SEGUIR PARA CONDICIONAIS SIMPLES EM PYTHON
## A - Se idade é maior que 60, escreva: "Você tem direito as beneficios"
idade = 61
if idade > 60:
print('Você tem direito aos benefícios')
##-----------------------------
## B - Se dano é maior do que 10 e escudo é igual a 0, escreva: Você está morto!
dano = 11
escudo = 0
if dano > 10 and escudo == 0:
print('Voce esta morto!')
##---------------------------
## C - Se pelo menos uma da variaveis booleanas norte, sul, leste e oeste resultare em true, escreva: Voce escapou!
norte = True
sul = False
leste = False
oeste = False
## Um jeito mais simples de resolver = if norte or sul or leste or oeste; Ele se compara a true sem precisar colocar o true.
if norte == True or sul == True or leste == True or oeste == True:
print('Voce escapou!')
## CONDICIONAL COMPOSTA EXERCICIOS
## TRADUZA AS AFIRMACOES A SEGUIR PARA CONDICIONAIS EM PYTHON
## A - Se ano é divisível por 4, escreva: "Pode ser um ano bissexto". Caso contrário, escreva: "Definitivamente não é um ano bissexto"
## Eu verifiquei se o ano divido por 4 tem o resto igual 0, sendo assim fiz ano divido por 100 onde o resto tem que ser diferente de 0 para ser um ano bissexto
ano = 2016
if ano % 4 == 0 and ano % 100 != 0:
print('Pode ser um ano bissexto!')
else:
print('Definitivamente nao e bissexto!')
##-------------------------------
## B - Sem ambas as variaveis booleanas cima e baixo forem true, escreva: 'Decida-se', caso contrario escreva: "Voce escolheu um caminho"
cima = True
baixo = True
if cima and baixo:
print('Decida-se!')
else:
print('voce escolheu um caminho!')
##--------------------------
|
# Heap
class Solution:
def shortestPathLength(self, graph):
memo, final, q = set(), (1 << len(graph)) - 1, [(0, i, 1 << i) for i in range(len(graph))]
while q:
steps, node, state = heapq.heappop(q)
if state == final: return steps
for v in graph[node]:
if (state | 1 << v, v) not in memo:
heapq.heappush(q, (steps + 1, v, state | 1 << v))
memo.add((state | 1 << v, v))
# BFS
class Solution:
def shortestPathLength(self, graph):
memo, final, q, steps = set(), (1 << len(graph)) - 1, [(i, 1 << i) for i in range(len(graph))], 0
while True:
new = []
for node, state in q:
if state == final: return steps
for v in graph[node]:
if (state | 1 << v, v) not in memo:
new.append((v, state | 1 << v))
memo.add((state | 1 << v, v))
q = new
steps += 1
# Deque
class Solution:
def shortestPathLength(self, graph):
memo, final, q = set(), (1 << len(graph)) - 1, collections.deque([(i, 0, 1 << i) for i in range(len(graph))])
while q:
node, steps, state = q.popleft()
if state == final: return steps
for v in graph[node]:
if (state | 1 << v, v) not in memo:
q.append((v, steps + 1, state | 1 << v))
memo.add((state | 1 << v, v))
|
"""
Conf file for base_url
"""
base_url = "http://qxf2trainer.pythonanywhere.com/accounts/login/"
|
"""
link: https://leetcode-cn.com/problems/target-sum
problem: 对数组每个元素补上正负号,问共有多少种方法使得数组元素和为 S,数组长度小于20,初始数组元素和不大于1000
solution: DP。直接搜时间复杂度O(2^20) 会 TLE,性能真烂。转变成有两个选择的 01 背包问题,扫一遍记录每轮的可能的结果有哪些。
注意两个选择的结果会互相干扰,不能用 01 背包的倒序法遍历,需要另起临时数组存储每轮新的结果再换回来。
"""
class Solution:
def findTargetSumWays(self, nums: List[int], S: int) -> int:
n, res, a = len(nums), 0, sum(nums)
offset = a
if not 0 <= offset + S <= a + offset:
return 0
cnt = [0 for _ in range(a * 2 + 10)]
cnt[0 + offset] = 1
for i in range(n):
t = [0 for _ in range(a * 2 + 10)]
for j in range(-a + offset, a + offset + 1):
if cnt[j] != 0:
t[j + nums[i]] += cnt[j]
t[j - nums[i]] += cnt[j]
cnt = t
return cnt[S + offset]
|
def test_besthit():
assert False
def test_get_term():
assert False
def test_get_ancestors():
assert False
def test_search():
assert False
def test_suggest():
assert False
def test_select():
assert False
|
#
# PySNMP MIB module VISM-SESSION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/VISM-SESSION-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:27:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint")
voice, = mibBuilder.importSymbols("BASIS-MIB", "voice")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Bits, Counter64, ModuleIdentity, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Counter32, Integer32, NotificationType, ObjectIdentity, Unsigned32, MibIdentifier, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Bits", "Counter64", "ModuleIdentity", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Counter32", "Integer32", "NotificationType", "ObjectIdentity", "Unsigned32", "MibIdentifier", "Gauge32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
vismSessionGrp = MibIdentifier((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11))
class TruthValue(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("true", 1), ("false", 2))
vismSessionSetTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1), )
if mibBuilder.loadTexts: vismSessionSetTable.setStatus('mandatory')
vismSessionSetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1), ).setIndexNames((0, "VISM-SESSION-MIB", "vismSessionSetNum"))
if mibBuilder.loadTexts: vismSessionSetEntry.setStatus('mandatory')
vismSessionSetNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionSetNum.setStatus('mandatory')
vismSessionSetRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 4, 6))).clone(namedValues=NamedValues(("active", 1), ("createAndGo", 4), ("destroy", 6)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismSessionSetRowStatus.setStatus('mandatory')
vismSessionSetState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("idle", 1), ("oos", 2), ("activeIs", 3), ("standbyIs", 4), ("fullIs", 5), ("unknown", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionSetState.setStatus('mandatory')
vismSessionSetTotalGrps = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionSetTotalGrps.setStatus('mandatory')
vismSessionSetActiveGrp = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionSetActiveGrp.setStatus('mandatory')
vismSessionSetSwitchFails = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionSetSwitchFails.setStatus('mandatory')
vismSessionSetSwitchSuccesses = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionSetSwitchSuccesses.setStatus('mandatory')
vismSessionSetFaultTolerant = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 1, 1, 8), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismSessionSetFaultTolerant.setStatus('mandatory')
vismSessionGrpTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2), )
if mibBuilder.loadTexts: vismSessionGrpTable.setStatus('mandatory')
vismSessionGrpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1), ).setIndexNames((0, "VISM-SESSION-MIB", "vismSessionGrpNum"))
if mibBuilder.loadTexts: vismSessionGrpEntry.setStatus('mandatory')
vismSessionGrpNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionGrpNum.setStatus('mandatory')
vismSessionGrpSetNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismSessionGrpSetNum.setStatus('mandatory')
vismSessionGrpRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 4, 6))).clone(namedValues=NamedValues(("active", 1), ("createAndGo", 4), ("destroy", 6)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismSessionGrpRowStatus.setStatus('mandatory')
vismSessionGrpState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("idle", 1), ("oos", 2), ("is", 3), ("unknown", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionGrpState.setStatus('mandatory')
vismSessionGrpCurrSession = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionGrpCurrSession.setStatus('mandatory')
vismSessionGrpTotalSessions = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionGrpTotalSessions.setStatus('mandatory')
vismSessionGrpSwitchFails = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionGrpSwitchFails.setStatus('mandatory')
vismSessionGrpSwitchSuccesses = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismSessionGrpSwitchSuccesses.setStatus('mandatory')
vismSessionGrpMgcName = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 2, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismSessionGrpMgcName.setStatus('mandatory')
vismRudpSessionCnfTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3), )
if mibBuilder.loadTexts: vismRudpSessionCnfTable.setStatus('mandatory')
vismRudpSessionCnfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1), ).setIndexNames((0, "VISM-SESSION-MIB", "vismRudpSessionNum"))
if mibBuilder.loadTexts: vismRudpSessionCnfEntry.setStatus('mandatory')
vismRudpSessionNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionNum.setStatus('mandatory')
vismRudpSessionGrpNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionGrpNum.setStatus('mandatory')
vismRudpSessionCnfRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 4, 6))).clone(namedValues=NamedValues(("active", 1), ("createAndGo", 4), ("destroy", 6)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionCnfRowStatus.setStatus('mandatory')
vismRudpSessionPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionPriority.setStatus('mandatory')
vismRudpSessionState = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("oos", 1), ("is", 2), ("unknown", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionState.setStatus('mandatory')
vismRudpSessionCurrSession = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionCurrSession.setStatus('mandatory')
vismRudpSessionLocalIp = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 7), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionLocalIp.setStatus('mandatory')
vismRudpSessionLocalPort = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1124, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionLocalPort.setStatus('mandatory')
vismRudpSessionRmtIp = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 9), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionRmtIp.setStatus('mandatory')
vismRudpSessionRmtPort = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1124, 65535))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionRmtPort.setStatus('mandatory')
vismRudpSessionMaxWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64)).clone(32)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionMaxWindow.setStatus('mandatory')
vismRudpSessionSyncAttempts = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32)).clone(5)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionSyncAttempts.setStatus('mandatory')
vismRudpSessionMaxSegSize = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(30, 65535)).clone(384)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionMaxSegSize.setStatus('mandatory')
vismRudpSessionMaxAutoReset = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(5)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionMaxAutoReset.setStatus('mandatory')
vismRudpSessionRetransTmout = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 65535)).clone(600)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionRetransTmout.setStatus('mandatory')
vismRudpSessionMaxRetrans = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 16), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionMaxRetrans.setStatus('mandatory')
vismRudpSessionMaxCumAck = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionMaxCumAck.setStatus('mandatory')
vismRudpSessionCumAckTmout = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(100, 65535)).clone(300)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionCumAckTmout.setStatus('mandatory')
vismRudpSessionMaxOutOfSeq = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(4)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionMaxOutOfSeq.setStatus('mandatory')
vismRudpSessionNullSegTmout = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)).clone(2000)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionNullSegTmout.setStatus('mandatory')
vismRudpSessionTransStateTmout = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 21), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)).clone(2000)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionTransStateTmout.setStatus('mandatory')
vismRudpSessionType = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("backhaul", 1), ("lapdTrunking", 2))).clone('backhaul')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionType.setStatus('mandatory')
vismRudpSessionRmtGwIp = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 3, 1, 23), IpAddress()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: vismRudpSessionRmtGwIp.setStatus('mandatory')
vismRudpSessionStatTable = MibTable((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4), )
if mibBuilder.loadTexts: vismRudpSessionStatTable.setStatus('mandatory')
vismRudpSessionStatEntry = MibTableRow((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1), ).setIndexNames((0, "VISM-SESSION-MIB", "vismRudpSessionStatNum"))
if mibBuilder.loadTexts: vismRudpSessionStatEntry.setStatus('mandatory')
vismRudpSessionStatNum = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionStatNum.setStatus('mandatory')
vismRudpSessionAutoResets = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionAutoResets.setStatus('mandatory')
vismRudpSessionRcvdAutoResets = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionRcvdAutoResets.setStatus('mandatory')
vismRudpSessionRcvdInSeqs = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionRcvdInSeqs.setStatus('mandatory')
vismRudpSessionRcvdOutSeqs = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionRcvdOutSeqs.setStatus('mandatory')
vismRudpSessionSentPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionSentPackets.setStatus('mandatory')
vismRudpSessionRcvdPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionRcvdPackets.setStatus('mandatory')
vismRudpSessionSentBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionSentBytes.setStatus('mandatory')
vismRudpSessionRcvdBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionRcvdBytes.setStatus('mandatory')
vismRudpSessionDataSentPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionDataSentPkts.setStatus('mandatory')
vismRudpSessionDataRcvdPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionDataRcvdPkts.setStatus('mandatory')
vismRudpSessionDiscardPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionDiscardPkts.setStatus('mandatory')
vismRudpSessionRetransPkts = MibTableColumn((1, 3, 6, 1, 4, 1, 351, 110, 5, 5, 11, 4, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: vismRudpSessionRetransPkts.setStatus('mandatory')
mibBuilder.exportSymbols("VISM-SESSION-MIB", vismRudpSessionCnfTable=vismRudpSessionCnfTable, vismRudpSessionLocalPort=vismRudpSessionLocalPort, vismRudpSessionCnfRowStatus=vismRudpSessionCnfRowStatus, vismRudpSessionRmtPort=vismRudpSessionRmtPort, vismRudpSessionMaxAutoReset=vismRudpSessionMaxAutoReset, vismRudpSessionAutoResets=vismRudpSessionAutoResets, vismRudpSessionTransStateTmout=vismRudpSessionTransStateTmout, vismRudpSessionRetransTmout=vismRudpSessionRetransTmout, vismRudpSessionNullSegTmout=vismRudpSessionNullSegTmout, vismRudpSessionSentBytes=vismRudpSessionSentBytes, vismSessionSetNum=vismSessionSetNum, vismRudpSessionSyncAttempts=vismRudpSessionSyncAttempts, vismRudpSessionType=vismRudpSessionType, vismRudpSessionDiscardPkts=vismRudpSessionDiscardPkts, vismSessionSetState=vismSessionSetState, vismSessionGrpSwitchSuccesses=vismSessionGrpSwitchSuccesses, vismRudpSessionState=vismRudpSessionState, TruthValue=TruthValue, vismSessionGrpSetNum=vismSessionGrpSetNum, vismRudpSessionRcvdInSeqs=vismRudpSessionRcvdInSeqs, vismRudpSessionRcvdOutSeqs=vismRudpSessionRcvdOutSeqs, vismRudpSessionRetransPkts=vismRudpSessionRetransPkts, vismRudpSessionStatEntry=vismRudpSessionStatEntry, vismSessionGrp=vismSessionGrp, vismRudpSessionGrpNum=vismRudpSessionGrpNum, vismSessionSetFaultTolerant=vismSessionSetFaultTolerant, vismRudpSessionDataRcvdPkts=vismRudpSessionDataRcvdPkts, vismSessionSetRowStatus=vismSessionSetRowStatus, vismRudpSessionLocalIp=vismRudpSessionLocalIp, vismSessionGrpTotalSessions=vismSessionGrpTotalSessions, vismSessionSetTable=vismSessionSetTable, vismRudpSessionMaxOutOfSeq=vismRudpSessionMaxOutOfSeq, vismSessionGrpMgcName=vismSessionGrpMgcName, vismSessionGrpTable=vismSessionGrpTable, vismRudpSessionCnfEntry=vismRudpSessionCnfEntry, vismSessionSetSwitchSuccesses=vismSessionSetSwitchSuccesses, vismRudpSessionRcvdAutoResets=vismRudpSessionRcvdAutoResets, vismRudpSessionCumAckTmout=vismRudpSessionCumAckTmout, vismSessionSetEntry=vismSessionSetEntry, vismRudpSessionStatTable=vismRudpSessionStatTable, vismRudpSessionNum=vismRudpSessionNum, vismRudpSessionMaxWindow=vismRudpSessionMaxWindow, vismSessionGrpCurrSession=vismSessionGrpCurrSession, vismRudpSessionMaxCumAck=vismRudpSessionMaxCumAck, vismSessionSetActiveGrp=vismSessionSetActiveGrp, vismRudpSessionRcvdBytes=vismRudpSessionRcvdBytes, vismSessionGrpNum=vismSessionGrpNum, vismSessionGrpEntry=vismSessionGrpEntry, vismSessionGrpSwitchFails=vismSessionGrpSwitchFails, vismRudpSessionRmtIp=vismRudpSessionRmtIp, vismRudpSessionDataSentPkts=vismRudpSessionDataSentPkts, vismRudpSessionPriority=vismRudpSessionPriority, vismSessionSetSwitchFails=vismSessionSetSwitchFails, vismRudpSessionRcvdPackets=vismRudpSessionRcvdPackets, vismRudpSessionMaxRetrans=vismRudpSessionMaxRetrans, vismRudpSessionMaxSegSize=vismRudpSessionMaxSegSize, vismRudpSessionStatNum=vismRudpSessionStatNum, vismRudpSessionRmtGwIp=vismRudpSessionRmtGwIp, vismRudpSessionCurrSession=vismRudpSessionCurrSession, vismSessionGrpRowStatus=vismSessionGrpRowStatus, vismSessionSetTotalGrps=vismSessionSetTotalGrps, vismSessionGrpState=vismSessionGrpState, vismRudpSessionSentPackets=vismRudpSessionSentPackets)
|
"""
This module contains a function that loads previous trained classifier into the nlp unit.
"""
def loadClassif(nlp, app_path):
"""
This function loads the already trained classifier into the nlp unit.
If the classifier does not yet exist, it will be trained as part of this function.
Input:
nlp: nlp unit
app_path: path to chatbot app
Returns:
Nothing.
"""
nlp.build()
# loading domain classifier
dc = nlp.domain_classifier
dc.load(app_path+"/models/domain_model.pkl")
# loading intent classifier
for domain in nlp.domains:
clf = nlp.domains[domain].intent_classifier
try:
clf.load(app_path + "/models/domain_" + domain + "_intent_model.pkl")
except:
nlp.domains[domain].intent_classifier.fit()
# loading entity recognizer
for domain in nlp.domains:
for intent in nlp.domains[domain].intents:
nlp.domains[domain].intents[intent].build()
if nlp.domains[domain].intents[intent].entities != {}:
er = nlp.domains[domain].intents[intent].entity_recognizer
er.load(app_path + '/models/domain_' + domain + '_intent_' + intent + '_entity_recognizer.pkl')
|
#---------------------------------
# PIPELINE RUN
#---------------------------------
# The configuration settings to run the pipeline. These options are overwritten
# if a new setting is specified as an argument when running the pipeline.
# These settings include:
# - logDir: The directory where the batch queue scripts are stored, along with
# stdout and stderr dumps after the job is run.
# - logFile: Log file in logDir which all commands submitted are stored.
# - style: the style which the pipeline runs in. One of:
# - 'print': prints the stages which will be run to stdout,
# - 'run': runs the pipeline until the specified stages are finished, and
# - 'flowchart': outputs a flowchart of the pipeline stages specified and
# their dependencies.
# - procs: the number of python processes to run simultaneously. This
# determines the maximum parallelism of the pipeline. For distributed jobs
# it also constrains the maximum total jobs submitted to the queue at any one
# time.
# - verbosity: one of 0 (quiet), 1 (normal), 2 (chatty).
# - end: the desired tasks to be run. Rubra will also run all tasks which are
# dependencies of these tasks.
# - force: tasks which will be forced to run, regardless of timestamps.
# - rebuild: one of 'fromstart','fromend'. Whether to calculate which
# dependencies will be rerun by working back from an end task to the latest
# up-to-date task, or forward from the earliest out-of-date task. 'fromstart'
# is the most conservative and commonly used as it brings all intermediate
# tasks up to date.
# - manager: "pbs" or "slurm"
pipeline = {
"logDir": "log",
"logFile": "pipeline_commands.log",
"style": "print",
"procs": 16,
"verbose": 2,
"end": ["fastQCSummary", "voom", "edgeR", "qcSummary"],
"force": [],
"rebuild": "fromstart",
"manager": "slurm",
}
# This option specifies whether or not you are using VLSCI's Merri or Barcoo
# cluster. If True, this changes java's tmpdir to the job's tmp dir on
# /scratch ($TMPDIR) instead of using the default /tmp which has limited space.
using_merri = True
# Optional parameter governing how Ruffus determines which part of the
# pipeline is out-of-date and needs to be re-run. If set to False, Ruffus
# will work back from the end target tasks and only execute the pipeline
# after the first up-to-date tasks that it encounters.
# Warning: Use with caution! If you don't understand what this option does,
# keep this option as True.
maximal_rebuild_mode = True
#---------------------------------
# CONFIG
#---------------------------------
# Name of analysis. Changing the name will create new sub-directories for
# voom, edgeR, and cuffdiff analysis.
analysis_name = "analysis_v1"
# The directory containing *.fastq.gz read files.
raw_seq_dir = "/path_to_project/fastq_files/"
# Path to the CSV file with sample information regarding condition and
# covariates if available.
samples_csv = "/path_to_project/fastq_files/samples.csv"
# Path to the CSV file with which comparisons to make.
comparisons_csv = "/path_to_project/fastq_files/comparisons.csv"
# The output directory.
output_dir = "/path_to_project/results/"
# Sequencing platform for read group information.
platform = "Illumina"
# If the experiment is paired-end or single-end: True (PE) or False (SE).
paired_end = False
# Whether the experiment is strand specific: "yes", "no", or "reverse".
stranded = "no"
#---------------------------------
# REFERENCE FILES
#---------------------------------
# Most reference files can be obtained from the Illumina iGenomes project:
# http://cufflinks.cbcb.umd.edu/igenomes.html
# Bowtie 2 index files: *.1.bt2, *.2.bt2, *.3.bt2, *.4.bt2, *.rev.1.bt2,
# *.rev.2.bt2.
genome_ref = "/vlsci/VR0002/shared/Reference_Files/Indexed_Ref_Genomes/bowtie_Indexed/human_g1k_v37"
# Genome reference FASTA. Also needs an indexed genome (.fai) and dictionary
# (.dict) file in the same directory.
genome_ref_fa = "/vlsci/VR0002/shared/Reference_Files/Indexed_Ref_Genomes/bowtie_Indexed/human_g1k_v37.fa"
# Gene set reference file (.gtf). Recommend using the GTF file obtained from
# Ensembl as Ensembl gene IDs are used for annotation (if specified).
gene_ref = "/vlsci/VR0002/shared/Reference_Files/Indexed_Ref_Genomes/TuxedoSuite_Ref_Files/Homo_sapiens/Ensembl/GRCh37/Annotation/Genes/genes.gtf"
# Either a rRNA reference fasta (ending in .fasta or .fa) or an GATK interval
# file (ending in .list) containing rRNA intervals to calculate the rRNA
# content. Can set as False if not available.
# rrna_ref = "/vlsci/VR0002/shared/Reference_Files/rRNA/human_all_rRNA.fasta"
rrna_ref = "/vlsci/VR0002/shared/jchung/human_reference_files/human_rRNA.list"
# Optional tRNA and rRNA sequences to filter out in Cuffdiff (.gtf or .gff).
# Set as False if not provided.
cuffdiff_mask_file = False
#---------------------------------
# TRIMMOMATIC PARAMETERS
#---------------------------------
# Parameters for Trimmomatic (a tool for trimming Illumina reads).
# http://www.usadellab.org/cms/index.php?page=trimmomatic
# Path of a FASTA file containing adapter sequences used in sequencing.
adapter_seq = "/vlsci/VR0002/shared/jchung/human_reference_files/TruSeqAdapters.fa"
# The maximum mismatch count which will still allow a full match to be
# performed.
seed_mismatches = 2
# How accurate the match between the two 'adapter ligated' reads must be for
# PE palindrome read alignment.
palendrome_clip_threshold = 30
# How accurate the match between any adapter etc. sequence must be against a
# read.
simple_clip_threshold = 10
# The minimum quality needed to keep a base and the minimum length of reads to
# be kept.
extra_parameters = "LEADING:3 TRAILING:3 SLIDINGWINDOW:4:15 MINLEN:36"
# Output Trimmomatic log file
write_trimmomatic_log = True
#---------------------------------
# R PARAMETERS
#---------------------------------
# Get annotations from Ensembl BioMart. GTF file needs to use IDs from Ensembl.
# Set as False to skip annotation, else
# provide the name of the dataset that will be queried. Attributes to be
# obtained include gene symbol, chromosome name, description, and gene biotype.
# Commonly used datasets:
# human: "hsapiens_gene_ensembl"
# mouse: "mmusculus_gene_ensembl"
# rat: "rnorvegicus_gene_ensembl"
# You can list all available datasets in R by using the listDatasets fuction:
# > library(biomaRt)
# > listDatasets(useMart("ensembl"))
# The gene symbol is obtained from the attribute "hgnc_symbol" (human) or
# "mgi_symbol" (mice/rats) if available. If not, the "external_gene_id" is used
# to obtain the gene symbol. You can change this by editing the script:
# scripts/combine_and_annotate.r
annotation_dataset = "hsapiens_gene_ensembl"
#---------------------------------
# SCRIPT PATHS
#---------------------------------
# Paths to other wrapper scripts needed to run the pipeline. Make sure these
# paths are relative to the directory where you plan to run the pipeline in or
# change them to absolute paths.
html_index_script = "scripts/html_index.py"
index_script = "scripts/build_index.sh"
tophat_script = "scripts/run_tophat.sh"
merge_tophat_script = "scripts/merge_tophat.sh"
fix_tophat_unmapped_reads_script = "scripts/fix_tophat_unmapped_reads.py"
htseq_script = "scripts/run_htseq.sh"
fastqc_parse_script = "scripts/fastqc_parse.py"
qc_parse_script = "scripts/qc_parse.py"
alignment_stats_script = "scripts/alignment_stats.sh"
combine_and_annotate_script = "scripts/combine_and_annotate.R"
de_analysis_script = "scripts/de_analysis.R"
#---------------------------------
# PROGRAM PATHS
#---------------------------------
trimmomatic_path = "/usr/local/trimmomatic/0.30/trimmomatic-0.30.jar"
reorder_sam_path = "/usr/local/picard/1.69/lib/ReorderSam.jar"
mark_duplicates_path = "/usr/local/picard/1.69/lib/MarkDuplicates.jar"
rnaseqc_path = "/usr/local/rnaseqc/1.1.7/RNA-SeQC_v1.1.7.jar"
add_or_replace_read_groups_path = "/usr/local/picard/1.69/lib/AddOrReplaceReadGroups.jar"
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
t = int(input())
def num_glowing(n, primes):
if len(primes) == 0:
return 0
p = primes[0]
m = n // p
ps = primes[1:]
return m + num_glowing(n, ps) - num_glowing(m, ps)
for _ in range(t):
s = input()
k = int(input())
switches = []
for i in range(len(s)):
if s[i] == '1':
switches.append(i + 1)
left = 1
right = 40 * k
u = 0
v = num_glowing(right, switches)
while left + 1 < right:
mid = (left * (v - k) + right * (k - u)) // (v - u)
if mid <= left:
mid += 1
if mid >= right:
mid -= 1
x = num_glowing(mid, switches)
if x >= k:
right = mid
v = x
else:
left = mid
u = x
print(right)
|
class DesignOpt:
def __init__(mesh, dofManager, quadRule):
self.mesh = mesh
self.dofManager = dofManager
self.quadRule = quadRule
|
__author__ = 'rhoerbe' #2013-09-05
# Entity Categories specifying the PVP eGov Token as of "PVP2-Allgemein V2.1.0", http://www.ref.gv.at/
EGOVTOKEN = ["PVP-VERSION",
"PVP-PRINCIPAL-NAME",
"PVP-GIVENNAME",
"PVP-BIRTHDATE",
"PVP-USERID",
"PVP-GID",
"PVP-BPK",
"PVP-MAIL",
"PVP-TEL",
"PVP-PARTICIPANT-ID",
"PVP-PARTICIPANT-OKZ",
"PVP-OU-OKZ",
"PVP-OU",
"PVP-OU-GV-OU-ID",
"PVP-FUNCTION",
"PVP-ROLES",
]
CHARGEATTR = ["PVP-INVOICE-RECPT-ID",
"PVP-COST-CENTER-ID",
"PVP-CHARGE-CODE",
]
# all eGov Token attributes except (1) transaction charging and (2) chaining
PVP2 = "http://www.ref.gv.at/ns/names/agiz/pvp/egovtoken"
# transaction charging extension
PVP2CHARGE = "http://www.ref.gv.at/ns/names/agiz/pvp/egovtoken-charge"
RELEASE = {
PVP2: EGOVTOKEN,
PVP2CHARGE: CHARGEATTR,
}
|
# Даны два момента времени в пределах одних и тех же суток. Для каждого момента указан час,
# минута и секунда. Известно, что второй момент времени наступил не раньше первого.
# Определите сколько секунд прошло между двумя моментами времени.
h1 = int(input())
m1 = int(input())
s1 = int(input())
h2 = int(input())
m2 = int(input())
s2 = int(input())
print(((h2 - h1) * 3600) + ((m2 - m1) * 60) + (s2 - s1))
|
# classes for inline and reply keyboards
class InlineButton:
def __init__(self, text_, callback_data_ = "", url_=""):
self.text = text_
self.callback_data = callback_data_
self.url = url_
if not self.callback_data and not self.url:
raise TypeError("Either callback_data or url must be given")
def __str__(self):
return str(self.toDict())
def toDict(self):
return self.__dict__
class KeyboardButton:
def __init__(self, text_):
self.text = text_
def __str__(self):
return str(self.toDict())
def toDict(self):
return self.__dict__
class ButtonList:
def __init__(self, button_type_: type, button_list_: list = []):
self.__button_type = None
self.__button_type_str = ""
self.__button_list = []
if button_type_ == InlineButton:
self.__button_type = button_type_
self.__button_type_str = "inline"
elif button_type_ == KeyboardButton:
self.__button_type = button_type_
self.__button_type_str = "keyboard"
else:
raise TypeError(
"given button_type is not type InlineButton or KeyboardButton")
if button_list_:
for element in button_list_:
if isinstance(element, self.__button_type):
self.__button_list.append(element)
def __str__(self):
return str(self.toDict())
def toDict(self):
return [button.toDict() for button in self.__button_list]
def addCommand(self, button_):
if isinstance(button_, self.__button_type):
self.__button_list.append(button_)
def bulkAddCommands(self, button_list: list):
for element in button_list:
if isinstance(element, self.__button_type):
self.__button_list.append(element)
def getButtonType(self):
return self.__button_type
def toBotDict(self, special_button: type = None, column_count: int = 3):
button_list = []
button_row = []
for button in self.__button_list:
button_row.append(button.toDict())
if len(button_row) >= column_count or button == self.__button_list[-1]:
button_list.append(button_row[:])
button_row.clear()
if special_button and isinstance(special_button, self.__button_type):
button_list.append([special_button.toDict()])
return {f'{"inline_" if self.__button_type_str == "inline" else ""}keyboard': button_list}
|
def rank4_simple(a, b):
assert a.shape == b.shape
da, db, dc, dd = a.shape
s = 0
for iia in range(da):
for iib in range(db):
for iic in range(dc):
for iid in range(dd):
s += a[iia, iib, iic, iid] * b[iia, iib, iic, iid]
return s
|
#
# PySNMP MIB module CNTEXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CNTEXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:25:29 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)
#
cntExt, = mibBuilder.importSymbols("APENT-MIB", "cntExt")
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter64, NotificationType, Gauge32, ObjectIdentity, TimeTicks, IpAddress, MibIdentifier, Bits, ModuleIdentity, Unsigned32, iso, Counter32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "NotificationType", "Gauge32", "ObjectIdentity", "TimeTicks", "IpAddress", "MibIdentifier", "Bits", "ModuleIdentity", "Unsigned32", "iso", "Counter32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, RowStatus, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "DisplayString")
apCntExtMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 2467, 1, 16, 1))
if mibBuilder.loadTexts: apCntExtMib.setLastUpdated('9710092000Z')
if mibBuilder.loadTexts: apCntExtMib.setOrganization('ArrowPoint Communications Inc.')
if mibBuilder.loadTexts: apCntExtMib.setContactInfo(' Postal: ArrowPoint Communications Inc. 50 Nagog Park Acton, Massachusetts 01720 Tel: +1 978-206-3000 option 1 E-Mail: support@arrowpoint.com')
if mibBuilder.loadTexts: apCntExtMib.setDescription('The MIB module used to describe the ArrowPoint Communications content rule table')
apCntRuleOrder = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("hierarchicalFirst", 0), ("cacheRuleFirst", 1))).clone('cacheRuleFirst')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: apCntRuleOrder.setStatus('current')
if mibBuilder.loadTexts: apCntRuleOrder.setDescription('Affects which ruleset is consulted first when categorizing flows')
apCntTable = MibTable((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4), )
if mibBuilder.loadTexts: apCntTable.setStatus('current')
if mibBuilder.loadTexts: apCntTable.setDescription('A list of content rule entries.')
apCntEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1), ).setIndexNames((0, "CNTEXT-MIB", "apCntOwner"), (0, "CNTEXT-MIB", "apCntName"))
if mibBuilder.loadTexts: apCntEntry.setStatus('current')
if mibBuilder.loadTexts: apCntEntry.setDescription('A group of information to uniquely identify a content providing service.')
apCntOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntOwner.setStatus('current')
if mibBuilder.loadTexts: apCntOwner.setDescription('The name of the contents administrative owner.')
apCntName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntName.setStatus('current')
if mibBuilder.loadTexts: apCntName.setDescription('The name of the content providing service.')
apCntIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntIndex.setStatus('current')
if mibBuilder.loadTexts: apCntIndex.setDescription('The unique service index assigned to the name by the SCM.')
apCntIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 4), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntIPAddress.setStatus('current')
if mibBuilder.loadTexts: apCntIPAddress.setDescription('The IP Address the of the content providing service.')
apCntIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 6, 17))).clone(namedValues=NamedValues(("any", 0), ("tcp", 6), ("udp", 17))).clone('any')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntIPProtocol.setStatus('current')
if mibBuilder.loadTexts: apCntIPProtocol.setDescription('The IP Protocol the of the content providing service.')
apCntPort = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntPort.setStatus('current')
if mibBuilder.loadTexts: apCntPort.setDescription('The UDP or TCP port of the content providing service.')
apCntUrl = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 7), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntUrl.setStatus('current')
if mibBuilder.loadTexts: apCntUrl.setDescription('The name of the content providing service.')
apCntSticky = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("none", 1), ("ssl", 2), ("cookieurl", 3), ("url", 4), ("cookies", 5), ("sticky-srcip-dstport", 6), ("sticky-srcip", 7), ("arrowpoint-cookie", 8))).clone('none')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntSticky.setStatus('current')
if mibBuilder.loadTexts: apCntSticky.setDescription('The sticky attribute controls whether source addresses stick to a server once they go to it initially based on load balancing.')
apCntBalance = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("roundrobin", 1), ("aca", 2), ("destip", 3), ("srcip", 4), ("domain", 5), ("url", 6), ("leastconn", 7), ("weightedrr", 8), ("domainhash", 9), ("urlhash", 10))).clone('roundrobin')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntBalance.setStatus('current')
if mibBuilder.loadTexts: apCntBalance.setDescription('The load distribution algorithm to use for this content.')
apCntQOSTag = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7)).clone(7)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntQOSTag.setStatus('current')
if mibBuilder.loadTexts: apCntQOSTag.setDescription('The QOS tag to associate with this content definition.')
apCntEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntEnable.setStatus('current')
if mibBuilder.loadTexts: apCntEnable.setDescription('The state of the service, either enable or disabled')
apCntRedirect = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 12), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntRedirect.setStatus('current')
if mibBuilder.loadTexts: apCntRedirect.setDescription('Where to 302 redirect any requests for this content')
apCntDrop = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 13), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntDrop.setStatus('current')
if mibBuilder.loadTexts: apCntDrop.setDescription('Specify that requests for this content receive a 404 message and the txt to include')
apCntSize = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535)).clone(4000)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntSize.setStatus('obsolete')
if mibBuilder.loadTexts: apCntSize.setDescription('This object is obsolete.')
apCntPersistence = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntPersistence.setStatus('current')
if mibBuilder.loadTexts: apCntPersistence.setDescription('Controls whether each GET is inspected individuallly or else GETs may be pipelined on a single persistent TCP connection')
apCntAuthor = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 16), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntAuthor.setStatus('current')
if mibBuilder.loadTexts: apCntAuthor.setDescription('The name of the author of this content rule.')
apCntSpider = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntSpider.setStatus('current')
if mibBuilder.loadTexts: apCntSpider.setDescription('Controls whether the content will be spidered at rule activation time.')
apCntHits = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 18), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntHits.setStatus('current')
if mibBuilder.loadTexts: apCntHits.setDescription('Number of times user request was detected which invoked this content rule.')
apCntRedirects = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 19), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntRedirects.setStatus('current')
if mibBuilder.loadTexts: apCntRedirects.setDescription('Number of times this content rule caused a redirect request.')
apCntDrops = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 20), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntDrops.setStatus('current')
if mibBuilder.loadTexts: apCntDrops.setDescription('Number of times this content rule was unable to establish a connection.')
apCntRejNoServices = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 21), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntRejNoServices.setStatus('current')
if mibBuilder.loadTexts: apCntRejNoServices.setDescription('Number of times this content rule rejected a connection for want of a service.')
apCntRejServOverload = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 22), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntRejServOverload.setStatus('current')
if mibBuilder.loadTexts: apCntRejServOverload.setDescription('Number of times this content rule rejected a connection because of overload on the designated service(s).')
apCntSpoofs = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 23), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntSpoofs.setStatus('current')
if mibBuilder.loadTexts: apCntSpoofs.setDescription('Number of times a connection was created using this content rule.')
apCntNats = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 24), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntNats.setStatus('current')
if mibBuilder.loadTexts: apCntNats.setDescription('Number of times network address translation was performed using this content rule.')
apCntByteCount = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 25), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntByteCount.setStatus('current')
if mibBuilder.loadTexts: apCntByteCount.setDescription('Total number of bytes passed using this content rule.')
apCntFrameCount = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 26), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntFrameCount.setStatus('current')
if mibBuilder.loadTexts: apCntFrameCount.setDescription('Total number of frames passed using this content rule.')
apCntZeroButton = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 27), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntZeroButton.setStatus('current')
if mibBuilder.loadTexts: apCntZeroButton.setDescription('Number of time counters for this content rule have been zeroed.')
apCntHotListEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntHotListEnabled.setStatus('current')
if mibBuilder.loadTexts: apCntHotListEnabled.setDescription('Controls whether a hotlist will be maintained for this content rule.')
apCntHotListSize = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 29), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 100)).clone(10)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntHotListSize.setStatus('current')
if mibBuilder.loadTexts: apCntHotListSize.setDescription('Total number of hotlist entries which will be maintainted for this rule.')
apCntHotListThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 30), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntHotListThreshold.setStatus('current')
if mibBuilder.loadTexts: apCntHotListThreshold.setDescription('The threshold under which an item is not considered hot.')
apCntHotListType = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0))).clone(namedValues=NamedValues(("hitCount", 0))).clone('hitCount')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntHotListType.setStatus('current')
if mibBuilder.loadTexts: apCntHotListType.setDescription('Configures how a determination of hotness will be done.')
apCntHotListInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 32), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 60)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntHotListInterval.setStatus('current')
if mibBuilder.loadTexts: apCntHotListInterval.setDescription('The interval in units of minutes used to refreshing the hot list.')
apCntFlowTrack = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('disable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntFlowTrack.setStatus('current')
if mibBuilder.loadTexts: apCntFlowTrack.setDescription('Controls whether arrowflow reporting will be done for this content rule.')
apCntWeightMask = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 34), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 8))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntWeightMask.setStatus('current')
if mibBuilder.loadTexts: apCntWeightMask.setDescription('This object specifies a bitmask used to determine the type of metric to be used for load balancing.')
apCntStickyMask = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 35), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyMask.setStatus('current')
if mibBuilder.loadTexts: apCntStickyMask.setDescription('This object specifies the sticky mask used to determine the portion of the IP Address which denotes stickness between the server and client.')
apCntCookieStartPos = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 36), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 600)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntCookieStartPos.setStatus('current')
if mibBuilder.loadTexts: apCntCookieStartPos.setDescription('This object specifies the start of a cookie.')
apCntHeuristicCookieFence = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 37), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)).clone(100)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntHeuristicCookieFence.setStatus('current')
if mibBuilder.loadTexts: apCntHeuristicCookieFence.setDescription('This object specifies the end of a Heuristic Cookie Fence.')
apCntEqlName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 38), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntEqlName.setStatus('current')
if mibBuilder.loadTexts: apCntEqlName.setDescription('The name of the EQL associated with this content rule')
apCntCacheFalloverType = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 39), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("linear", 1), ("next", 2), ("bypass", 3))).clone('linear')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntCacheFalloverType.setStatus('current')
if mibBuilder.loadTexts: apCntCacheFalloverType.setDescription('The type of fallover to use with division balancing')
apCntLocalLoadThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 40), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 254)).clone(254)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntLocalLoadThreshold.setStatus('current')
if mibBuilder.loadTexts: apCntLocalLoadThreshold.setDescription('Redirect services are preferred when all local services exceed this thrreshold.')
apCntStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 41), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStatus.setStatus('current')
if mibBuilder.loadTexts: apCntStatus.setDescription('Status entry for this row ')
apCntRedirectLoadThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 42), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(255)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntRedirectLoadThreshold.setStatus('current')
if mibBuilder.loadTexts: apCntRedirectLoadThreshold.setDescription('Redirect services are eligible when their load is below this thrreshold.')
apCntContentType = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 43), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("http", 1), ("ftp-control", 2), ("realaudio-control", 3), ("ssl", 4), ("bypass", 5), ("ftp-publish", 6))).clone('http')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntContentType.setStatus('current')
if mibBuilder.loadTexts: apCntContentType.setDescription('The type of flow associated with this rule')
apCntStickyInactivity = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 44), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyInactivity.setStatus('current')
if mibBuilder.loadTexts: apCntStickyInactivity.setDescription('The maximun inactivity on a sticky connection (in minutes)')
apCntDNSBalance = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 45), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("preferlocal", 1), ("roundrobin", 2), ("useownerdnsbalance", 3), ("leastloaded", 4))).clone('useownerdnsbalance')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntDNSBalance.setStatus('current')
if mibBuilder.loadTexts: apCntDNSBalance.setDescription('The DNS distribution algorithm to use for this content rule.')
apCntStickyGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 46), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 65535))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyGroup.setStatus('current')
if mibBuilder.loadTexts: apCntStickyGroup.setDescription('The sticky group number of a rule, 0 means not being used')
apCntAppTypeBypasses = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 47), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntAppTypeBypasses.setStatus('current')
if mibBuilder.loadTexts: apCntAppTypeBypasses.setDescription('Total number of frames bypassed directly by matching this content rule.')
apCntNoSvcBypasses = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 48), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntNoSvcBypasses.setStatus('current')
if mibBuilder.loadTexts: apCntNoSvcBypasses.setDescription('Total number of frames bypassed due to no services available on this content rule.')
apCntSvcLoadBypasses = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 49), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntSvcLoadBypasses.setStatus('current')
if mibBuilder.loadTexts: apCntSvcLoadBypasses.setDescription('Total number of frames bypassed due to overloaded services on this content rule.')
apCntConnCtBypasses = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 50), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntConnCtBypasses.setStatus('current')
if mibBuilder.loadTexts: apCntConnCtBypasses.setDescription('Total number of frames bypassed due to connection count on this content rule.')
apCntUrqlTblName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 51), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntUrqlTblName.setStatus('current')
if mibBuilder.loadTexts: apCntUrqlTblName.setDescription('The name of the URQL table associated with this content rule')
apCntStickyStrPre = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 52), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyStrPre.setStatus('current')
if mibBuilder.loadTexts: apCntStickyStrPre.setDescription('The string prefix for sticky string operation')
apCntStickyStrEos = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 53), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 5))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyStrEos.setStatus('current')
if mibBuilder.loadTexts: apCntStickyStrEos.setDescription('The End-Of-String characters')
apCntStickyStrSkipLen = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 54), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyStrSkipLen.setStatus('current')
if mibBuilder.loadTexts: apCntStickyStrSkipLen.setDescription('The number of bytes to be skipped before sticky operation')
apCntStickyStrProcLen = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 55), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyStrProcLen.setStatus('current')
if mibBuilder.loadTexts: apCntStickyStrProcLen.setDescription('The number of bytes to be processed by the string action')
apCntStickyStrAction = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 56), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("hash-a", 1), ("hash-xor", 2), ("hash-crc32", 3), ("match-service-cookie", 4))).clone('match-service-cookie')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyStrAction.setStatus('current')
if mibBuilder.loadTexts: apCntStickyStrAction.setDescription('The sticky operation to be applied on the sticky cookie/string')
apCntStickyStrAsciiConv = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 57), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyStrAsciiConv.setStatus('current')
if mibBuilder.loadTexts: apCntStickyStrAsciiConv.setDescription('To convert the escaped ASCII code to its char in sticky string')
apCntPrimarySorryServer = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 58), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntPrimarySorryServer.setStatus('current')
if mibBuilder.loadTexts: apCntPrimarySorryServer.setDescription('The last chance server which will be chosen if all other servers fail')
apCntSecondSorryServer = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 59), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntSecondSorryServer.setStatus('current')
if mibBuilder.loadTexts: apCntSecondSorryServer.setDescription('The backup for the primary sorry server')
apCntPrimarySorryHits = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 60), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntPrimarySorryHits.setStatus('current')
if mibBuilder.loadTexts: apCntPrimarySorryHits.setDescription('Total number of hits to the primary sorry server')
apCntSecondSorryHits = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 61), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntSecondSorryHits.setStatus('current')
if mibBuilder.loadTexts: apCntSecondSorryHits.setDescription('Total number of hits to the secondary sorry server')
apCntStickySrvrDownFailover = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 62), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("reject", 1), ("redirect", 2), ("balance", 3), ("sticky-srcip", 4), ("sticky-srcip-dstport", 5))).clone('balance')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickySrvrDownFailover.setStatus('current')
if mibBuilder.loadTexts: apCntStickySrvrDownFailover.setDescription('The failover mechanism used when sticky server is not active')
apCntStickyStrType = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 63), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("cookieurl", 1), ("url", 2), ("cookies", 3))).clone('cookieurl')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyStrType.setStatus('current')
if mibBuilder.loadTexts: apCntStickyStrType.setDescription('The type of string that strig criteria applies to')
apCntParamBypass = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 64), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntParamBypass.setStatus('current')
if mibBuilder.loadTexts: apCntParamBypass.setDescription("Specifies that content requests which contain the special terminators '?' or '#' indicating arguments in the request are to bypass transparent caches and are to be sent directly to the origin server.")
apCntAvgLocalLoad = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 65), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntAvgLocalLoad.setStatus('current')
if mibBuilder.loadTexts: apCntAvgLocalLoad.setDescription('The currently sensed average load for all local services under this rule')
apCntAvgRemoteLoad = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 66), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntAvgRemoteLoad.setStatus('current')
if mibBuilder.loadTexts: apCntAvgRemoteLoad.setDescription('The currently sensed average load for all remote services under this rule')
apCntDqlName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 67), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntDqlName.setStatus('current')
if mibBuilder.loadTexts: apCntDqlName.setDescription('The name of the DQL table associated with this content rule')
apCntIPAddressRange = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 68), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)).clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntIPAddressRange.setStatus('current')
if mibBuilder.loadTexts: apCntIPAddressRange.setDescription('The range of IP Addresses of the content providing service.')
apCntTagListName = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 69), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntTagListName.setStatus('current')
if mibBuilder.loadTexts: apCntTagListName.setDescription('The name of the tag list to be used with this content rule')
apCntStickyNoCookieAction = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 70), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("loadbalance", 1), ("reject", 2), ("redirect", 3), ("service", 4))).clone('loadbalance')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyNoCookieAction.setStatus('current')
if mibBuilder.loadTexts: apCntStickyNoCookieAction.setDescription('The action to be taken when no cookie found with sticky cookie config.')
apCntStickyNoCookieString = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 71), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyNoCookieString.setStatus('current')
if mibBuilder.loadTexts: apCntStickyNoCookieString.setDescription('The String used by sticky no cookie redirect action')
apCntStickyCookiePath = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 72), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 99))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyCookiePath.setStatus('current')
if mibBuilder.loadTexts: apCntStickyCookiePath.setDescription('The value to be used as the Cookie Path Attribute.')
apCntStickyCookieExp = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 73), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(11, 11)).setFixedLength(11)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyCookieExp.setStatus('current')
if mibBuilder.loadTexts: apCntStickyCookieExp.setDescription('The value to be used as the Cookie Experation Attribute. Format - dd:hh:mm:ss')
apCntStickyCacheExp = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 74), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 60)).clone(3)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntStickyCacheExp.setStatus('current')
if mibBuilder.loadTexts: apCntStickyCacheExp.setDescription('The value used to time out entries in the Cookie Cache.')
apCntTagWeight = MibTableColumn((1, 3, 6, 1, 4, 1, 2467, 1, 16, 4, 1, 75), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1024))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: apCntTagWeight.setStatus('current')
if mibBuilder.loadTexts: apCntTagWeight.setDescription('The weight assigned to the rule using header-field-group.')
apCntAclBypassCt = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntAclBypassCt.setStatus('current')
if mibBuilder.loadTexts: apCntAclBypassCt.setDescription('Total number of frames bypassed due to ACL restrictions.')
apCntNoRuleBypassCt = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntNoRuleBypassCt.setStatus('current')
if mibBuilder.loadTexts: apCntNoRuleBypassCt.setDescription('Total number of frames bypassed due to no rule matches.')
apCntCacheMissBypassCt = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntCacheMissBypassCt.setStatus('current')
if mibBuilder.loadTexts: apCntCacheMissBypassCt.setDescription('Total number of frames bypassed due to returning from a transparent cache.')
apCntGarbageBypassCt = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntGarbageBypassCt.setStatus('current')
if mibBuilder.loadTexts: apCntGarbageBypassCt.setDescription('Total number of frames bypassed due to unknown info found in the URL.')
apCntUrlParamsBypassCt = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: apCntUrlParamsBypassCt.setStatus('current')
if mibBuilder.loadTexts: apCntUrlParamsBypassCt.setDescription('Total number of frames bypassed due to paramters found in the URL.')
apCntBypassConnectionPersistence = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: apCntBypassConnectionPersistence.setStatus('current')
if mibBuilder.loadTexts: apCntBypassConnectionPersistence.setDescription('Affects which ruleset is consulted first when categorizing flows')
apCntPersistenceResetMethod = MibScalar((1, 3, 6, 1, 4, 1, 2467, 1, 16, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("redirect", 0), ("remap", 1))).clone('redirect')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: apCntPersistenceResetMethod.setStatus('current')
if mibBuilder.loadTexts: apCntPersistenceResetMethod.setDescription('Affects which ruleset is consulted first when categorizing flows')
mibBuilder.exportSymbols("CNTEXT-MIB", apCntHits=apCntHits, apCntSecondSorryHits=apCntSecondSorryHits, apCntSpoofs=apCntSpoofs, apCntStickyNoCookieString=apCntStickyNoCookieString, apCntStickyMask=apCntStickyMask, apCntCacheFalloverType=apCntCacheFalloverType, apCntName=apCntName, apCntHotListInterval=apCntHotListInterval, apCntUrlParamsBypassCt=apCntUrlParamsBypassCt, apCntStickyStrEos=apCntStickyStrEos, PYSNMP_MODULE_ID=apCntExtMib, apCntCacheMissBypassCt=apCntCacheMissBypassCt, apCntRedirectLoadThreshold=apCntRedirectLoadThreshold, apCntSpider=apCntSpider, apCntAuthor=apCntAuthor, apCntAppTypeBypasses=apCntAppTypeBypasses, apCntExtMib=apCntExtMib, apCntStickyStrAsciiConv=apCntStickyStrAsciiConv, apCntStickyCookiePath=apCntStickyCookiePath, apCntStickyStrPre=apCntStickyStrPre, apCntIPAddressRange=apCntIPAddressRange, apCntIPProtocol=apCntIPProtocol, apCntTable=apCntTable, apCntStickyNoCookieAction=apCntStickyNoCookieAction, apCntStickyCacheExp=apCntStickyCacheExp, apCntPrimarySorryServer=apCntPrimarySorryServer, apCntCookieStartPos=apCntCookieStartPos, apCntPrimarySorryHits=apCntPrimarySorryHits, apCntAclBypassCt=apCntAclBypassCt, apCntRejServOverload=apCntRejServOverload, apCntHotListThreshold=apCntHotListThreshold, apCntUrl=apCntUrl, apCntDrops=apCntDrops, apCntSvcLoadBypasses=apCntSvcLoadBypasses, apCntEnable=apCntEnable, apCntFrameCount=apCntFrameCount, apCntSize=apCntSize, apCntEqlName=apCntEqlName, apCntWeightMask=apCntWeightMask, apCntPersistence=apCntPersistence, apCntStickyGroup=apCntStickyGroup, apCntSecondSorryServer=apCntSecondSorryServer, apCntStickyStrAction=apCntStickyStrAction, apCntHotListType=apCntHotListType, apCntParamBypass=apCntParamBypass, apCntQOSTag=apCntQOSTag, apCntGarbageBypassCt=apCntGarbageBypassCt, apCntConnCtBypasses=apCntConnCtBypasses, apCntRedirect=apCntRedirect, apCntEntry=apCntEntry, apCntNats=apCntNats, apCntStickyInactivity=apCntStickyInactivity, apCntPort=apCntPort, apCntNoRuleBypassCt=apCntNoRuleBypassCt, apCntHeuristicCookieFence=apCntHeuristicCookieFence, apCntStatus=apCntStatus, apCntZeroButton=apCntZeroButton, apCntRejNoServices=apCntRejNoServices, apCntIPAddress=apCntIPAddress, apCntFlowTrack=apCntFlowTrack, apCntContentType=apCntContentType, apCntBypassConnectionPersistence=apCntBypassConnectionPersistence, apCntRuleOrder=apCntRuleOrder, apCntAvgRemoteLoad=apCntAvgRemoteLoad, apCntDrop=apCntDrop, apCntStickyStrProcLen=apCntStickyStrProcLen, apCntSticky=apCntSticky, apCntStickyStrSkipLen=apCntStickyStrSkipLen, apCntStickyStrType=apCntStickyStrType, apCntLocalLoadThreshold=apCntLocalLoadThreshold, apCntOwner=apCntOwner, apCntTagListName=apCntTagListName, apCntNoSvcBypasses=apCntNoSvcBypasses, apCntDqlName=apCntDqlName, apCntDNSBalance=apCntDNSBalance, apCntRedirects=apCntRedirects, apCntByteCount=apCntByteCount, apCntStickySrvrDownFailover=apCntStickySrvrDownFailover, apCntTagWeight=apCntTagWeight, apCntStickyCookieExp=apCntStickyCookieExp, apCntIndex=apCntIndex, apCntHotListEnabled=apCntHotListEnabled, apCntBalance=apCntBalance, apCntAvgLocalLoad=apCntAvgLocalLoad, apCntHotListSize=apCntHotListSize, apCntPersistenceResetMethod=apCntPersistenceResetMethod, apCntUrqlTblName=apCntUrqlTblName)
|
def get_dict_pos(lst, key, value):
return next((index for (index, d) in enumerate(lst) if d[key] == value), None)
def search_engine(search_term, data_key, data):
a = filter(lambda search_found: search_term in search_found[data_key], data)
return list(a)
|
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
n = len(word1)
m = len(word2)
# 有一个字符串为空串
if n * m == 0:
return n + m
# DP 数组
D = [ [0] * (m + 1) for _ in range(n + 1)]
# 边界状态初始化
for i in range(n + 1):
D[i][0] = i
for j in range(m + 1):
D[0][j] = j
# 计算所有 DP 值
for i in range(1, n + 1):
for j in range(1, m + 1):
left = D[i - 1][j] + 1
down = D[i][j - 1] + 1
left_down = D[i - 1][j - 1]
if word1[i - 1] != word2[j - 1]:
left_down += 1
D[i][j] = min(left, down, left_down)
return D[n][m] |
"""
This module contains submodules used to mine Interaction data from `Kegg`,
`Hprd`, `InnateDB`, `BioPlex` and `Pina2` along with other data processing
modules.
The `features` module contains a function to compute the features based on
two `:class:`.database.models.Protein`s. The `uniprot` module contains several
functions that use the `UniProt` class from `bioservices` and http utilities
of `BioPython` to download and parse `UniProt` records into
`:class:`.database.models.Protein` instances. The `tools` module contains
utility functions to turn parsed files into a dataframe of interactions, along
with several utility functions that operate on those dataframe to perform
tasks such as removing invalid rows, null rows, merging rows etc. The
`ontology` module contains methods to parse a `Gene Ontology` obo file into
a dictionary of entries. The `psimi` module does that same, except with
`Psi-Mi` obo files.
"""
__all__ = [
"features",
"generic",
"hprd",
"kegg",
"ontology",
"psimi",
"tools",
"uniprot"
]
|
#
# PySNMP MIB module F10-BPSTATS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/F10-BPSTATS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:11:15 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion")
f10Mgmt, = mibBuilder.importSymbols("FORCE10-SMI", "f10Mgmt")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, Bits, iso, Unsigned32, MibIdentifier, Counter32, TimeTicks, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, ModuleIdentity, Integer32, NotificationType, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "Bits", "iso", "Unsigned32", "MibIdentifier", "Counter32", "TimeTicks", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "ModuleIdentity", "Integer32", "NotificationType", "ObjectIdentity")
TimeStamp, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DisplayString", "TextualConvention")
f10BpStatsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 6027, 3, 24))
f10BpStatsMib.setRevisions(('2013-05-22 12:48',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: f10BpStatsMib.setRevisionsDescriptions(('Initial version of this mib.',))
if mibBuilder.loadTexts: f10BpStatsMib.setLastUpdated('201309181248Z')
if mibBuilder.loadTexts: f10BpStatsMib.setOrganization('Dell Inc')
if mibBuilder.loadTexts: f10BpStatsMib.setContactInfo('http://www.force10networks.com/support')
if mibBuilder.loadTexts: f10BpStatsMib.setDescription('Dell Networking OS Back plane statistics mib. This is MIB shall use for all back plane statistics related activities. This includes the BP ports traffic statistics. BP link bundle monitoring based on BP port statistics. Queue statistics and buffer utilization on BP ports etc ..')
f10BpStatsLinkBundleObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 24, 1))
f10BpStatsObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2))
f10BpStatsAlarms = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3))
bpLinkBundleObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 24, 1, 1))
bpLinkBundleRateInterval = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 24, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 299))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: bpLinkBundleRateInterval.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleRateInterval.setDescription('The rate interval for polling the Bp link bundle Monitoring.')
bpLinkBundleTriggerThreshold = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 24, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 90))).setUnits('percent').setMaxAccess("readwrite")
if mibBuilder.loadTexts: bpLinkBundleTriggerThreshold.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleTriggerThreshold.setDescription('The traffic distribution trigger threshold for Bp link bundle Monitoring.In percentage of total bandwidth of the link Bundle')
bpStatsObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1))
bpDropsTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1), )
if mibBuilder.loadTexts: bpDropsTable.setStatus('current')
if mibBuilder.loadTexts: bpDropsTable.setDescription('The back plane drops table contains the list of various drops per BP higig port per BCM unit in a stack unit(card type).')
bpDropsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1), ).setIndexNames((0, "F10-BPSTATS-MIB", "bpDropsStackUnitIndex"), (0, "F10-BPSTATS-MIB", "bpDropsPortPipe"), (0, "F10-BPSTATS-MIB", "bpDropsPortIndex"))
if mibBuilder.loadTexts: bpDropsEntry.setStatus('current')
if mibBuilder.loadTexts: bpDropsEntry.setDescription('Each drops entry is being indexed by StackUnit(card Type) BCM unit ID and local Port Id')
bpDropsStackUnitIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 12)))
if mibBuilder.loadTexts: bpDropsStackUnitIndex.setStatus('current')
if mibBuilder.loadTexts: bpDropsStackUnitIndex.setDescription('Stack unit(Card Type Id) number where this port present Each card shall contain more than one BCM units')
bpDropsPortPipe = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6)))
if mibBuilder.loadTexts: bpDropsPortPipe.setStatus('current')
if mibBuilder.loadTexts: bpDropsPortPipe.setDescription('bpPortPipe denotes the BCM unit in the stack unit(card Type) Each BCM unit shall contain 1-128 local ports, which includes BP as well as front end ports')
bpDropsPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128)))
if mibBuilder.loadTexts: bpDropsPortIndex.setStatus('current')
if mibBuilder.loadTexts: bpDropsPortIndex.setDescription('BP port number. Maximum ports shall support by Trident2 BCM npu is 128. This address space includes FE ports also, which are invalid ports as far as BP is concern. For Z9000 leaf BCM units, 34 to 41 are the valid BP port numbers and for spine BCM units, 1 to 16 are the valid BP ports ')
bpDropsInDrops = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 4), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsInDrops.setStatus('current')
if mibBuilder.loadTexts: bpDropsInDrops.setDescription('The No of Ingress packet Drops')
bpDropsInUnKnownHgHdr = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsInUnKnownHgHdr.setStatus('current')
if mibBuilder.loadTexts: bpDropsInUnKnownHgHdr.setDescription('The No of Unknown hiGig header Ingress packet Drops')
bpDropsInUnKnownHgOpcode = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 6), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsInUnKnownHgOpcode.setStatus('current')
if mibBuilder.loadTexts: bpDropsInUnKnownHgOpcode.setDescription('The No of Unknown hiGig Opcode Ingress packet Drops')
bpDropsInMTUExceeds = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 7), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsInMTUExceeds.setStatus('current')
if mibBuilder.loadTexts: bpDropsInMTUExceeds.setDescription('No of packets dropped on Ingress because of MTUExceeds')
bpDropsInMacDrops = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsInMacDrops.setStatus('current')
if mibBuilder.loadTexts: bpDropsInMacDrops.setDescription('No of packets dropped on Ingress MAC')
bpDropsMMUHOLDrops = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 9), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsMMUHOLDrops.setStatus('current')
if mibBuilder.loadTexts: bpDropsMMUHOLDrops.setDescription('No of packets dropped in MMU because of MMU HOL Drops')
bpDropsEgMacDrops = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 10), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsEgMacDrops.setStatus('current')
if mibBuilder.loadTexts: bpDropsEgMacDrops.setDescription('No of packets dropped on Egress MAC')
bpDropsEgTxAgedCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsEgTxAgedCounter.setStatus('current')
if mibBuilder.loadTexts: bpDropsEgTxAgedCounter.setDescription('No of Aged packets dropped on Egress')
bpDropsEgTxErrCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsEgTxErrCounter.setStatus('current')
if mibBuilder.loadTexts: bpDropsEgTxErrCounter.setDescription('No of Error packets dropped on Egress')
bpDropsEgTxMACUnderflow = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsEgTxMACUnderflow.setStatus('current')
if mibBuilder.loadTexts: bpDropsEgTxMACUnderflow.setDescription('No of MAC underflow packets dropped on Egress')
bpDropsEgTxErrPktCounter = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 1, 1, 14), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpDropsEgTxErrPktCounter.setStatus('current')
if mibBuilder.loadTexts: bpDropsEgTxErrPktCounter.setDescription('No of total packets dropped in Egress')
bpIfStatsTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2), )
if mibBuilder.loadTexts: bpIfStatsTable.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsTable.setDescription('The back plane counter statistics table contains the list of various counters per BP higig port per BCM unit in a stack unit(card type).')
bpIfStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1), ).setIndexNames((0, "F10-BPSTATS-MIB", "bpIfStatsStackUnitIndex"), (0, "F10-BPSTATS-MIB", "bpIfStatsPortPipe"), (0, "F10-BPSTATS-MIB", "bpIfStatsPortIndex"))
if mibBuilder.loadTexts: bpIfStatsEntry.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsEntry.setDescription('Each Stats entry is being indexed by StackUnit(card Type) BCM unit ID and local Port Id')
bpIfStatsStackUnitIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 12)))
if mibBuilder.loadTexts: bpIfStatsStackUnitIndex.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsStackUnitIndex.setDescription('Stack unit(Card Type Id) number where this port present Each card shall contain more than one BCM units')
bpIfStatsPortPipe = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6)))
if mibBuilder.loadTexts: bpIfStatsPortPipe.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsPortPipe.setDescription('bpPortPipe denotes the BCM unit in the stack unit(card Type) Each BCM unit shall contain 1-128 local ports, which includes BP as well as front end ports')
bpIfStatsPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128)))
if mibBuilder.loadTexts: bpIfStatsPortIndex.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsPortIndex.setDescription('BP port number. Maximum ports shall support by Trident2 BCM npu is 128. This address space includes FE ports also, which are invalid ports as far as BP is concern. For Z9000 leaf BCM units, 34 to 41 are the valid BP port numbers and for spine BCM units, 1 to 16 are the valid BP ports ')
bpIfStatsIn64BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 4), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsIn64BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsIn64BytePkts.setDescription('The total number of frames (including bad frames) received that were 64 octets in length (excluding framing bits but including FCS octets).')
bpIfStatsIn65To127BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 5), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsIn65To127BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsIn65To127BytePkts.setDescription('The total number of frames (including bad frames) received that were between 65 and 127 octets in length inclusive (excluding framing bits but including FCS octets).')
bpIfStatsIn128To255BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 6), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsIn128To255BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsIn128To255BytePkts.setDescription('The total number of frames (including bad frames) received that were between 128 and 255 octets in length inclusive (excluding framing bits but including FCS octets).')
bpIfStatsIn256To511BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 7), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsIn256To511BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsIn256To511BytePkts.setDescription('The total number of frames (including bad frames) received that were between 256 and 511 octets in length inclusive (excluding framing bits but including FCS octets).')
bpIfStatsIn512To1023BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsIn512To1023BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsIn512To1023BytePkts.setDescription('The total number of frames (including bad frames) received that were between 512 and 1023 octets in length inclusive (excluding framing bits but including FCS octets).')
bpIfStatsInOver1023BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 9), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsInOver1023BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsInOver1023BytePkts.setDescription('The total number of frames received that were longer than 1023 (1025 Bytes in case of VLAN Tag) octets (excluding framing bits, but including FCS octets) and were otherwise well formed. This counter is not incremented for too long frames.')
bpIfStatsInThrottles = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 10), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsInThrottles.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsInThrottles.setDescription('This counter is incremented when a valid frame with a length or type field value equal to 0x8808 (Control Frame) is received.')
bpIfStatsInRunts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 11), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsInRunts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsInRunts.setDescription('The total number of frames received that were less than 64 octets long (excluding framing bits, but including FCS octets) and were otherwise well formed.')
bpIfStatsInGiants = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 12), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsInGiants.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsInGiants.setDescription('The total number of frames received that were longer than 1518 (1522 Bytes in case of VLAN Tag) octets (excluding framing bits, but including FCS octets) and were otherwise well formed. This counter is not incremented for too long frames.')
bpIfStatsInCRC = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 13), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsInCRC.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsInCRC.setDescription('The total number of frames received that had a length (excluding framing bits, but including FCS octets) of between 64 and 1518 octets, inclusive, but had a bad CRC.')
bpIfStatsInOverruns = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 14), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsInOverruns.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsInOverruns.setDescription('The total number of frames has been chosen to be dropped by detecting the buffer issue')
bpIfStatsOutUnderruns = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 15), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOutUnderruns.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOutUnderruns.setDescription('The total number of frames dropped because of buffer underrun.')
bpIfStatsOutUnicasts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 16), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOutUnicasts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOutUnicasts.setDescription('The total number of Unicast frames are transmitted out of the interface')
bpIfStatsOutCollisions = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 17), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOutCollisions.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOutCollisions.setDescription('A count of the frames that due to excessive or late collisions are not transmitted successfully.')
bpIfStatsOutWredDrops = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 18), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOutWredDrops.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOutWredDrops.setDescription('The total number of frames are dropped by using WRED policy due to excessive traffic.')
bpIfStatsOut64BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 19), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOut64BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOut64BytePkts.setDescription('The total number of valid frames with the block of 64 byte size is transmitted')
bpIfStatsOut65To127BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 20), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOut65To127BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOut65To127BytePkts.setDescription('The total of valid frame with the block size of range between 65 and 127 bytes are transmitted.')
bpIfStatsOut128To255BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 21), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOut128To255BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOut128To255BytePkts.setDescription('The total of valid frame with the block size of range between 128 and 255 bytes are transmitted')
bpIfStatsOut256To511BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 22), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOut256To511BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOut256To511BytePkts.setDescription('The total of valid frame with the block size of range between 256 and 511 bytes are transmitted')
bpIfStatsOut512To1023BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 23), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOut512To1023BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOut512To1023BytePkts.setDescription('The total of valid frame with the block size of range between 512 and 1023 bytes are transmitted')
bpIfStatsOutOver1023BytePkts = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 24), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOutOver1023BytePkts.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOutOver1023BytePkts.setDescription('The total of valid frame with the block size of greater than 1023 bytes are transmitted.')
bpIfStatsOutThrottles = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 25), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOutThrottles.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOutThrottles.setDescription('This counter is incremented when a valid frame with a length or type field value equal to 0x8808 (Control Frame) is sent.')
bpIfStatsLastDiscontinuityTime = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 26), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsLastDiscontinuityTime.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsLastDiscontinuityTime.setDescription("The value of sysUpTime on the most recent occasion at which this interface's counters suffered a discontinuity via a reset. If no such discontinuities have occurred since the last reinitialization of the local management subsystem, then this object contains a zero value.")
bpIfStatsInCentRate = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 27), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsInCentRate.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsInCentRate.setDescription('This is the percentage of maximum line rate at which data is receiving on the Interface. For Z9000 - BP hiGig line rate is 42G. This is an integer value which can go from 0% to 100%.')
bpIfStatsOutCentRate = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 28), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsOutCentRate.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsOutCentRate.setDescription('This is the percentage of maximum line rate at which data is sending on the Interface. For Z9000 - BP hiGig line rate is 42G. This is an integer value which can go from 0% to 100%.')
bpIfStatsLastChange = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 2, 1, 29), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpIfStatsLastChange.setStatus('current')
if mibBuilder.loadTexts: bpIfStatsLastChange.setDescription('The value of sysUpTime, on which all the counters are updated recently')
bpPacketBufferTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 3), )
if mibBuilder.loadTexts: bpPacketBufferTable.setStatus('current')
if mibBuilder.loadTexts: bpPacketBufferTable.setDescription('The packet buffer table contains the modular packet buffers details per stack unit and the mode of allocation.')
bpPacketBufferEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 3, 1), ).setIndexNames((0, "F10-BPSTATS-MIB", "bpPacketBufferStackUnitIndex"), (0, "F10-BPSTATS-MIB", "bpPacketBufferPortPipe"))
if mibBuilder.loadTexts: bpPacketBufferEntry.setStatus('current')
if mibBuilder.loadTexts: bpPacketBufferEntry.setDescription('Packet buffer details per NPU unit.')
bpPacketBufferStackUnitIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 12)))
if mibBuilder.loadTexts: bpPacketBufferStackUnitIndex.setStatus('current')
if mibBuilder.loadTexts: bpPacketBufferStackUnitIndex.setDescription('Stack unit(Card Type Id) number where this port present Each card shall contain more than one BCM units')
bpPacketBufferPortPipe = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6)))
if mibBuilder.loadTexts: bpPacketBufferPortPipe.setStatus('current')
if mibBuilder.loadTexts: bpPacketBufferPortPipe.setDescription('bpPortPipe denotes the BCM unit in the stack unit(card Type) Each BCM unit shall contain 1-128 local ports, which includes BP as well as front end ports')
bpPacketBufferTotalPacketBuffer = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 3, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpPacketBufferTotalPacketBuffer.setStatus('current')
if mibBuilder.loadTexts: bpPacketBufferTotalPacketBuffer.setDescription('Total packet buffer in this NPU unit.')
bpPacketBufferCurrentAvailBuffer = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 3, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpPacketBufferCurrentAvailBuffer.setStatus('current')
if mibBuilder.loadTexts: bpPacketBufferCurrentAvailBuffer.setDescription('Current available buffer in this NPU unit.')
bpPacketBufferPacketBufferAlloc = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 3, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpPacketBufferPacketBufferAlloc.setStatus('current')
if mibBuilder.loadTexts: bpPacketBufferPacketBufferAlloc.setDescription('Static or Dynamic allocation.')
bpBufferStatsTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4), )
if mibBuilder.loadTexts: bpBufferStatsTable.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsTable.setDescription('The back plane stats per port table contains the packet buffer usage per bp port per NPU unit.')
bpBufferStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4, 1), ).setIndexNames((0, "F10-BPSTATS-MIB", "bpBufferStatsStackUnitIndex"), (0, "F10-BPSTATS-MIB", "bpBufferStatsPortPipe"), (0, "F10-BPSTATS-MIB", "bpBufferStatsPortIndex"))
if mibBuilder.loadTexts: bpBufferStatsEntry.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsEntry.setDescription('Per bp port buffer stats ')
bpBufferStatsStackUnitIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 12)))
if mibBuilder.loadTexts: bpBufferStatsStackUnitIndex.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsStackUnitIndex.setDescription('Stack unit(Card Type Id) number where this port present Each card shall contain more than one BCM units')
bpBufferStatsPortPipe = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6)))
if mibBuilder.loadTexts: bpBufferStatsPortPipe.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsPortPipe.setDescription('bpPortPipe denotes the BCM unit in the stack unit(card Type) Each BCM unit shall contain 1-128 local ports, which includes BP as well as front end ports')
bpBufferStatsPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128)))
if mibBuilder.loadTexts: bpBufferStatsPortIndex.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsPortIndex.setDescription('BP port number. Maximum ports shall support by Trident2 BCM npu is 128. This address space includes FE ports also, which are invalid ports as far as BP is concern. For Z9000 leaf BCM units, 34 to 41 are the valid BP port numbers and for spine BCM units, 1 to 16 are the valid BP ports ')
bpBufferStatsCurrentUsagePerPort = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpBufferStatsCurrentUsagePerPort.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsCurrentUsagePerPort.setDescription('Current buffer usage per bp port.')
bpBufferStatsDefaultPacketBuffAlloc = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpBufferStatsDefaultPacketBuffAlloc.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsDefaultPacketBuffAlloc.setDescription('Default packet buffer allocated.')
bpBufferStatsMaxLimitPerPort = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 4, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpBufferStatsMaxLimitPerPort.setStatus('current')
if mibBuilder.loadTexts: bpBufferStatsMaxLimitPerPort.setDescription('Max buffer limit per bp port.')
bpCosStatsTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5), )
if mibBuilder.loadTexts: bpCosStatsTable.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsTable.setDescription('The back plane statistics per COS table gives packet buffer statistics per COS per bp port.')
bpCosStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1), ).setIndexNames((0, "F10-BPSTATS-MIB", "bpCosStatsStackUnitIndex"), (0, "F10-BPSTATS-MIB", "bpCosStatsPortPipe"), (0, "F10-BPSTATS-MIB", "bpCosStatsPortIndex"), (0, "F10-BPSTATS-MIB", "bpCosStatsCOSNumber"))
if mibBuilder.loadTexts: bpCosStatsEntry.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsEntry.setDescription('Per bp port buffer stats and per COS buffer stats.')
bpCosStatsStackUnitIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 12)))
if mibBuilder.loadTexts: bpCosStatsStackUnitIndex.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsStackUnitIndex.setDescription('Stack unit(Card Type Id) number where this port present Each card shall contain more than one BCM units')
bpCosStatsPortPipe = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 6)))
if mibBuilder.loadTexts: bpCosStatsPortPipe.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsPortPipe.setDescription('bpPortPipe denotes the BCM unit in the stack unit(card Type) Each BCM unit shall contain 1-128 local ports, which includes BP as well as front end ports')
bpCosStatsPortIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128)))
if mibBuilder.loadTexts: bpCosStatsPortIndex.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsPortIndex.setDescription('BP port number. Maximum ports shall support by Trident2 BCM npu is 128. This address space includes FE ports also, which are invalid ports as far as BP is concern. For Z9000 leaf BCM units, 34 to 41 are the valid BP port numbers and for spine BCM units, 1 to 16 are the valid BP ports ')
bpCosStatsCOSNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15)))
if mibBuilder.loadTexts: bpCosStatsCOSNumber.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsCOSNumber.setDescription('COS queue number, There shall 10 unicast and 5 multicast queues per port in Trident2')
bpCosStatsCurrentUsage = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpCosStatsCurrentUsage.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsCurrentUsage.setDescription('Current buffer usage per COS per bp port.')
bpCosStatsDefaultPacketBuffAlloc = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpCosStatsDefaultPacketBuffAlloc.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsDefaultPacketBuffAlloc.setDescription('Default packet buffer allocated per COS queue')
bpCosStatsMaxLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpCosStatsMaxLimit.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsMaxLimit.setDescription('Max buffer utilization limit per bp port.')
bpCosStatsHOLDDrops = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 24, 2, 1, 5, 1, 8), Counter64()).setMaxAccess("readonly")
if mibBuilder.loadTexts: bpCosStatsHOLDDrops.setStatus('current')
if mibBuilder.loadTexts: bpCosStatsHOLDDrops.setDescription('HOLD Drops Per Queue.')
bpLinkBundleNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 1))
bpLinkBundleAlarmVariable = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 2))
bpLinkBundleType = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("unknown", 1), ("bpHgBundle", 2)))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: bpLinkBundleType.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleType.setDescription('Indicates Type of Back plane HiGig link bundle')
bpLinkBundleSlot = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 2, 2), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: bpLinkBundleSlot.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleSlot.setDescription('The SlotId on which Link Bundle is overloaded')
bpLinkBundleNpuUnit = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 2, 3), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: bpLinkBundleNpuUnit.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleNpuUnit.setDescription('The npuUnitId(BCM unit Id) on which Link Bundle is overloaded')
bpLinkBundleLocalId = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 2, 4), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: bpLinkBundleLocalId.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleLocalId.setDescription('The local linkBundle Id which is overloaded')
bpLinkBundleImbalance = NotificationType((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 1, 1)).setObjects(("F10-BPSTATS-MIB", "bpLinkBundleType"), ("F10-BPSTATS-MIB", "bpLinkBundleSlot"), ("F10-BPSTATS-MIB", "bpLinkBundleNpuUnit"), ("F10-BPSTATS-MIB", "bpLinkBundleLocalId"))
if mibBuilder.loadTexts: bpLinkBundleImbalance.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleImbalance.setDescription('Trap generated when traffic imbalance observed in BP Link Bundles')
bpLinkBundleImbalanceClear = NotificationType((1, 3, 6, 1, 4, 1, 6027, 3, 24, 3, 1, 2)).setObjects(("F10-BPSTATS-MIB", "bpLinkBundleType"), ("F10-BPSTATS-MIB", "bpLinkBundleSlot"), ("F10-BPSTATS-MIB", "bpLinkBundleNpuUnit"), ("F10-BPSTATS-MIB", "bpLinkBundleLocalId"))
if mibBuilder.loadTexts: bpLinkBundleImbalanceClear.setStatus('current')
if mibBuilder.loadTexts: bpLinkBundleImbalanceClear.setDescription('Trap generated when traffic imbalance is no longer observed on Bp Link bundles')
mibBuilder.exportSymbols("F10-BPSTATS-MIB", bpIfStatsOutCentRate=bpIfStatsOutCentRate, bpCosStatsHOLDDrops=bpCosStatsHOLDDrops, bpLinkBundleLocalId=bpLinkBundleLocalId, bpBufferStatsStackUnitIndex=bpBufferStatsStackUnitIndex, bpIfStatsIn256To511BytePkts=bpIfStatsIn256To511BytePkts, bpIfStatsInGiants=bpIfStatsInGiants, bpBufferStatsDefaultPacketBuffAlloc=bpBufferStatsDefaultPacketBuffAlloc, bpCosStatsDefaultPacketBuffAlloc=bpCosStatsDefaultPacketBuffAlloc, bpDropsInUnKnownHgOpcode=bpDropsInUnKnownHgOpcode, bpCosStatsEntry=bpCosStatsEntry, bpBufferStatsCurrentUsagePerPort=bpBufferStatsCurrentUsagePerPort, bpLinkBundleType=bpLinkBundleType, PYSNMP_MODULE_ID=f10BpStatsMib, bpDropsEgTxErrPktCounter=bpDropsEgTxErrPktCounter, bpDropsTable=bpDropsTable, bpDropsEgTxAgedCounter=bpDropsEgTxAgedCounter, bpCosStatsCOSNumber=bpCosStatsCOSNumber, bpLinkBundleTriggerThreshold=bpLinkBundleTriggerThreshold, bpLinkBundleNpuUnit=bpLinkBundleNpuUnit, bpDropsInMacDrops=bpDropsInMacDrops, bpPacketBufferEntry=bpPacketBufferEntry, bpIfStatsOutWredDrops=bpIfStatsOutWredDrops, bpCosStatsStackUnitIndex=bpCosStatsStackUnitIndex, bpCosStatsMaxLimit=bpCosStatsMaxLimit, bpBufferStatsTable=bpBufferStatsTable, bpIfStatsOutUnderruns=bpIfStatsOutUnderruns, bpDropsPortIndex=bpDropsPortIndex, bpPacketBufferStackUnitIndex=bpPacketBufferStackUnitIndex, bpDropsEgMacDrops=bpDropsEgMacDrops, bpDropsInMTUExceeds=bpDropsInMTUExceeds, bpLinkBundleNotifications=bpLinkBundleNotifications, bpIfStatsInCentRate=bpIfStatsInCentRate, bpIfStatsStackUnitIndex=bpIfStatsStackUnitIndex, bpCosStatsCurrentUsage=bpCosStatsCurrentUsage, bpDropsEntry=bpDropsEntry, bpPacketBufferTotalPacketBuffer=bpPacketBufferTotalPacketBuffer, bpIfStatsOut256To511BytePkts=bpIfStatsOut256To511BytePkts, bpIfStatsTable=bpIfStatsTable, bpIfStatsLastDiscontinuityTime=bpIfStatsLastDiscontinuityTime, bpLinkBundleImbalanceClear=bpLinkBundleImbalanceClear, bpIfStatsInOverruns=bpIfStatsInOverruns, bpIfStatsIn64BytePkts=bpIfStatsIn64BytePkts, bpIfStatsIn512To1023BytePkts=bpIfStatsIn512To1023BytePkts, bpBufferStatsMaxLimitPerPort=bpBufferStatsMaxLimitPerPort, bpBufferStatsPortIndex=bpBufferStatsPortIndex, bpDropsEgTxErrCounter=bpDropsEgTxErrCounter, bpIfStatsPortPipe=bpIfStatsPortPipe, bpIfStatsLastChange=bpIfStatsLastChange, bpDropsInDrops=bpDropsInDrops, bpIfStatsInRunts=bpIfStatsInRunts, bpLinkBundleImbalance=bpLinkBundleImbalance, f10BpStatsLinkBundleObjects=f10BpStatsLinkBundleObjects, f10BpStatsObjects=f10BpStatsObjects, bpIfStatsOutOver1023BytePkts=bpIfStatsOutOver1023BytePkts, bpDropsInUnKnownHgHdr=bpDropsInUnKnownHgHdr, bpIfStatsIn65To127BytePkts=bpIfStatsIn65To127BytePkts, bpDropsStackUnitIndex=bpDropsStackUnitIndex, bpIfStatsEntry=bpIfStatsEntry, bpIfStatsIn128To255BytePkts=bpIfStatsIn128To255BytePkts, f10BpStatsMib=f10BpStatsMib, bpBufferStatsEntry=bpBufferStatsEntry, bpPacketBufferTable=bpPacketBufferTable, bpLinkBundleRateInterval=bpLinkBundleRateInterval, bpCosStatsPortIndex=bpCosStatsPortIndex, bpLinkBundleAlarmVariable=bpLinkBundleAlarmVariable, bpDropsPortPipe=bpDropsPortPipe, bpStatsObjects=bpStatsObjects, bpIfStatsOutCollisions=bpIfStatsOutCollisions, f10BpStatsAlarms=f10BpStatsAlarms, bpIfStatsInCRC=bpIfStatsInCRC, bpIfStatsOut512To1023BytePkts=bpIfStatsOut512To1023BytePkts, bpPacketBufferCurrentAvailBuffer=bpPacketBufferCurrentAvailBuffer, bpIfStatsOutUnicasts=bpIfStatsOutUnicasts, bpIfStatsInOver1023BytePkts=bpIfStatsInOver1023BytePkts, bpDropsEgTxMACUnderflow=bpDropsEgTxMACUnderflow, bpCosStatsTable=bpCosStatsTable, bpIfStatsOut128To255BytePkts=bpIfStatsOut128To255BytePkts, bpIfStatsInThrottles=bpIfStatsInThrottles, bpIfStatsPortIndex=bpIfStatsPortIndex, bpBufferStatsPortPipe=bpBufferStatsPortPipe, bpPacketBufferPortPipe=bpPacketBufferPortPipe, bpCosStatsPortPipe=bpCosStatsPortPipe, bpLinkBundleObjects=bpLinkBundleObjects, bpIfStatsOutThrottles=bpIfStatsOutThrottles, bpDropsMMUHOLDrops=bpDropsMMUHOLDrops, bpIfStatsOut64BytePkts=bpIfStatsOut64BytePkts, bpPacketBufferPacketBufferAlloc=bpPacketBufferPacketBufferAlloc, bpIfStatsOut65To127BytePkts=bpIfStatsOut65To127BytePkts, bpLinkBundleSlot=bpLinkBundleSlot)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#3.1.1 => updates from 2016 to 2018
#3.1.2 => fix to pip distribution
__version__ = '3.1.2'
|
if __name__ == '__main__':
print("{file} is main".format(file=__file__))
else:
print("{file} is loaded".format(file=__file__)) |
class Config:
"""Discriminator configurations.
"""
def __init__(self, steps: int):
"""Initializer.
Args:
steps: diffusion steps.
"""
self.steps = steps
# embedding
self.pe = 128
self.embeddings = 512
self.mappers = 2
# block
self.channels = 64
self.kernels = 3
self.layers = 10
self.leak = 0.2
|
with open('.\\DARKCPU\\DARKCPU.bin', 'rb') as inputFile:
with open('image.bin', 'wb') as outputFile:
while True:
bufA = inputFile.read(1)
bufB = inputFile.read(1)
if bufA == "" or bufB == "":
break;
outputFile.write(bufB)
outputFile.write(bufA)
print("Done")
|
class DefaultBindingPropertyAttribute:
"""
Specifies the default binding property for a component. This class cannot be inherited.
DefaultBindingPropertyAttribute()
DefaultBindingPropertyAttribute(name: str)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DefaultBindingPropertyAttribute()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def Equals(self,obj):
"""
Equals(self: DefaultBindingPropertyAttribute,obj: object) -> bool
Determines whether the specified System.Object is equal to the current System.ComponentModel.DefaultBindingPropertyAttribute instance.
obj: The System.Object to compare with the current System.ComponentModel.DefaultBindingPropertyAttribute instance
Returns: true if the object is equal to the current instance; otherwise,false,indicating they are not equal.
"""
pass
def GetHashCode(self):
"""
GetHashCode(self: DefaultBindingPropertyAttribute) -> int
Returns: A 32-bit signed integer hash code.
"""
pass
def __eq__(self,*args):
""" x.__eq__(y) <==> x==y """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,name=None):
"""
__new__(cls: type)
__new__(cls: type,name: str)
"""
pass
def __ne__(self,*args):
pass
Name=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the name of the default binding property for the component to which the System.ComponentModel.DefaultBindingPropertyAttribute is bound.
Get: Name(self: DefaultBindingPropertyAttribute) -> str
"""
Default=None
|
# problem description can be added if required
n = int(input())
hou = [int(i) for i in input().split()]
p = int(input())
for i in range(p):
a, b = [int(i) for i in input().split()]
print(sum(hou[a - 1:b])) # sum was to be including both the 'a'th and 'b'th index
|
class ModelAdmin:
"""
The class provides the possibility of declarative describe of information
about the table and describe all things related to viewing this table on
the administrator's page.
class Users(models.ModelAdmin):
class Meta:
resource_type = PGResource
table = users
"""
can_edit = True
can_create = True
can_delete = True
per_page = 10
fields = None
form = None
edit_form = None
create_form = None
show_form = None
primary_key = 'id'
def __init__(self, db=None):
self.name = self.__class__.__name__.lower()
self._table = self.Meta.table
self._resource_type = self.Meta.resource_type
self.db = db
def to_dict(self):
"""
Return dict with the all base information about the instance.
"""
data = {
"name": self.name,
"canEdit": self.can_edit,
"canCreate": self.can_create,
"canDelete": self.can_delete,
"perPage": self.per_page,
"showPage": self.generate_data_for_show_page(),
"editPage": self.generate_data_for_edit_page(),
"createPage": self.generate_data_for_create_page(),
"primaryKey": self.primary_key
}
return data
def generate_simple_data_page(self):
"""
Generate a simple representation of table's fields in dictionary type.
:return: dict
"""
return self._resource_type.get_type_for_inputs(self._table)
def generate_data_for_edit_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist edit form else use default representation.
:return: dict
"""
if not self.can_edit:
return {}
if self.edit_form:
return self.edit_form.to_dict()
return self.generate_simple_data_page()
def generate_data_for_show_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist show form else use default representation.
:return: dict
"""
if self.show_form:
return self.show_form.to_dict()
return self.generate_simple_data_page()
def generate_data_for_create_page(self):
"""
Generate a custom representation of table's fields in dictionary type
if exist create form else use default representation.
:return: dict
"""
if not self.can_create:
return {}
if self.create_form:
return self.create_form.to_dict()
return self.generate_simple_data_page()
def get_info_for_resource(self):
return dict(
table=self.Meta.table,
url=self.name,
db=self.db
)
|
''' Base Class method Proxy'''
#method 1, not recommand!
class A:
def spam(self, x):
pass
def foo(self):
pass
class B:
def __init__(self):
self._a = A()
def spam(self, x):
# Delegate to the internal self._a instance
return self._a.spam(x)
def foo(self):
# Delegate to the internal self._a instance
return self._a.foo()
def bar(self):
pass
#method 2, better
class A:
def spam(self, x):
pass
def foo(self):
pass
class B:
def __init__(self):
self._a = A()
def bar(self):
pass
#Expose all of the methods defined on Class A,like virtual method fields filled
def __getattr__(self, item):
return getattr( self._a, item )
#method 3, common Proxy
# A proxy class that wraps around another object, but
# exposes its public attributes
class Proxy:
def __init__(self, obj):
self._obj = obj
# Delegate attribute lookup to internal obj
def __getattr__(self, name):
print('getattr:', name)
return getattr(self._obj, name)
# Delegate attribute assignment
def __setattr__(self, name, value):
if name.startswith('_'):
super().__setattr__(name, value)
else:
print('setattr:', name, value)
setattr(self._obj, name, value)
# Delegate attribute deletion
def __delattr__(self, name):
if name.startswith('_'):
super().__delattr__(name)
else:
print('delattr:', name)
delattr(self._obj, name)
class Spam:
def __init__(self, x):
self.x = x
def bar(self, y):
print('Spam.bar:', self.x, y)
# Create an instance
s = Spam(2)
# Create a proxy around it
p = Proxy(s)
# Access the proxy
print(p.x) # Outputs 2
p.bar(3) # Outputs "Spam.bar: 2 3"
p.x = 37 # Changes s.x to 37
#Example for ListLike
'''TODO:: All functions starts with __ must defined by hand~~'''
class ListLike:
def __init__(self):
self._items = []
def __getattr__(self, name):
return getattr(self._items, name)
# Added special methods to support certain list operations
def __len__(self):
return len(self._items)
def __getitem__(self, index):
return self._items[index]
def __setitem__(self, index, value):
self._items[index] = value
def __delitem__(self, index):
del self._items[index] |
def aléa(a, b):
return (a + b) // 2
if __name__ == '__main__':
print('Import this module in order to use it!') |
class PacketSummary(object):
"""
A simple object containing a psml summary.
Can contain various summary information about a packet.
"""
def __init__(self, structure, values):
self._fields = {}
self._field_order = []
for key, val in zip(structure, values):
key, val = str(key), str(val)
self._fields[key] = val
self._field_order.append(key)
setattr(self, key.lower().replace('.', '').replace(',', ''), val)
def __repr__(self):
protocol, src, dst = self._fields.get('Protocol', '?'), self._fields.get('Source', '?'),\
self._fields.get('Destination', '?')
return '<%s %s: %s to %s>' % (self.__class__.__name__, protocol, src, dst)
def __str__(self):
return self.summary_line
@property
def summary_line(self):
return ' '.join([self._fields[key] for key in self._field_order])
|
# "Matrix Decomposition"
# Alec Dewulf
# April Cook Off 2020
# Difficulty: Simple
# Concepts: Fast exponentiation, implementation
"""
This problem required the solver to caculate exponentials very quickly.
I did that by computing everything mod so the numbers remained small.
A more efficient exponent function could have also been used.
"""
T = int(input())
mod = 10**9 + 7
for _ in range(T):
num_rows, value = map(int, input().split())
ans = 0
for i in range(1, num_rows + 1):
# update the answer and compute it mod to save time
ans += pow(value, 2*i-1, mod)
ans %= mod
# update the value of the cells
value = pow(value, 2*i, mod)
print(ans)
|
class Customer:
def __init__(self, customer_id, first, last, email, address, city, state, zip_code, phone):
self.id = customer_id
self.first = first
self.last = last
self.email = email
self.address = address
self.city = city
self.state = state
self.zip = zip_code
self.phone = phone
def as_dict(self):
return vars(self)
|
def solution(x):
answer = True
temp = 0
copy = x
while copy != 0:
r = copy % 10
copy //= 10
temp += r
if x % temp != 0:
answer = False
return answer
print(solution(13)) |
# ------------------------------
# 138. Copy List with Random Pointer
#
# Description:
# A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.
# Return a deep copy of the list.
#
# Version: 1.0
# 08/21/18 by Jianfa
# ------------------------------
# Definition for singly-linked list with a random pointer.
# class RandomListNode(object):
# def __init__(self, x):
# self.label = x
# self.next = None
# self.random = None
class Solution(object):
def copyRandomList(self, head):
"""
:type head: RandomListNode
:rtype: RandomListNode
"""
iterhead = head
while iterhead:
nextnode = iterhead.next
copynode = RandomListNode(iterhead.label)
iterhead.next = copynode
copynode.next = nextnode
iterhead = nextnode
iterhead = head
while iterhead:
if iterhead.random:
iterhead.next.random = iterhead.random.next
iterhead = iterhead.next.next
iterhead = head
startpointer = RandomListNode(0)
copyiter = startpointer
while iterhead:
nextnode = iterhead.next.next
copynode = iterhead.next
copyiter.next = copynode
copyiter = copynode
iterhead.next = nextnode
iterhead = iterhead.next
return startpointer.next
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get idea from: https://leetcode.com/problems/copy-list-with-random-pointer/discuss/43491/A-solution-with-constant-space-complexity-O(1)-and-linear-time-complexity-O(N)
# Key points:
# 1. Iterate the original list and duplicate each node. The duplicate of each node follows its original immediately.
# 2. Iterate the new list and assign the random pointer for each duplicated node.
# 3. Restore the original list and extract the duplicated nodes. |
#!/usr/bin/python
# Tutaj _used i independent_set jest typu set.
class UnorderedSequentialIndependentSet1:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError("the graph is directed")
self.graph = graph
for edge in self.graph.iteredges():
if edge.source == edge.target: # for multigraphs
raise ValueError("a loop detected")
self.independent_set = set()
self.cardinality = 0
self.source = None
def run(self, source=None):
"""Executable pseudocode."""
used = set()
if source is not None:
self.source = source
self.independent_set.add(source)
used.add(source)
used.update(self.graph.iteradjacent(source))
for source in self.graph.iternodes():
if source in used:
continue
self.independent_set.add(source)
used.add(source)
used.update(self.graph.iteradjacent(source))
self.cardinality = len(self.independent_set)
# Tutaj _used jest dict, a independent_set jest typu set.
class UnorderedSequentialIndependentSet2:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError("the graph is directed")
self.graph = graph
for edge in self.graph.iteredges():
if edge.source == edge.target: # for multigraphs
raise ValueError("a loop detected")
self.independent_set = set()
self.cardinality = 0
self.source = None
def run(self, source=None):
"""Executable pseudocode."""
used = dict((node, False) for node in self.graph.iternodes())
if source is not None:
self.source = source
self.independent_set.add(source)
used[source] = True
for target in self.graph.iteradjacent(source):
used[target] = True
for source in self.graph.iternodes():
if used[source]:
continue
self.independent_set.add(source)
used[source] = True
for target in self.graph.iteradjacent(source):
used[target] = True
self.cardinality = len(self.independent_set)
# Tutaj _used i independent_set jest dict. Wygodne dla C++.
class UnorderedSequentialIndependentSet3:
"""Find a maximal independent set."""
def __init__(self, graph):
"""The algorithm initialization."""
if graph.is_directed():
raise ValueError("the graph is directed")
self.graph = graph
for edge in self.graph.iteredges():
if edge.source == edge.target: # for multigraphs
raise ValueError("a loop detected")
self.independent_set = dict((node, False) for node in self.graph.iternodes())
self.cardinality = 0
self.source = None
def run(self, source=None):
"""Executable pseudocode."""
used = dict((node, False) for node in self.graph.iternodes())
if source is not None:
self.source = source
self.independent_set[source] = True
used[source] = True
self.cardinality += 1
for target in self.graph.iteradjacent(source):
used[target] = True
for source in self.graph.iternodes():
if used[source]:
continue
self.independent_set[source] = True
used[source] = True
self.cardinality += 1
for target in self.graph.iteradjacent(source):
used[target] = True
UnorderedSequentialIndependentSet = UnorderedSequentialIndependentSet1
# EOF
|
input = '''10 3 15 10 5 15 5 15 9 2 5 8 5 2 3 6'''
memory = [int(x) for x in input.split('\t')]
memory_status = []
def update_memoery(memory):
highest_bank = max(memory)
highest_index = memory.index(highest_bank)
memory[highest_index] = 0
i = 0
while i < highest_bank:
memory[(highest_index + i + 1) % len(memory)] += 1
i += 1
return tuple(memory)
def find_steps(memory):
steps = 0
memory_history = [tuple(memory)]
#while memory not in memory_status:
while True:
new_memory = update_memoery(memory)
steps += 1
if new_memory in memory_history:
break
else:
memory_history.append(new_memory)
return steps
if __name__ == '__main__':
print(find_steps(memory))
|
for _ in range(int(input())):
n,x = [int(x) for x in input().split()]
dp = {}
s = input()
dp[x] = 1
for i in s:
if(i == "R"): x += 1
else:x -= 1
if(not dp.get(x)):dp[x] = 1
print(len(dp)) |
class FontStyleConverter(TypeConverter):
"""
Converts instances of System.Windows.FontStyle to and from other data types.
FontStyleConverter()
"""
def CanConvertFrom(self,*__args):
"""
CanConvertFrom(self: FontStyleConverter,td: ITypeDescriptorContext,t: Type) -> bool
Returns a value that indicates whether this converter can convert an object of
the given type to an instance of System.Windows.FontStyle.
td: Describes the context information of a type.
t: The type of the source that is being evaluated for conversion.
Returns: true if the converter can convert the provided type to an instance of
System.Windows.FontStyle; otherwise,false.
"""
pass
def CanConvertTo(self,*__args):
"""
CanConvertTo(self: FontStyleConverter,context: ITypeDescriptorContext,destinationType: Type) -> bool
Determines whether an instance of System.Windows.FontStyle can be converted to
a different type.
context: Context information of a type.
destinationType: The desired type that that this instance of System.Windows.FontStyle is being
evaluated for conversion to.
Returns: true if the converter can convert this instance of System.Windows.FontStyle;
otherwise,false.
"""
pass
def ConvertFrom(self,*__args):
"""
ConvertFrom(self: FontStyleConverter,td: ITypeDescriptorContext,ci: CultureInfo,value: object) -> object
Attempts to convert a specified object to an instance of
System.Windows.FontStyle.
td: Context information of a type.
ci: System.Globalization.CultureInfo of the type being converted.
value: The object being converted.
Returns: The instance of System.Windows.FontStyle created from the converted value.
"""
pass
def ConvertTo(self,*__args):
"""
ConvertTo(self: FontStyleConverter,context: ITypeDescriptorContext,culture: CultureInfo,value: object,destinationType: Type) -> object
Attempts to convert an instance of System.Windows.FontStyle to a specified type.
context: Context information of a type.
culture: System.Globalization.CultureInfo of the type being converted.
value: The instance of System.Windows.FontStyle to convert.
destinationType: The type this instance of System.Windows.FontStyle is converted to.
Returns: The object created from the converted instance of System.Windows.FontStyle.
"""
pass
|
def median(array):
array = sorted(array)
if len(array) % 2 == 0:
return (array[(len(array) - 1) // 2] + array[len(array) // 2]) / 2
else:
return array[len(array) // 2]
|
# Copyright 2019 VMware, Inc.
# SPDX-License-Identifier: BSD-2-Clause
class PrePostProcessor(object):
def pre_process(self, data):
type(self)
return data
def post_process(self, data):
type(self)
return data
|
def find_digits(digits1, digits2, digit_quantity_to_find):
print('Inputs:')
print('\tdigits1 = %s' % (digits1))
print('\tdigits2 = %s' % (digits2))
print('\tdigit_quantity_to_find = %d' % (digit_quantity_to_find))
digit_count_by_input = [len(digits1), len(digits2)]
positions_by_digit_input = [[[], []] for _ in range(10)]
for i in range(digit_count_by_input[0]):
positions_by_digit_input[digits1[i]][0].append(digit_count_by_input[0] - i - 1)
for i in range(digit_count_by_input[1]):
positions_by_digit_input[digits2[i]][1].append(digit_count_by_input[1] - i - 1)
digits_found = []
digit_quantity_left_to_find = digit_quantity_to_find
digit_quantity_remaining_by_input = list(digit_count_by_input)
# Search for the greatest available digit, given the constraint that a
# digit can't be chosen if its selection would result in too few digits
# remaining to construct a number of the specified length. If multiple
# candidates are found for the greatest digit, choose the one that is
# furthest to the left in the input list, since its selection maximizes
# the number of remaining digits for consideration in subsequent
# positions. If no candidates are found for the search digit, try again
# using the next greatest digit. If a digit is found, for the next
# position, start a new search using the greatest digit again.
search_digit = 9
while digit_quantity_left_to_find > 0:
print('digits_found = %s, digit_quantity_left_to_find = %d, search_digit = %d' % (digits_found, digit_quantity_left_to_find, search_digit))
print('digit_quantity_remaining_by_input = %s' % (digit_quantity_remaining_by_input))
final_candidates = [-1, -1]
winner_index = -1
for i in range(2):
positions = positions_by_digit_input[search_digit][i]
print('Step 0: positions_by_digit_input[%d][%d] = %s' % (search_digit, i, positions))
# Remove digits whose positions have already been passed. These
# cannot be used now or in subsequent positions, so permanently
# eliminate them from consideration.
while len(positions) > 0 and positions[0] >= digit_quantity_remaining_by_input[i]:
del positions[0]
print('Step 1: positions_by_digit_input[%d][%d] = %s' % (search_digit, i, positions))
# Filter out digits that, if chosen, would not leave enough
# remaining digits to construct a number of the specified length.
# These digits may be needed in subsequent positions, so just
# eliminate them from consideration for now.
candidates = list(positions)
min_remaining_digits_in_list = digit_quantity_left_to_find - digit_quantity_remaining_by_input[(i + 1) % 2]
candidates = [positions[j] for j in range(len(positions)) if positions[j] + 1 >= min_remaining_digits_in_list]
print('Step 2: positions = %s' % (positions))
# Given how the position list was initially built, elements that
# are further to the left after filtering correspond to digits
# that are further to the left in the input list. Hence, choose
# the first element of the list, if any, as this will maximize the
# number of remaining digits for consideration in subsequent
# positions.
if len(candidates) > 0:
final_candidates[i] = candidates[0]
winner_index = i
print('Step 3: final_candidates = %s, winner_index = %d' % (final_candidates, winner_index))
# If a candidate was chosen from both lists, one must now be chosen as
# the winner. The best candidate is the one belonging to a list whose
# remaining digits include a digit greater than the candidate digit.
# If this is is the situation for both candidates, then the candidate
# with the nearest greater digit is best.
if final_candidates[0] != -1 and final_candidates[1] != -1:
shortest_distances = [0, 0]
for i in range(2):
for j in range(digit_count_by_input[i] - final_candidates[i], digit_count_by_input[i]):
print(i, digit_count_by_input[i], digit_quantity_remaining_by_input[i], j)
if (digits1, digits2)[i][j] > search_digit:
shortest_distances[i] = final_candidates[i] - j
break
winner_index = (0, 1)[shortest_distances[0] < shortest_distances[1]]
print('Step 4: final_candidates = %s, winner_index = %d' % (final_candidates, winner_index))
if winner_index != -1:
digit_quantity_left_to_find -= 1
digit_quantity_remaining_by_input[winner_index] = final_candidates[winner_index]
digits_found.append(search_digit)
search_digit = 9
else:
search_digit -= 1
print('Output:\t%s' % (digits_found))
return digits_found
if __name__ == '__main__':
print(find_digits([3, 4, 6, 5], [9, 1, 2, 5, 8, 3], 5))
print(find_digits([6, 7], [6, 0, 4], 5))
print(find_digits([3, 9], [8, 9], 3))
print(find_digits([1,1,1,9,1], [1,1,9,1,1], 6))
print(find_digits([1,1,1,9,1,0,0], [1,1,9,1,1,0,0], 10))
print(find_digits([1,1,1,9,1,9,1], [1,1,9,1,1,9,1], 10))
print(find_digits([6, 7], [6, 0, 8], 5))
print(find_digits([6, 7], [6, 7, 8], 5))
|
class Animal:
hungry = 100
def __init__(self, name, weight):
self.name = name
self.weight = weight
def eat(self, value):
self.hungry += int(value)
class FruitOfEggs:
amount_eggs = 5
def get_eggs(self):
if self.amount_eggs >= 0:
self.amount_eggs -= 1
return 1
class FruitOfMilk:
amount_milk = 100
def get_milk(self):
if self.amount_milk >= 10:
self.amount_milk -= 10
return 10
class Goose(Animal, FruitOfEggs):
@staticmethod
def vote():
return 'Goose vote'
class Cow(Animal, FruitOfMilk):
@staticmethod
def vote():
return 'Cow vote'
class Sheep(Animal):
trimmed = False
def shave(self):
if not self.trimmed:
self.trimmed = True
return 'Шерсть'
@staticmethod
def vote():
return 'Sheep Vote'
class Chicken(Animal, FruitOfEggs):
@staticmethod
def vote():
return 'Chicken vote!'
class Goat(Animal, FruitOfEggs, FruitOfMilk):
@staticmethod
def vote():
return 'Goat vote'
class Duck(Animal, FruitOfEggs):
@staticmethod
def vote():
return 'Duck vote'
goose_gray = Goose('Gray', 100)
goose_white = Goose('White', 100)
cow_manyka = Cow('Manyka', 200)
sheep_barash = Sheep('Barash', 200)
sheep_kudr = Sheep('Kudr', 300)
chicken_koko = Chicken('Koko', 300)
chiken_kukareku = Chicken('Kukareku', 400)
goat_roga = Goat('Roga', 500)
goat_kopito = Goat('Kopito', 600)
duck_kryakva = Duck('Kryakva', 700)
animals_farm = [goose_gray, goose_white, cow_manyka, sheep_barash, sheep_kudr, chicken_koko,
chiken_kukareku, goat_roga, goat_kopito, duck_kryakva]
animal_milk = [cow_manyka, goat_kopito, goat_roga]
animal_wool = [sheep_kudr, sheep_barash]
animal_eggs = [chiken_kukareku, chicken_koko, duck_kryakva, goose_white, goose_gray]
def spend_day():
for animal in animals_farm:
animal.eat(5)
if animal in animal_milk:
animal.get_milk()
if animal in animal_wool:
animal.shave()
if animal in animal_eggs:
animal.get_eggs()
def calculate_weight_animals(animals):
total_weight = 0
for animal in animals:
total_weight += animal.weight
return total_weight
def get_heaviest_animal(animals):
max_weight = 0
for animal in animals:
max_weight = max(max_weight, animal.weight)
return max_weight
spend_day()
print(calculate_weight_animals(animals_farm))
print(get_heaviest_animal(animals_farm))
|
class Args:
"""
This module helps in preventing args being sent through multiple of classes to reach
any analysis/laser module
"""
def __init__(self):
self.solver_timeout = 10000
self.sparse_pruning = True
self.unconstrained_storage = False
args = Args()
|
# (c) 2012 Urban Airship and Contributors
__version__ = (0, 2, 0)
class RequestIPStorage(object):
def __init__(self):
self.ip = None
def set(self, ip):
self.ip = ip
def get(self):
return self.ip
_request_ip_storage = RequestIPStorage()
get_current_ip = _request_ip_storage.get
set_current_ip = _request_ip_storage.set
|
def sum_of_squares(value):
sum = 0
for _ in range(value + 1):
sum = sum + _ ** 2
return sum
def summed_squares(value):
sum = 0
for _ in range(value + 1):
sum += _
return sum ** 2
print(summed_squares(100) - sum_of_squares(100)) |
# Part 1
data = data.split("\r\n\r\n")
nums = list(map(int, data[0].split(",")))
boards = []
for k in data[1:]:
boards.append([])
for j in k.splitlines():
boards[-1].append(list(map(int, j.split())))
for num in nums:
for board in boards:
for row in board:
for i in range(len(row)):
if row[i] == num:
row[i] = None
if any(all(x == None for x in row) for row in board) or any(all(row[i] == None for row in board) for i in range(len(board[0]))):
print(sum(x or 0 for row in board for x in row) * num)
exit(0)
# Part 2
data = data.split("\r\n\r\n")
nums = list(map(int, data[0].split(",")))
boards = []
for k in data[1:]:
boards.append([])
for j in k.splitlines():
boards[-1].append(list(map(int, j.split())))
lb = None
for num in nums:
bi = 0
while bi < len(boards):
board = boards[bi]
for row in board:
for i in range(len(row)):
if row[i] == num:
row[i] = None
if any(all(x == None for x in row) for row in board) or any(all(row[i] == None for row in board) for i in range(len(board[0]))):
lb = board
del boards[bi]
else:
bi += 1
if len(boards) == 0:
break
print(sum(x or 0 for row in lb for x in row) * num)
|
def test_000_a_test_can_pass():
print("This test should always pass!")
assert True
def test_001_can_see_the_internet(selenium):
selenium.get('http://www.example.com')
|
f = open("shaam.txt")
# tell() tell the position of our f pointer
# print(f.readline())
# print(f.tell())
# print(f.readline())
# print(f.tell())
# seek() point the pointer to given index
f.seek(5)
print(f.readline())
f.close() |
"""
Stores all global variables
"""
global d, aSub1, aSubN, aSubX, aSubY, x, y, sSubN, n, operations, selection, r # declares all variables global
r = None # common rate
d = None # common difference
aSub1 = None # first number in sequence
aSubN = None # number in sequence given index n
aSubX = None # number in sequence with index x
aSubY = None # number in sequence with index y
x = None # index x, correlates with aSubX
y = None # index y, correlates with aSUbY
sSubN = None # partial sum given index n
n = None # index n
selection = None
operations = ['arithmetic summation', 'arithmetic sequence', 'geometric summation', 'geometric sequence']
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
""" __init__.py : __init__ """
__author__ = "Abhay Arora ( @dumbstark )"
|
#!/usr/bin/env python3
# 给定一个正整数n, 求解出所有和为n的整数组合, 要求组合按照递增的方式展示,而且唯一,例如: 4=1+1+1+1,4=1+1+2
def get_all_combination(sums, result, count):
if sums < 0:
return
if sums == 0:
print("满足条件的组合...")
i = 0
while i < count:
print(result[i])
i += 1
i = (1 if count == 0 else result[count-1])
while i <= sums:
result[count] = i
count += 1
get_all_combination(sums - i, result, count)
count -= 1
i += 1
def show_all(n):
if n <1:
print("参数不满足要")
return
result = [0] * n
get_all_combination(n, result, 0)
if __name__ == '__main__':
show_all(6) |
dp=[[0]*5 for i in range(101)]
dp[0][0]=1
dp[1][0]=1
dp[2][0]=1
dp[2][1]=1
dp[2][2]=1
dp[2][3]=1
dp[2][4]=1
for i in range(3,101):
dp[i][0]=sum(dp[i-1])
dp[i][4]=sum(dp[i-2])
j=i-2
while j>=0:
dp[i][1]+=sum(dp[j])
j-=2
j=i-2
while j>=0:
dp[i][2]+=sum(dp[j])
dp[i][3]+=sum(dp[j])
j-=1
for i in range(int(input())):
x=int(input())
print(sum(dp[x])) |
# leapyear
y=input("enter any year")
if y%4==0:
print("{} is:leap year".format(y))
else:
print("{} is not a leap year".format(y))
|
t = int(input())
for i in range(t):
n, m = list(map(int, input().split()))
if(n%m == 0):
print("YES")
else:
print("NO")
|
a, b, c = (int(input()) for i in range(3))
if a <= b <= c:
print("True")
else:
print("False")
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr , n , x ) :
for i in range ( n ) :
if arr [ i ] > arr [ i + 1 ] :
break
l = ( i + 1 ) % n
r = i
cnt = 0
while ( l != r ) :
if arr [ l ] + arr [ r ] == x :
cnt += 1
if l == ( r - 1 + n ) % n :
return cnt
l = ( l + 1 ) % n
r = ( r - 1 + n ) % n
elif arr [ l ] + arr [ r ] < x :
l = ( l + 1 ) % n
else :
r = ( n + r - 1 ) % n
return cnt
#TOFILL
if __name__ == '__main__':
param = [
([24, 54],1,1,),
([68, -30, -18, -6, 70, -40, 86, 98, -24, -48],8,8,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],33,28,),
([84, 44, 40, 45, 2, 41, 52, 17, 50, 41, 5, 52, 48, 90, 13, 55, 34, 55, 94, 44, 41, 2],18,16,),
([-92, -76, -74, -72, -68, -64, -58, -44, -44, -38, -26, -24, -20, -12, -8, -8, -4, 10, 10, 10, 20, 20, 26, 26, 28, 50, 52, 54, 60, 66, 72, 74, 78, 78, 78, 80, 86, 88],29,30,),
([1, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 1, 1, 1],19,10,),
([5, 5, 15, 19, 22, 24, 26, 27, 28, 32, 37, 39, 40, 43, 49, 52, 55, 56, 58, 58, 59, 62, 67, 68, 77, 79, 79, 80, 81, 87, 95, 95, 96, 98, 98],28,34,),
([-98, 28, 54, 44, -98, -70, 48, -98, 56, 4, -18, 26, -8, -58, 30, 82, 4, -38, 42, 64, -28],17,14,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],24,24,),
([26, 72, 74, 86, 98, 86, 22, 6, 95, 36, 11, 82, 34, 3, 50, 36, 81, 94, 55, 30, 62, 53, 50, 95, 32, 83, 9, 16],19,16,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param))) |
class Queue:
def __init__(self) -> None:
self._queue = []
def insert(self, val: int) -> None:
self._queue.append(val)
def pop(self) -> None:
self._queue.pop(0)
def __str__(self):
return "{}".format(self._queue)
def __len__(self):
return len(self._queue)
if __name__ == "__main__":
queue = Queue()
queue.print()
queue.insert(10)
queue.insert(53)
queue.pop()
queue.insert(48)
queue.print()
print(len(queue))
|
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def minimalExecTime(self, root: TreeNode) -> float:
# @param n: 并行数目
# @return [0] 执行完当前节点的最小耗时
# [1] 当前 node 为根的时间串行之和
def dfs(root, n):
if root == None:
return 0, 0
leftMinTime, leftSumTime = dfs(root.left, n)
rightMinTime, rightSumTime = dfs(root.right, n)
sumTime = leftSumTime + rightSumTime
minTime = max(leftMinTime, rightMinTime, sumTime/2) + root.val
return minTime, sumTime + root.val
result, _ = dfs(root, 2)
return result
n1 = TreeNode(1)
n2 = TreeNode(3)
n3 = TreeNode(2)
n4 = TreeNode(4)
n5 = TreeNode(4)
n1.left = n2
n1.right = n3
n3.left = n4
n3.right = n5
s = Solution()
result = s.minimalExecTime(n1)
print(result)
|
class DeployResult(object):
def __init__(self, vm_name, vm_uuid, cloud_provider_resource_name, autoload,
inbound_ports, deployed_app_attributes, deployed_app_address,
public_ip, resource_group, extension_time_out, vm_details_data):
"""
:param str vm_name: The name of the virtual machine
:param uuid uuid: The UUID
:param str cloud_provider_resource_name: The Cloud Provider resource name
:param boolean autoload:
:param str inbound_ports:
:param [dict] deployed_app_attributes:
:param str deployed_app_address:
:param str public_ip:
:param bool extension_time_out:
:return:
"""
self.resource_group = resource_group
self.inbound_ports = inbound_ports
self.vm_name = vm_name
self.vm_uuid = vm_uuid
self.cloud_provider_resource_name = cloud_provider_resource_name
self.auto_power_off = False
self.wait_for_ip = False
self.auto_delete = True
self.autoload = autoload
self.deployed_app_attributes = deployed_app_attributes
self.deployed_app_address = deployed_app_address
self.public_ip = public_ip
self.extension_time_out = extension_time_out
self.vm_details_data = vm_details_data
|
# -*- coding: utf-8 -*-
# -------------------------------------
# basic unit
# -------------------------------------
PT = 1.0 # basic unit
ITP = 72.0 # inch to point
MAJOR_DIST = 5.0 * PT # significant distance exists between two block lines
MINOR_DIST = 1.0 * PT # small distance
TINY_DIST = 0.5 * PT # very small distance
FACTOR_SAME = 0.99
FACTOR_ALMOST = 0.95
FACTOR_MOST = 0.90
FACTOR_MAJOR = 0.75
FACTOR_A_HALF = 0.5
FACTOR_A_FEW = 0.1
FACTOR_FEW = 0.01
# -------------------------------------
# docx
# -------------------------------------
HIDDEN_W_BORDER = 0.0 # do not show border
MIN_LINE_SPACING = 0.7 # minimum line spacing available in MS word
# -------------------------------------
# font name mapping
# -------------------------------------
# special process on the key:
# - upper case
# - delete blanks, '-', '_'
DICT_FONTS = {
'SIMSUN': '宋体',
'SIMHEI': '黑体',
'MICROSOFTYAHEI': '微软雅黑',
'MICROSOFTJHENGHEI': '微软正黑体',
'NSIMSUN': '新宋体',
'PMINGLIU': '新细明体',
'MINGLIU': '细明体',
'DFKAISB': '标楷体', # 'DFKAI-SB'
'FANGSONG': '仿宋',
'KAITI': '楷体',
'FANGSONGGB2312': '仿宋_GB2312', # FANGSONG_GB2312
'KAITIGB2312': '楷体_GB2312', # KAITI_GB2312
'LISU': '隶书',
'YOUYUAN': '幼圆',
'STXIHEI': '华文细黑',
'STKAITI': '华文楷体',
'STSONG': '华文宋体',
'STZHONGSONG': '华文中宋',
'STFANGSONG': '华文仿宋',
'FZSHUTI': '方正舒体',
'FZYAOTI': '方正姚体',
'STCAIYUN': '华文彩云',
'STHUPO': '华文琥珀',
'STLITI': '华文隶书',
'STXINGKAI': '华文行楷',
'STXINWEI': '华文新魏',
'ARIALNARROW': 'Arial Narrow'
} |
"""
readtransaction.py
Description:
This class keeps track of keys for which a write
operation is still pending when a client wants
to perform a read operation.
It also contains helper functions to easily store
(pending) writes and return the values corresponding
to those keys once no more keys are pending.
"""
class ReadTransaction():
def __init__(self, addr):
self.n_keys = 0
self.n_pending = 0
self.keys = []
self.values = {}
self.write_orders = {}
self.addr = addr
self.pending = []
# Adds a key to the list of pending keys
def add_pending(self, key):
self.pending.append(key)
self.n_pending += 1
self.keys.append(key)
# Adds a key-value pair, unless it's not pending
def add_pair(self, key, value, write_order, pending=False):
self.n_keys += 1
self.values[key] = value
self.write_orders[key] = write_order
if pending:
self.n_pending -= 1
else:
self.keys.append(key)
return not self.n_pending
# Returns the key-value pairs and their corresponding write order
def return_data(self):
return_values = []
return_write_orders = []
if self.n_keys == 1:
return_values = self.values[self.keys[0]]
return_write_orders = self.write_orders[self.keys[0]]
else:
for k in self.keys:
return_values.append(self.values[k])
return_write_orders.append(self.write_orders[k])
# Data used for read_result message
data = {
"type": "read_result",
"key": self.keys,
"value": return_values,
"order_index": return_write_orders
}
return data
|
class PreRequisites:
def __init__(self, course_list=None):
self.course_list = course_list
|
#!/usr/local/bin/python3
def soma_1(x, y):
return x + y
def soma_2(x, y, z):
return x + y + z
def soma(*numeros):
return sum(numeros)
if __name__ == '__main__':
print(soma_1(10, 10))
print(soma_2(10, 10, 10))
# packing
print(soma(10, 10, 10, 10))
# unpacking
list_nums = [10, 20]
print(soma_1(*list_nums))
tuple_nums = (10, 20)
print(soma_1(*tuple_nums))
|
class ElementMulticlassFilter(ElementQuickFilter, IDisposable):
"""
A filter used to match elements by their class,where more than one class of element may be passed.
ElementMulticlassFilter(typeList: IList[Type],inverted: bool)
ElementMulticlassFilter(typeList: IList[Type])
"""
def Dispose(self):
""" Dispose(self: ElementFilter,A_0: bool) """
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: ElementFilter,disposing: bool) """
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, typeList, inverted=None):
"""
__new__(cls: type,typeList: IList[Type],inverted: bool)
__new__(cls: type,typeList: IList[Type])
"""
pass
|
'''Escreva um programa que lê um número não determinados de valores a, todos inteiros e positivos, um de cada vez, e
calcule e escreva a média aritmética dos valores lidos, a quantidade de valores pares, a quantidade de valores ímpares, a
percentagem de valores pares e a percentagem de valores ímpares.'''
num = int(input('Total de valores: '))
soma = 0
media = 0
vp = 0
vi = 0
ppar = 0
pimpar = 0
for c in range(1,num + 1):
c = int(input(f'Digite o {c}º valor: '))
soma += c
if c % 2 == 0:
vp += 1
elif c % 2 == 1:
vi +=1
print(f'A média aritmética entre os calores lidos é: {soma / num}')
print(f'A quantidade de Pares: {vp}')
print(f'A quantidade de Impares: {vi}')
print(f'A porcentagem de valore pares é {(vp / num)*100} %')
print(f'A porcentagem de valore impares é {(vi / num)*100} %') |
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
m = {}
for i, n in enumerate(nums):
if (target-n) in m:
return [m[target-n], i]
m[n] = i
|
class CPU:
VECTOR_RESET = 0xFFFC # Reset Vector address.
def __init__(self, system):
self._system = system
self._debug_log = open("debug.log", "w")
def reset(self):
# Program Counter 16-bit, default to value located at the reset vector address.
self._pc = self._system.mmu.read_word(self.VECTOR_RESET)
#self._pc = 0xC000 # NES TEST Start point
# Stack Pointer 8-bit, ranges from 0x0100 to 0x01FF
self._sp = 0xFD
# Accumulator 8-bit
self._a = 0x00
# Index Register X 8-bit
self._x = 0x00
# Index Register Y 8-bit
self._y = 0x00
#### Processor Status Flags
# Carry - set if the last operation caused an overflow from bit 7, or an underflow from bit 0.
self._carry = False
# Zero - the result of the last operation was zero.
self._zero = False
# Interrupt Disable - set if the program executed an SEI instruction. It's cleared with a CLI instruction.
self._interrupt_disable = True
# Break Command - Set when a BRK instruction is hit and an interrupt has been generated to process it.
self._break_command = False
# Decimal Mode
self._decimal_mode = False
# Overflow - Set during arithmetic operations if the result has yielded an invalid 2's compliment result.
self._overflow = False
# Negative - Set if the result of the last operation had bit 7 set to a one.
self._negative = False
# Reset clock
self.clock = 0
def step(self):
# Fetch next instruction.
pc = self._pc
self._current_instruction = pc
# print(f"PC: {format(pc,'x').upper()} / SP: {format(self._sp,'x').upper()} / A: {format(self._a,'x').upper()} / X: {format(self._x,'x').upper()} / Y: {format(self._y,'x').upper()}")
self._debug_log.write(f"{format(pc,'x').upper()}\n")
op_code = self._get_next_byte()
# Decode op code.
instruction = self.decode_instruction(op_code)
# Execute instruction.
instruction(op_code)
def decode_instruction(self, op_code):
instructions = {
0x69: self.ADC, 0x65: self.ADC, 0x75: self.ADC, 0x6D: self.ADC, 0x7D: self.ADC, 0x79: self.ADC, 0x61: self.ADC, 0x71: self.ADC,
0x29: self.AND, 0x25: self.AND, 0x35: self.AND, 0x2D: self.AND, 0x3D: self.AND, 0x39: self.AND, 0x21: self.AND, 0x31: self.AND,
0x0A: self.ASL, 0x06: self.ASL, 0x16: self.ASL, 0x0E: self.ASL, 0x1E: self.ASL,
0x90: self.BCC, 0xB0: self.BCS, 0xF0: self.BEQ,
0x24: self.BIT, 0x2C: self.BIT,
0x30: self.BMI, 0xD0: self.BNE, 0x10: self.BPL, 0x00: self.BRK, 0x50: self.BVC, 0x70: self.BVS,
0x18: self.CLC, 0xD8: self.CLD, 0x58: self.CLI, 0xB8: self.CLV,
0xC9: self.CMP, 0xC5: self.CMP, 0xD5: self.CMP, 0xCD: self.CMP, 0xDD: self.CMP, 0xD9: self.CMP, 0xC1: self.CMP, 0xD1: self.CMP,
0xE0: self.CPX, 0xE4: self.CPX, 0xEC: self.CPX,
0xC0: self.CPY, 0xC4: self.CPY, 0xCC: self.CPY,
0xC6: self.DEC, 0xD6: self.DEC, 0xCE: self.DEC, 0xDE: self.DEC, 0xCA: self.DEX, 0x88: self.DEY,
0x49: self.EOR, 0x45: self.EOR, 0x55: self.EOR, 0x4D: self.EOR, 0x5D: self.EOR, 0x59: self.EOR, 0x41: self.EOR, 0x51: self.EOR,
0xE6: self.INC, 0xF6: self.INC, 0xEE: self.INC, 0xFE: self.INC, 0xE8: self.INX, 0xC8: self.INY,
0x4C: self.JMP, 0x6C: self.JMP, 0x20: self.JSR,
0xA9: self.LDA, 0xA5: self.LDA, 0xB5: self.LDA, 0xAD: self.LDA, 0xBD: self.LDA, 0xB9: self.LDA, 0xA1: self.LDA, 0xB1: self.LDA,
0xA2: self.LDX, 0xA6: self.LDX, 0xB6: self.LDX, 0xAE: self.LDX, 0xBE: self.LDX,
0xA0: self.LDY, 0xA4: self.LDY, 0xB4: self.LDY, 0xAC: self.LDY, 0xBC: self.LDY,
0x4A: self.LSR, 0x46: self.LSR, 0x56: self.LSR, 0x4E: self.LSR, 0x5E: self.LSR,
0xEA: self.NOP,
0x09: self.ORA, 0x05: self.ORA, 0x15: self.ORA, 0x0D: self.ORA, 0x1D: self.ORA, 0x19: self.ORA, 0x01: self.ORA, 0x11: self.ORA,
0x48: self.PHA, 0x08: self.PHP, 0x68: self.PLA, 0x28: self.PLP,
0x2A: self.ROL, 0x26: self.ROL, 0x36: self.ROL, 0x2E: self.ROL, 0x3E: self.ROL,
0x6A: self.ROR, 0x66: self.ROR, 0x76: self.ROR, 0x6E: self.ROR, 0x7E: self.ROR,
0x40: self.RTI, 0x60: self.RTS,
0xE9: self.SBC, 0xE5: self.SBC, 0xF5: self.SBC, 0xED: self.SBC, 0xFD: self.SBC, 0xF9: self.SBC, 0xE1: self.SBC, 0xF1: self.SBC,
0x38: self.SEC, 0xF8: self.SED, 0x78: self.SEI,
0x85: self.STA, 0x95: self.STA, 0x8D: self.STA, 0x9D: self.STA, 0x99: self.STA, 0x81: self.STA, 0x91: self.STA,
0x86: self.STX, 0x96: self.STX, 0x8E: self.STX,
0x84: self.STY, 0x94: self.STY, 0x8C: self.STY,
0xAA: self.TAX, 0xA8: self.TAY, 0xBA: self.TSX, 0x8A: self.TXA, 0x9A: self.TXS, 0x98: self.TYA
}
instruction = instructions.get(op_code, None)
if (instruction == None):
raise RuntimeError(f"No instruction found: {hex(op_code)}")
return instruction
def _get_next_byte(self):
value = self._system.mmu.read_byte(self._pc)
self._pc += 1
return value
def _get_next_word(self):
lo = self._get_next_byte()
hi = self._get_next_byte()
return (hi<<8)+lo
def _set_status_flag(self, byte):
self._negative = byte&0x80 > 0
self._overflow = byte&0x40 > 0
self._decimal_mode = byte&0x08 > 0
self._interrupt_disable = byte&0x04 > 0
self._zero = byte&0x02 > 0
self._carry = byte&0x01 > 0
def _get_status_flag(self):
value = 0
value |= 0x80 if (self._negative) else 0
value |= 0x40 if (self._overflow) else 0
value |= 0x08 if (self._decimal_mode) else 0
value |= 0x04 if (self._interrupt_disable) else 0
value |= 0x02 if (self._zero) else 0
value |= 0x01 if (self._carry) else 0
return value
# Pushes a byte onto the stack.
def push(self, value):
self._system.mmu.write_byte(0x0100 + self._sp, value)
self._sp = (self._sp-1)&0xFF
# Pulls the next byte off the stack.
def pull(self):
self._sp = (self._sp+1)&0xFF
value = self._system.mmu.read_byte(0x0100 + self._sp)
return value
###############################################################################
# Address Mode Helpers
###############################################################################
def _get_address_at_zeropage(self):
return self._get_next_byte()
def _get_address_at_zeropage_x(self):
return (self._get_next_byte() + self._x)&0xFF
def _get_address_at_zeropage_y(self):
return (self._get_next_byte() + self._y)&0xFF
def _get_address_at_absolute(self):
return self._get_next_word()
def _get_address_at_absolute_x(self):
return self._get_next_word() + self._x
def _get_address_at_absolute_y(self):
return self._get_next_word() + self._y
def _get_address_at_indirect(self):
return self._system.mmu.read_word(self._get_next_byte())
def _get_address_at_indirect_x(self):
m = self._get_next_byte()
hi = self._system.mmu.read_byte((m + 1 + self._x)&0xFF)
lo = self._system.mmu.read_byte((m + self._x)&0xFF)
return (hi<<8)+lo
def _get_address_at_indirect_y(self):
return (self._system.mmu.read_word(self._get_next_byte()) + self._y)&0xFFFF
def _get_value_at_zeropage(self):
return self._system.mmu.read_byte(self._get_address_at_zeropage())
def _get_value_at_zeropage_x(self):
return self._system.mmu.read_byte(self._get_address_at_zeropage_x())
def _get_value_at_absolute(self):
return self._system.mmu.read_byte(self._get_address_at_absolute())
def _get_value_at_absolute_x(self):
return self._system.mmu.read_byte(self._get_address_at_absolute_x())
def _get_value_at_absolute_y(self):
return self._system.mmu.read_byte(self._get_address_at_absolute_y())
def _get_value_at_indirect_x(self):
return self._system.mmu.read_byte(self._get_address_at_indirect_x())
def _get_value_at_indirect_y(self):
return self._system.mmu.read_byte(self._get_address_at_indirect_y())
###############################################################################
# Instructions
# TODO: Implement * modifiers to instruction timing. i.e. add 1 if page boundary is crossed.
###############################################################################
def ADC(self, op_code):
# Add Memory to Accumulator with Carry
# A + M + C -> A, C N Z C I D V
# + + + - - +
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate ADC #oper 69 2 2
# zeropage ADC oper 65 2 3
# zeropage,X ADC oper,X 75 2 4
# absolute ADC oper 6D 3 4
# absolute,X ADC oper,X 7D 3 4*
# absolute,Y ADC oper,Y 79 3 4*
# (indirect,X) ADC (oper,X) 61 2 6
# (indirect),Y ADC (oper),Y 71 2 5*
value = None
cycles = None
if (op_code == 0x69): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0x65): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0x75): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0x6D): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0x7D): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
elif (op_code == 0x79): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
elif (op_code == 0x61): # (indirect,X)
value = self._get_value_at_indirect_x()
cycles = 6
elif (op_code == 0x71): # (indirect),Y
value = self._get_value_at_indirect_y()
cycles = 5
else:
raise RuntimeError(f"Unknown op code: {op_code}")
result = self._a + value + (1 if self._carry == True else 0)
self._carry = result > 0xFF
# More info on source: https://stackoverflow.com/a/29224684
self._overflow = ~(self._a ^ value) & (self._a ^ result) & 0x80
self._a = result&0xFF
self._negative = (self._a>>7) == 1
self._zero = self._a == 0
self._system.consume_cycles(cycles)
def AND(self, op_code):
# AND Memory with Accumulator
# A AND M -> A N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate AND #oper 29 2 2
# zeropage AND oper 25 2 3
# zeropage,X AND oper,X 35 2 4
# absolute AND oper 2D 3 4
# absolute,X AND oper,X 3D 3 4*
# absolute,Y AND oper,Y 39 3 4*
# (indirect,X) AND (oper,X) 21 2 6
# (indirect),Y AND (oper),Y 31 2 5*
value = None
cycles = None
if (op_code == 0x29): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0x25): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0x35): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0x2D): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0x3D): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
elif (op_code == 0x39): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
elif (op_code == 0x21): # (indirect,X)
value = self._get_value_at_indirect_x()
cycles = 6
elif (op_code == 0x31): # (indirect),Y
value = self._get_value_at_indirect_y()
cycles = 5
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._a = (self._a&value)&0xFF
self._negative = (self._a&0x80) > 0
self._zero = self._a == 0
self._system.consume_cycles(cycles)
def ASL(self, op_code):
# Shift Left One Bit (Memory or Accumulator)
# C <- [76543210] <- 0 N Z C I D V
# + + + - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# accumulator ASL A 0A 1 2
# zeropage ASL oper 06 2 5
# zeropage,X ASL oper,X 16 2 6
# absolute ASL oper 0E 3 6
# absolute,X ASL oper,X 1E 3 7
address = None
cycles = None
if (op_code == 0x0A): # accumulator
self._carry = self._a&0x80 > 0
self._a = (self._a<<1)&0xFF
self._negative = self._a&0x80 > 0
self._zero = self._a == 0
cycles = 2
return
elif (op_code == 0x06): # zeropage
address = self._get_address_at_zeropage()
cycles = 5
elif (op_code == 0x16): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 6
elif (op_code == 0x0E): # absolute
address = self._get_address_at_absolute()
cycles = 6
elif (op_code == 0x1E): # absolute,X
address = self._get_address_at_absolute_x()
cycles = 7
else:
raise RuntimeError(f"Unknown op code: {op_code}")
value = self._system.mmu.read_byte(address)
self._carry = value&0x80 > 0
value = (value<<1)&0xFF
self._negative = value&0x80 > 0
self._zero = value == 0
self._system.mmu.write_byte(address, value)
self._system.consume_cycles(cycles)
def BCC(self, op_code):
# Branch on Carry Clear
# branch on C = 0 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BCC oper 90 2 2**
offset = self._get_next_byte()
if (not self._carry):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def BCS(self, op_code):
# Branch on Carry Set
# branch on C = 1 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BCS oper B0 2 2**
offset = self._get_next_byte()
if (self._carry):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def BEQ(self, op_code):
# Branch on Result Zero
# branch on Z = 1 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BEQ oper F0 2 2**
offset = self._get_next_byte()
if (self._zero):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def BIT(self, op_code):
# Test Bits in Memory with Accumulator
# bits 7 and 6 of operand are transfered to bit 7 and 6 of SR (N,V);
# the zeroflag is set to the result of operand AND accumulator.
# A AND M, M7 -> N, M6 -> V N Z C I D V
# M7 + - - - M6
# addressing assembler opc bytes cyles
# --------------------------------------------
# zeropage BIT oper 24 2 3
# absolute BIT oper 2C 3 4
value = None
cycles = None
if (op_code == 0x24): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0x2C): # absolute
value = self._get_value_at_absolute()
cycles = 4
self._negative = value&0x80 > 0
self._overflow = value&0x40 > 0
value &= self._a
self._zero = value == 0
self._system.consume_cycles(cycles)
def BMI(self, op_code):
# Branch on Result Minus
# branch on N = 1 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BMI oper 30 2 2**
offset = self._get_next_byte()
if (self._negative):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def BNE(self, op_code):
# Branch on Result not Zero
# branch on Z = 0 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BNE oper D0 2 2**
offset = self._get_next_byte()
if (not self._zero):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def BPL(self, op_code):
# Branch on Result Plus
# branch on N = 0 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BPL oper 10 2 2**
offset = self._get_next_byte()
if (not self._negative):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def BRK(self, op_code):
# Force Break
# interrupt, N Z C I D V
# push PC+2, push SR - - - 1 - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied BRK 00 1 7
raise NotImplementedError()
def BVC(self, op_code):
# Branch on Overflow Clear
# branch on V = 0 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BVC oper 50 2 2**
offset = self._get_next_byte()
if (not self._overflow):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def BVS(self, op_code):
# Branch on Overflow Set
# branch on V = 1 N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# relative BVC oper 70 2 2**
offset = self._get_next_byte()
if (self._overflow):
if (offset > 127):
offset = -((~offset+1)&255) # Signed byte
self._pc += offset
cycles = 2
def CLC(self, op_code):
# Clear Carry Flag
# 0 -> C N Z C I D V
# - - 0 - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied CLC 18 1 2
self._carry = False
cycles = 2
def CLD(self, op_code):
# Clear Decimal Mode
# 0 -> D N Z C I D V
# - - - - 0 -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied CLD D8 1 2
self._decimal_mode = False
cycles = 2
def CLI(self, op_code):
# Clear Interrupt Disable Bit
# 0 -> I N Z C I D V
# - - - 0 - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied CLI 58 1 2
self._interrupt_disable = False
cycles = 2
def CLV(self, op_code):
# Clear Overflow Flag
# 0 -> V N Z C I D V
# - - - - - 0
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied CLV B8 1 2
self._overflow = False
cycles = 2
def CMP(self, op_code):
# Compare Memory with Accumulator
# A - M N Z C I D V
# + + + - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate CMP #oper C9 2 2
# zeropage CMP oper C5 2 3
# zeropage,X CMP oper,X D5 2 4
# absolute CMP oper CD 3 4
# absolute,X CMP oper,X DD 3 4*
# absolute,Y CMP oper,Y D9 3 4*
# (indirect,X) CMP (oper,X) C1 2 6
# (indirect),Y CMP (oper),Y D1 2 5*
value = None
cycles = None
if (op_code == 0xC9): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0xC5): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0xD5): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0xCD): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0xDD): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
elif (op_code == 0xD9): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
elif (op_code == 0xC1): # (indirect,X)
value = self._get_value_at_indirect_x()
cycles = 6
elif (op_code == 0xD1): # (indirect),Y
value = self._get_value_at_indirect_y()
cycles = 5
else:
raise RuntimeError(f"Unknown op code: {op_code}")
result = (self._a - value)&0xFF
self._carry = self._a >= value
self._zero = self._a == value
self._negative = result&0x80 > 0
self._system.consume_cycles(cycles)
def CPX(self, op_code):
# Compare Memory and Index X
# X - M N Z C I D V
# + + + - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate CPX #oper E0 2 2
# zeropage CPX oper E4 2 3
# absolute CPX oper EC 3 4
value = None
cycles = None
if (op_code == 0xE0): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0xE4): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0xEC): # absolute
value = self._get_value_at_absolute()
cycles = 4
else:
raise RuntimeError(f"Unknown op code: {op_code}")
result = (self._x - value)&0xFF
self._carry = self._x >= value
self._zero = self._x == value
self._negative = result&0x80 > 0
self._system.consume_cycles(cycles)
def CPY(self, op_code):
# Compare Memory and Index Y
# Y - M N Z C I D V
# + + + - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate CPY #oper C0 2 2
# zeropage CPY oper C4 2 3
# absolute CPY oper CC 3 4
value = None
cycles = None
if (op_code == 0xC0): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0xC4): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0xCC): # absolute
value = self._get_value_at_absolute()
cycles = 4
else:
raise RuntimeError(f"Unknown op code: {op_code}")
result = (self._y - value)&0xFF
self._carry = self._y >= value
self._zero = self._y == value
self._negative = result&0x80 > 0
self._system.consume_cycles(cycles)
def DEC(self, op_code):
# Decrement Memory by One
# M - 1 -> M N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# zeropage DEC oper C6 2 5
# zeropage,X DEC oper,X D6 2 6
# absolute DEC oper CE 3 3
# absolute,X DEC oper,X DE 3 7
address = None
cycles = None
if (op_code == 0xC6): # zeropage
address = self._get_address_at_zeropage()
cycles = 5
elif (op_code == 0xD6): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 6
elif (op_code == 0xCE): # absolute
address = self._get_address_at_absolute()
cycles = 3
elif (op_code == 0xDE): # absolute,X
address = self._get_address_at_absolute_x()
cycles = 7
else:
raise RuntimeError(f"Unknown op code: {op_code}")
value = (self._system.mmu.read_byte(address)-1)&0xFF
self._negative = value&0x80 > 1
self._zero = value == 0
self._system.mmu.write_byte(address, value)
self._system.consume_cycles(cycles)
def DEX(self, op_code):
# Decrement Index X by One
# X - 1 -> X N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied DEC CA 1 2
self._x = (self._x - 1)&0xFF
self._negative = self._x&0x80 > 1
self._zero = self._x == 0
cycles = 2
def DEY(self, op_code):
# Decrement Index Y by One
# Y - 1 -> Y N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied DEC 88 1 2
self._y = (self._y - 1)&0xFF
self._negative = self._y&0x80 > 1
self._zero = self._y == 0
cycles = 2
def EOR(self, op_code):
# Exclusive-OR Memory with Accumulator
# A EOR M -> A N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate EOR #oper 49 2 2
# zeropage EOR oper 45 2 3
# zeropage,X EOR oper,X 55 2 4
# absolute EOR oper 4D 3 4
# absolute,X EOR oper,X 5D 3 4*
# absolute,Y EOR oper,Y 59 3 4*
# (indirect,X) EOR (oper,X) 41 2 6
# (indirect),Y EOR (oper),Y 51 2 5*
value = None
cycles = None
if (op_code == 0x49): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0x45): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0x55): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0x4D): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0x5D): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
elif (op_code == 0x59): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
elif (op_code == 0x41): # (indirect,X)
value = self._get_value_at_indirect_x()
cycles = 6
elif (op_code == 0x51): # (indirect),Y
value = self._get_value_at_indirect_y()
cycles = 5
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._a ^= value
self._negative = (self._a>>7) == 1
self._zero = self._a == 0
self._system.consume_cycles(cycles)
def INC(self, op_code):
# Increment Memory by One
# M + 1 -> M N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# zeropage INC oper E6 2 5
# zeropage,X INC oper,X F6 2 6
# absolute INC oper EE 3 6
# absolute,X INC oper,X FE 3 7
address = None
cycles = None
if (op_code == 0xE6): # zeropage
address = self._get_address_at_zeropage()
cycles = 5
elif (op_code == 0xF6): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 6
elif (op_code == 0xEE): # absolute
address = self._get_address_at_absolute()
cycles = 6
elif (op_code == 0xFE): # absolute,X
address = self._get_address_at_absolute_x()
cycles = 7
else:
raise RuntimeError(f"Unknown op code: {op_code}")
value = (self._system.mmu.read_byte(address)+1)&0xFF
self._negative = (value>>7) == 1
self._zero = value == 0
self._system.mmu.write_byte(address, value)
self._system.consume_cycles(cycles)
def INX(self, op_code):
# Increment Index X by One
# X + 1 -> X N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied INX E8 1 2
self._x = (self._x + 1)&0xFF
self._negative = self._x&0x80 > 0
self._zero = self._x == 0
cycles = 2
def INY(self, op_code):
# Increment Index Y by One
# Y + 1 -> Y N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied INY C8 1 2
self._y = (self._y + 1)&0xFF
self._negative = self._y&0x80 > 0
self._zero = self._y == 0
cycles = 2
def JMP(self, op_code):
# Jump to New Location
# (PC+1) -> PCL N Z C I D V
# (PC+2) -> PCH - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# absolute JMP oper 4C 3 3
# indirect JMP (oper) 6C 3 5
address = None
cycles = None
if (op_code == 0x4C): # absolute
pcl = self._system.mmu.read_byte(self._pc)
pch = self._system.mmu.read_byte(self._pc+1)
address = (pch<<8)+pcl
cycles = 3
elif (op_code == 0x6C): # indirect
address = self._get_address_at_indirect()
cycles = 5
self._pc = address
self._system.consume_cycles(cycles)
def JSR(self, op_code):
# Jump to New Location Saving Return Address
# push (PC+2), N Z C I D V
# (PC+1) -> PCL - - - - - -
# (PC+2) -> PCH
# addressing assembler opc bytes cyles
# --------------------------------------------
# absolute JSR oper 20 3 6
next_address = self._pc+1
self.push(next_address>>8) # HI byte
self.push(next_address&0xFF) # LO byte
self._pc = self._get_address_at_absolute()
cycles = 6
def LDA(self, op_code):
# Load Accumulator with Memory
# M -> A N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate LDA #oper A9 2 2
# zeropage LDA oper A5 2 3
# zeropage,X LDA oper,X B5 2 4
# absolute LDA oper AD 3 4
# absolute,X LDA oper,X BD 3 4*
# absolute,Y LDA oper,Y B9 3 4*
# (indirect,X) LDA (oper,X) A1 2 6
# (indirect),Y LDA (oper),Y B1 2 5*
value = None
cycles = None
if (op_code == 0xA9): # immedidate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0xA5): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0xB5): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0xAD): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0xBD): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
elif (op_code == 0xB9): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
elif (op_code == 0xA1): # (indirect,X)
value = self._get_value_at_indirect_x()
cycles = 6
elif (op_code == 0xB1): # (indirect),Y
value = self._get_value_at_indirect_y()
cycles = 5
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._negative = (value&0x80) > 0
self._zero = value == 0
self._a = value
self._system.consume_cycles(cycles)
def LDX(self, op_code):
# Load Index X with Memory
# M -> X N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate LDX #oper A2 2 2
# zeropage LDX oper A6 2 3
# zeropage,Y LDX oper,Y B6 2 4
# absolute LDX oper AE 3 4
# absolute,Y LDX oper,Y BE 3 4*
value = None
cycles = None
if (op_code == 0xA2): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0xA6): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0xB6): # zeropage,Y
value = self._get_value_at_zeropage_y()
cycles = 4
elif (op_code == 0xAE): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0xBE): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._negative = (value&0x80) > 0
self._zero = value == 0
self._x = value
self._system.consume_cycles(cycles)
def LDY(self, op_code):
# Load Index Y with Memory
# M -> Y N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate LDY #oper A0 2 2
# zeropage LDY oper A4 2 3
# zeropage,X LDY oper,X B4 2 4
# absolute LDY oper AC 3 4
# absolute,X LDY oper,X BC 3 4*
value = None
cycles = None
if (op_code == 0xA0): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0xA4): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0xB4): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0xAC): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0xBC): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._negative = (value&0x80) > 0
self._zero = value == 0
self._y = value
self._system.consume_cycles(cycles)
def LSR(self, op_code):
# Shift One Bit Right (Memory or Accumulator)
# 0 -> [76543210] -> C N Z C I D V
# - + + - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# accumulator LSR A 4A 1 2
# zeropage LSR oper 46 2 5
# zeropage,X LSR oper,X 56 2 6
# absolute LSR oper 4E 3 6
# absolute,X LSR oper,X 5E 3 7
address = None
cycles = None
if (op_code == 0x4A): # accumulator
self._carry = (self._a&0x01) > 0
self._a >>= 1
self._negative = (self._a&0x80) > 0
self._zero = self._a == 0
cycles = 2
return
elif (op_code == 0x46): # zeropage
address = self._get_address_at_zeropage()
cycles = 5
elif (op_code == 0x56): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 6
elif (op_code == 0x4E): # absolute
address = self._get_address_at_absolute()
cycles = 6
elif (op_code == 0x5E): # absolute,X
address = self._get_address_at_absolute_x()
cycles = 7
else:
raise RuntimeError(f"Unknown op code: {op_code}")
value = self._system.mmu.read_byte(address)
self._carry = (value&0x80) > 0
value <<= 1
self._negative = (value&0x80) > 0
self._zero = value == 0
self._system.mmu.write_byte(address, value)
self._system.consume_cycles(cycles)
def NOP(self, op_code):
# No Operation
# --- N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied NOP EA 1 2
cycles = 2
def ORA(self, op_code):
# OR Memory with Accumulator
# A OR M -> A N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate ORA #oper 09 2 2
# zeropage ORA oper 05 2 3
# zeropage,X ORA oper,X 15 2 4
# absolute ORA oper 0D 3 4
# absolute,X ORA oper,X 1D 3 4*
# absolute,Y ORA oper,Y 19 3 4*
# (indirect,X) ORA (oper,X) 01 2 6
# (indirect),Y ORA (oper),Y 11 2 5*
value = None
cycles = None
if (op_code == 0x09): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0x05): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0x15): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0x0D): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0x1D): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
elif (op_code == 0x19): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
elif (op_code == 0x01): # (indirect,X)
value = self._get_value_at_indirect_x()
cycles = 6
elif (op_code == 0x11): # (indirect),Y
value = self._get_value_at_indirect_y()
cycles = 5
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._a = (self._a|value)&0xFF
self._negative = (self._a&0x80) > 0
self._zero = self._a == 0
self._system.consume_cycles(cycles)
def PHA(self, op_code):
# Push Accumulator on Stack
# push A N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied PHA 48 1 3
self.push(self._a)
cycles = 3
def PHP(self, op_code):
# Push Processor Status on Stack
# push SR N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied PHP 08 1 3
value = self._get_status_flag()
value |= 0x30 # Bits 5 and 4 are set when pushed by PHP
self.push(value)
cycles = 3
def PLA(self, op_code):
# Pull Accumulator from Stack
# pull A N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied PLA 68 1 4
self._a = self.pull()
self._negative = self._a&0x80 > 0
self._zero = self._a == 0
cycles = 4
def PLP(self, op_code):
# Pull Processor Status from Stack
# pull SR N Z C I D V
# from stack
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied PHP 28 1 4
self._set_status_flag(self.pull())
cycles = 4
def ROL(self, op_code):
# Rotate One Bit Left (Memory or Accumulator)
# C <- [76543210] <- C N Z C I D V
# + + + - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# accumulator ROL A 2A 1 2
# zeropage ROL oper 26 2 5
# zeropage,X ROL oper,X 36 2 6
# absolute ROL oper 2E 3 6
# absolute,X ROL oper,X 3E 3 7
address = None
cycles = None
if (op_code == 0x2A): # accumulator
carryOut = True if (self._a&0x80 > 0) else False
self._a = ((self._a<<1) + (1 if (self._carry) else 0))&0xFF
self._carry = carryOut
self._negative = self._a&0x80 > 0
self._zero = self._a == 0
cycles = 2
return
elif (op_code == 0x26): # zeropage
address = self._get_address_at_zeropage()
cycles = 5
elif (op_code == 0x36): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 6
elif (op_code == 0x2E): # absolute
address = self._get_address_at_absolute()
cycles = 6
elif (op_code == 0x3E): # absolute,X
address = self._get_address_at_absolute_x()
cycles = 7
else:
raise RuntimeError(f"Unknown op code: {op_code}")
value = self._system.mmu.read_byte(address)
carryOut = True if (value&0x80 > 0) else False
value = ((value<<1) + (1 if (self._carry) else 0))&0xFF
self._carry = carryOut
self._system.mmu.write_byte(address, value)
self._negative = value&0x80 > 0
self._zero = value == 0
self._system.consume_cycles(cycles)
def ROR(self, op_code):
# Rotate One Bit Right (Memory or Accumulator)
# C -> [76543210] -> C N Z C I D V
# + + + - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# accumulator ROR A 6A 1 2
# zeropage ROR oper 66 2 5
# zeropage,X ROR oper,X 76 2 6
# absolute ROR oper 6E 3 6
# absolute,X ROR oper,X 7E 3 7
address = None
cycles = None
if (op_code == 0x6A): # accumulator
carryOut = True if (self._a&0x01 > 0) else False
self._a = ((self._a>>1) + (0x80 if (self._carry) else 0))&0xFF
self._carry = carryOut
self._negative = self._a&0x80 > 0
self._zero = self._a == 0
cycles = 2
return
elif (op_code == 0x66): # zeropage
address = self._get_address_at_zeropage()
cycles = 5
elif (op_code == 0x76): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 6
elif (op_code == 0x6E): # absolute
address = self._get_address_at_absolute()
cycles = 6
elif (op_code == 0x7E): # absolute,X
address = self._get_address_at_absolute_x()
cycles = 7
else:
raise RuntimeError(f"Unknown op code: {op_code}")
value = self._system.mmu.read_byte(address)
carryOut = True if (value&0x01 > 0) else False
value = ((value>>1) + (0x80 if (self._carry) else 0))&0xFF
self._carry = carryOut
self._system.mmu.write_byte(address, value)
self._negative = value&0x80 > 0
self._zero = value == 0
self._system.consume_cycles(cycles)
def RTI(self, op_code):
# Return from Interrupt
# pull SR, pull PC N Z C I D V
# from stack
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied RTI 40 1 6
self._set_status_flag(self.pull())
pc_lo = self.pull()
pc_hi = self.pull()
self._pc = ((pc_hi<<8) + pc_lo)&0xFFFF
cycles = 6
def RTS(self, op_code):
# Return from Subroutine
# pull PC, PC+1 -> PC N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied RTS 60 1 6
pc_lo = self.pull()
pc_hi = self.pull()
self._pc = ((pc_hi<<8) + pc_lo + 1)&0xFFFF
cycles = 6
def SBC(self, op_code):
# Subtract Memory from Accumulator with Borrow
# A - M - C -> A N Z C I D V
# + + + - - +
# addressing assembler opc bytes cyles
# --------------------------------------------
# immediate SBC #oper E9 2 2
# zeropage SBC oper E5 2 3
# zeropage,X SBC oper,X F5 2 4
# absolute SBC oper ED 3 4
# absolute,X SBC oper,X FD 3 4*
# absolute,Y SBC oper,Y F9 3 4*
# (indirect,X) SBC (oper,X) E1 2 6
# (indirect),Y SBC (oper),Y F1 2 5*
value = None
cycles = None
if (op_code == 0xE9): # immediate
value = self._get_next_byte()
cycles = 2
elif (op_code == 0xE5): # zeropage
value = self._get_value_at_zeropage()
cycles = 3
elif (op_code == 0xF5): # zeropage,X
value = self._get_value_at_zeropage_x()
cycles = 4
elif (op_code == 0xED): # absolute
value = self._get_value_at_absolute()
cycles = 4
elif (op_code == 0xFD): # absolute,X
value = self._get_value_at_absolute_x()
cycles = 4
elif (op_code == 0xF9): # absolute,Y
value = self._get_value_at_absolute_y()
cycles = 4
elif (op_code == 0xE1): # (indirect,X)
value = self._get_value_at_indirect_x()
cycles = 6
elif (op_code == 0xF1): # (indirect),Y
value = self._get_value_at_indirect_y()
cycles = 5
else:
raise RuntimeError(f"Unknown op code: {op_code}")
# Invert value and run through same logic as ADC.
value ^= 0xFF
result = self._a + value + (1 if self._carry == True else 0)
self._carry = result > 0xFF
# More info on source: https://stackoverflow.com/a/29224684
self._overflow = ~(self._a ^ value) & (self._a ^ result) & 0x80
self._a = result&0xFF
self._negative = self._a&0x80 > 1
self._zero = self._a == 0
self._system.consume_cycles(cycles)
def SEC(self, op_code):
# Set Carry Flag
# 1 -> C N Z C I D V
# - - 1 - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied SEC 38 1 2
self._carry = True
cycles = 2
def SED(self, op_code):
# Set Decimal Flag
# 1 -> D N Z C I D V
# - - - - 1 -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied SED F8 1 2
self._decimal_mode = True
cycles = 2
def SEI(self, op_code):
# Set Interrupt Disable Status
# 1 -> I N Z C I D V
# - - - 1 - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied SEI 78 1 2
self._interrupt_disable = True
cycles = 2
def STA(self, op_code):
# Store Accumulator in Memory
# A -> M N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# zeropage STA oper 85 2 3
# zeropage,X STA oper,X 95 2 4
# absolute STA oper 8D 3 4
# absolute,X STA oper,X 9D 3 5
# absolute,Y STA oper,Y 99 3 5
# (indirect,X) STA (oper,X) 81 2 6
# (indirect),Y STA (oper),Y 91 2 6
address = None
cycles = None
if (op_code == 0x85): # zeropage
address = self._get_address_at_zeropage()
cycles = 3
elif (op_code == 0x95): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 4
elif (op_code == 0x8D): # absolute
address = self._get_address_at_absolute()
cycles = 4
elif (op_code == 0x9D): # absolute,X
address = self._get_address_at_absolute_x()
cycles = 5
elif (op_code == 0x99): # absolute,Y
address = self._get_address_at_absolute_y()
cycles = 5
elif (op_code == 0x81): # (indirect,X)
address = self._get_address_at_indirect_x()
cycles = 6
elif (op_code == 0x91): # (indirect),Y
address = self._get_address_at_indirect_y()
cycles = 6
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._system.mmu.write_byte(address, self._a)
self._system.consume_cycles(cycles)
def STX(self, op_code):
# Store Index X in Memory
# X -> M N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# zeropage STX oper 86 2 3
# zeropage,Y STX oper,Y 96 2 4
# absolute STX oper 8E 3 4
address = None
cycles = None
if (op_code == 0x86): # zeropage
address = self._get_address_at_zeropage()
cycles = 3
elif (op_code == 0x96): # zeropage,Y
address = self._get_address_at_zeropage_y()
cycles = 4
elif (op_code == 0x8E): # absolute
address = self._get_address_at_absolute()
cycles = 4
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._system.mmu.write_byte(address, self._x)
self._system.consume_cycles(cycles)
def STY(self, op_code):
# Sore Index Y in Memory
# Y -> M N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# zeropage STY oper 84 2 3
# zeropage,X STY oper,X 94 2 4
# absolute STY oper 8C 3 4
address = None
cycles = None
if (op_code == 0x84): # zeropage
address = self._get_address_at_zeropage()
cycles = 3
elif (op_code == 0x94): # zeropage,X
address = self._get_address_at_zeropage_x()
cycles = 4
elif (op_code == 0x8C): # absolute
address = self._get_address_at_absolute()
cycles = 4
else:
raise RuntimeError(f"Unknown op code: {op_code}")
self._system.mmu.write_byte(address, self._y)
self._system.consume_cycles(cycles)
def TAX(self, op_code):
# Transfer Accumulator to Index X
# A -> X N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied TAX AA 1 2
self._x = self._a
self._negative = (self._x>>7) > 0
self._zero = self._x == 0
cycles = 2
def TAY(self, op_code):
# Transfer Accumulator to Index Y
# A -> Y N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied TAY A8 1 2
self._y = self._a
self._negative = (self._y>>7) > 0
self._zero = self._y == 0
cycles = 2
def TSX(self, op_code):
# Transfer Stack Pointer to Index X
# SP -> X N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied TSX BA 1 2
self._x = self._sp
self._negative = (self._x>>7) > 0
self._zero = self._x == 0
cycles = 2
def TXA(self, op_code):
# Transfer Index X to Accumulator
# X -> A N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied TXA 8A 1 2
self._a = self._x
self._negative = (self._a>>7) > 0
self._zero = self._a == 0
cycles = 2
def TXS(self, op_code):
# Transfer Index X to Stack Register
# X -> SP N Z C I D V
# - - - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied TXS 9A 1 2
self._sp = self._x
cycles = 2
def TYA(self, op_code):
# Transfer Index Y to Accumulator
# Y -> A N Z C I D V
# + + - - - -
# addressing assembler opc bytes cyles
# --------------------------------------------
# implied TYA 98 1 2
self._a = self._y
self._negative = (self._a>>7) > 0
self._zero = self._a == 0
cycles = 2 |
# -*- coding: utf-8 -*-
"""
Created on Sat May 29 04:22:02 2021
@author: Septhiono
"""
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n").lower()
name2 = input("What is their name? \n").lower()
name3=name1+name2
true=name3.count('t')+name3.count('r')+name3.count('u')+name3.count('e')
love=name3.count('l')+name3.count('o')+name3.count('v')+name3.count('e')
score=int(str(true)+str(love))
if score<10 or score>90:
print(f"Your score is {score}, you go together like coke and mentos.")
elif 40<score<50:
print(f"Your score is {score}, you are alright together.")
else:
print(f"Your score is {score}.")
|
def greet_customer(grocery_store, special_item):
print("Welcome to "+ grocery_store + ".")
print("Our special is " + special_item + ".")
print("Have fun shopping!")
greet_customer("Stu's Staples", "papayas")
def mult_x_add_y(number, x, y):
print("Total: ", number * x + y)
mult_x_add_y(5, 2, 3)
mult_x_add_y(1, 3, 1) |
class TransitionId(object):
ClearReadout=0
Reset =1
Configure =2
Unconfigure =3
BeginRun =4
EndRun =5
BeginStep =6
EndStep =7
Enable =8
Disable =9
SlowUpdate =10
Unused_11 =11
L1Accept =12
NumberOf =13
|
MIN_MATCH = 4
STRING = 0x0
BYTE_ARR = 0x01
NUMERIC_INT = 0x02
NUMERIC_FLOAT = 0x03
NUMERIC_LONG = 0x04
NUMERIC_DOUBLE = 0x05
SECOND = 1000
HOUR = 60 * 60 * SECOND
DAY = 24 * HOUR
SECOND_ENCODING = 0x40
HOUR_ENCODING = 0x80
DAY_ENCODING = 0xC0
BLOCK_SIZE = 128
INDEX_OPTION_NONE = 0
INDEX_OPTION_DOCS = 1
INDEX_OPTION_DOCS_FREQS = 2
INDEX_OPTION_DOCS_FREQS_POSITIONS = 3
INDEX_OPTION_DOCS_FREQS_POSITIONS_OFFSETS = 4
DOC_VALUES_NUMERIC = 0
DOC_VALUES_BINARY = 1
DOC_VALUES_SORTED = 2
DOC_VALUES_SORTED_SET = 3
DOC_VALUES_SORTED_NUMERIC = 4
DOC_DELTA_COMPRESSED = 0
DOC_GCD_COMPRESSED = 1
DOC_TABLE_COMPRESSED = 2
DOC_MONOTONIC_COMPRESSED = 3
DOC_CONST_COMPRESSED = 4
DOC_SPARSE_COMPRESSED = 5
DOC_BINARY_FIXED_UNCOMPRESSED = 0
DOC_BINARY_VARIABLE_UNCOMPRESSED = 1
DOC_BINARY_PREFIX_COMPRESSED = 2
DOC_SORTED_WITH_ADDRESSES = 0
DOC_SORTED_SINGLE_VALUED = 1
DOC_SORTED_SET_TABLE = 2
STORE_TERMVECTOR = 0x1
OMIT_NORMS = 0x2
STORE_PAYLOADS = 0x4
ALL_VALUES_EQUAL = 0
PACKED = 0
PACKED_SINGLE_BLOCK = 1 |
# -*- coding: utf-8 -*-
"""
@date: 2020/9/10 上午11:21
@file: __init__.py
@author: zj
@description:
"""
|
def ficha(jogador='<Desconhecido>', gol = 0):
print(f'O Jogador {jogador} fez {gol} gols.')
name = str(input('Digite o Nome do Jogador: '))
#leitura de variável como string para realizar teste isnumeric() e validar
gols = str(input('Digite a quantidade de Gols no Campeonato: '))
if gols.isnumeric():
gols = int(gols)
else:
gols = 0
if name.strip() == '':
ficha(gol = gols)
else:
ficha(name, gols)
|
"""
Hao Ren
11 October, 2020
344. Reverse String
Python: One line solution. Just a joke.
"""
class Solution(object):
def reverseString(self, s):
"""
:type s: List[str]
:rtype: None Do not return anything, modify s in-place instead.
"""
s.reverse()
|
#encoding:utf-8
subreddit = 'ProsePorn'
t_channel = '@r_proseporn'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.